sqlite3.c 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.1. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqlite_config_rtthread.h **************************/
  29. #ifndef _SQLITE_CONFIG_RTTHREAD_H_
  30. #define _SQLITE_CONFIG_RTTHREAD_H_
  31. /*
  32. * SQLite compile macro
  33. */
  34. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  35. #define SQLITE_MINIMUM_FILE_DESCRIPTOR 0
  36. #endif
  37. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  38. #define SQLITE_OMIT_LOAD_EXTENSION 1
  39. #endif
  40. //#ifndef #define SQLITE_OMIT_WAL
  41. #define SQLITE_OMIT_WAL
  42. //#endif
  43. #ifndef SQLITE_RTTHREAD_NO_WIDE
  44. #define SQLITE_RTTHREAD_NO_WIDE 1
  45. #endif
  46. #ifndef SQLITE_ENABLE_LOCKING_STYLE
  47. #define SQLITE_ENABLE_LOCKING_STYLE 0
  48. #endif
  49. #ifndef SQLITE_DISABLE_LOCKING_STYLE
  50. #define SQLITE_DISABLE_LOCKING_STYLE 1
  51. #endif
  52. #ifndef SQLITE_TEMP_STORE
  53. #define SQLITE_TEMP_STORE 1
  54. #endif
  55. #ifndef SQLITE_THREADSAFE
  56. #define SQLITE_THREADSAFE 1
  57. #endif
  58. #ifndef HAVE_READLINE
  59. #define HAVE_READLINE 0
  60. #endif
  61. #ifndef NDEBUG
  62. #define NDEBUG
  63. #endif
  64. #ifndef _HAVE_SQLITE_CONFIG_H
  65. #define _HAVE_SQLITE_CONFIG_H
  66. #endif
  67. #ifndef BUILD_sqlite
  68. #define BUILD_sqlite
  69. #endif
  70. #ifndef SQLITE_OS_OTHER
  71. #define SQLITE_OS_OTHER 1
  72. #endif
  73. #ifndef SQLITE_OS_RTTHREAD
  74. #define SQLITE_OS_RTTHREAD 1
  75. #endif
  76. #endif
  77. /************** End of sqlite_config_rtthread.h ******************************/
  78. /************** Begin file sqlite3.h *****************************************/
  79. /*
  80. ** 2001 September 15
  81. **
  82. ** The author disclaims copyright to this source code. In place of
  83. ** a legal notice, here is a blessing:
  84. **
  85. ** May you do good and not evil.
  86. ** May you find forgiveness for yourself and forgive others.
  87. ** May you share freely, never taking more than you give.
  88. **
  89. *************************************************************************
  90. ** This header file defines the interface that the SQLite library
  91. ** presents to client programs. If a C-function, structure, datatype,
  92. ** or constant definition does not appear in this file, then it is
  93. ** not a published API of SQLite, is subject to change without
  94. ** notice, and should not be referenced by programs that use SQLite.
  95. **
  96. ** Some of the definitions that are in this file are marked as
  97. ** "experimental". Experimental interfaces are normally new
  98. ** features recently added to SQLite. We do not anticipate changes
  99. ** to experimental interfaces but reserve the right to make minor changes
  100. ** if experience from use "in the wild" suggest such changes are prudent.
  101. **
  102. ** The official C-language API documentation for SQLite is derived
  103. ** from comments in this file. This file is the authoritative source
  104. ** on how SQLite interfaces are suppose to operate.
  105. **
  106. ** The name of this file under configuration management is "sqlite.h.in".
  107. ** The makefile makes some minor changes to this file (such as inserting
  108. ** the version number) and changes its name to "sqlite3.h" as
  109. ** part of the build process.
  110. */
  111. #ifndef _SQLITE3_H_
  112. #define _SQLITE3_H_
  113. #include <stdarg.h> /* Needed for the definition of va_list */
  114. /*
  115. ** Make sure we can call this stuff from C++.
  116. */
  117. #if 0
  118. extern "C" {
  119. #endif
  120. #include <rtconfig.h>
  121. /*
  122. ** Add the ability to override 'extern'
  123. */
  124. #ifndef SQLITE_EXTERN
  125. # define SQLITE_EXTERN extern
  126. #endif
  127. #ifndef SQLITE_API
  128. # define SQLITE_API
  129. #endif
  130. /*
  131. ** These no-op macros are used in front of interfaces to mark those
  132. ** interfaces as either deprecated or experimental. New applications
  133. ** should not use deprecated interfaces - they are support for backwards
  134. ** compatibility only. Application writers should be aware that
  135. ** experimental interfaces are subject to change in point releases.
  136. **
  137. ** These macros used to resolve to various kinds of compiler magic that
  138. ** would generate warning messages when they were used. But that
  139. ** compiler magic ended up generating such a flurry of bug reports
  140. ** that we have taken it all out and gone back to using simple
  141. ** noop macros.
  142. */
  143. #define SQLITE_DEPRECATED
  144. #define SQLITE_EXPERIMENTAL
  145. /*
  146. ** Ensure these symbols were not defined by some previous header file.
  147. */
  148. #ifdef SQLITE_VERSION
  149. # undef SQLITE_VERSION
  150. #endif
  151. #ifdef SQLITE_VERSION_NUMBER
  152. # undef SQLITE_VERSION_NUMBER
  153. #endif
  154. /*
  155. ** CAPI3REF: Compile-Time Library Version Numbers
  156. **
  157. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  158. ** evaluates to a string literal that is the SQLite version in the
  159. ** format "X.Y.Z" where X is the major version number (always 3 for
  160. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  161. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  162. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  163. ** numbers used in [SQLITE_VERSION].)^
  164. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  165. ** be larger than the release from which it is derived. Either Y will
  166. ** be held constant and Z will be incremented or else Y will be incremented
  167. ** and Z will be reset to zero.
  168. **
  169. ** Since version 3.6.18, SQLite source code has been stored in the
  170. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  171. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  172. ** a string which identifies a particular check-in of SQLite
  173. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  174. ** string contains the date and time of the check-in (UTC) and an SHA1
  175. ** hash of the entire source tree.
  176. **
  177. ** See also: [sqlite3_libversion()],
  178. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  179. ** [sqlite_version()] and [sqlite_source_id()].
  180. */
  181. #define SQLITE_VERSION "3.8.1"
  182. #define SQLITE_VERSION_NUMBER 3008001
  183. #define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a"
  184. /*
  185. ** CAPI3REF: Run-Time Library Version Numbers
  186. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  187. **
  188. ** These interfaces provide the same information as the [SQLITE_VERSION],
  189. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  190. ** but are associated with the library instead of the header file. ^(Cautious
  191. ** programmers might include assert() statements in their application to
  192. ** verify that values returned by these interfaces match the macros in
  193. ** the header, and thus insure that the application is
  194. ** compiled with matching library and header files.
  195. **
  196. ** <blockquote><pre>
  197. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  198. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  199. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  200. ** </pre></blockquote>)^
  201. **
  202. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  203. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  204. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  205. ** function is provided for use in DLLs since DLL users usually do not have
  206. ** direct access to string constants within the DLL. ^The
  207. ** sqlite3_libversion_number() function returns an integer equal to
  208. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  209. ** a pointer to a string constant whose value is the same as the
  210. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  211. **
  212. ** See also: [sqlite_version()] and [sqlite_source_id()].
  213. */
  214. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  215. SQLITE_API const char *sqlite3_libversion(void);
  216. SQLITE_API const char *sqlite3_sourceid(void);
  217. SQLITE_API int sqlite3_libversion_number(void);
  218. /*
  219. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  220. **
  221. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  222. ** indicating whether the specified option was defined at
  223. ** compile time. ^The SQLITE_ prefix may be omitted from the
  224. ** option name passed to sqlite3_compileoption_used().
  225. **
  226. ** ^The sqlite3_compileoption_get() function allows iterating
  227. ** over the list of options that were defined at compile time by
  228. ** returning the N-th compile time option string. ^If N is out of range,
  229. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  230. ** prefix is omitted from any strings returned by
  231. ** sqlite3_compileoption_get().
  232. **
  233. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  234. ** and sqlite3_compileoption_get() may be omitted by specifying the
  235. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  236. **
  237. ** See also: SQL functions [sqlite_compileoption_used()] and
  238. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  239. */
  240. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  241. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  242. SQLITE_API const char *sqlite3_compileoption_get(int N);
  243. #endif
  244. /*
  245. ** CAPI3REF: Test To See If The Library Is Threadsafe
  246. **
  247. ** ^The sqlite3_threadsafe() function returns zero if and only if
  248. ** SQLite was compiled with mutexing code omitted due to the
  249. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  250. **
  251. ** SQLite can be compiled with or without mutexes. When
  252. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  253. ** are enabled and SQLite is threadsafe. When the
  254. ** [SQLITE_THREADSAFE] macro is 0,
  255. ** the mutexes are omitted. Without the mutexes, it is not safe
  256. ** to use SQLite concurrently from more than one thread.
  257. **
  258. ** Enabling mutexes incurs a measurable performance penalty.
  259. ** So if speed is of utmost importance, it makes sense to disable
  260. ** the mutexes. But for maximum safety, mutexes should be enabled.
  261. ** ^The default behavior is for mutexes to be enabled.
  262. **
  263. ** This interface can be used by an application to make sure that the
  264. ** version of SQLite that it is linking against was compiled with
  265. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  266. **
  267. ** This interface only reports on the compile-time mutex setting
  268. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  269. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  270. ** can be fully or partially disabled using a call to [sqlite3_config()]
  271. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  272. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  273. ** sqlite3_threadsafe() function shows only the compile-time setting of
  274. ** thread safety, not any run-time changes to that setting made by
  275. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  276. ** is unchanged by calls to sqlite3_config().)^
  277. **
  278. ** See the [threading mode] documentation for additional information.
  279. */
  280. SQLITE_API int sqlite3_threadsafe(void);
  281. /*
  282. ** CAPI3REF: Database Connection Handle
  283. ** KEYWORDS: {database connection} {database connections}
  284. **
  285. ** Each open SQLite database is represented by a pointer to an instance of
  286. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  287. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  288. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  289. ** and [sqlite3_close_v2()] are its destructors. There are many other
  290. ** interfaces (such as
  291. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  292. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  293. ** sqlite3 object.
  294. */
  295. typedef struct sqlite3 sqlite3;
  296. /*
  297. ** CAPI3REF: 64-Bit Integer Types
  298. ** KEYWORDS: sqlite_int64 sqlite_uint64
  299. **
  300. ** Because there is no cross-platform way to specify 64-bit integer types
  301. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  302. **
  303. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  304. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  305. ** compatibility only.
  306. **
  307. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  308. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  309. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  310. ** between 0 and +18446744073709551615 inclusive.
  311. */
  312. #ifdef SQLITE_INT64_TYPE
  313. typedef SQLITE_INT64_TYPE sqlite_int64;
  314. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  315. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  316. typedef __int64 sqlite_int64;
  317. typedef unsigned __int64 sqlite_uint64;
  318. #else
  319. typedef long long int sqlite_int64;
  320. typedef unsigned long long int sqlite_uint64;
  321. #endif
  322. typedef sqlite_int64 sqlite3_int64;
  323. typedef sqlite_uint64 sqlite3_uint64;
  324. /*
  325. ** If compiling for a processor that lacks floating point support,
  326. ** substitute integer for floating-point.
  327. */
  328. #ifdef SQLITE_OMIT_FLOATING_POINT
  329. # define double sqlite3_int64
  330. #endif
  331. /*
  332. ** CAPI3REF: Closing A Database Connection
  333. **
  334. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  335. ** for the [sqlite3] object.
  336. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  337. ** the [sqlite3] object is successfully destroyed and all associated
  338. ** resources are deallocated.
  339. **
  340. ** ^If the database connection is associated with unfinalized prepared
  341. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  342. ** will leave the database connection open and return [SQLITE_BUSY].
  343. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  344. ** and unfinished sqlite3_backups, then the database connection becomes
  345. ** an unusable "zombie" which will automatically be deallocated when the
  346. ** last prepared statement is finalized or the last sqlite3_backup is
  347. ** finished. The sqlite3_close_v2() interface is intended for use with
  348. ** host languages that are garbage collected, and where the order in which
  349. ** destructors are called is arbitrary.
  350. **
  351. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  352. ** [sqlite3_blob_close | close] all [BLOB handles], and
  353. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  354. ** with the [sqlite3] object prior to attempting to close the object. ^If
  355. ** sqlite3_close_v2() is called on a [database connection] that still has
  356. ** outstanding [prepared statements], [BLOB handles], and/or
  357. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  358. ** of resources is deferred until all [prepared statements], [BLOB handles],
  359. ** and [sqlite3_backup] objects are also destroyed.
  360. **
  361. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  362. ** the transaction is automatically rolled back.
  363. **
  364. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  365. ** must be either a NULL
  366. ** pointer or an [sqlite3] object pointer obtained
  367. ** from [sqlite3_open()], [sqlite3_open16()], or
  368. ** [sqlite3_open_v2()], and not previously closed.
  369. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  370. ** argument is a harmless no-op.
  371. */
  372. SQLITE_API int sqlite3_close(sqlite3*);
  373. SQLITE_API int sqlite3_close_v2(sqlite3*);
  374. /*
  375. ** The type for a callback function.
  376. ** This is legacy and deprecated. It is included for historical
  377. ** compatibility and is not documented.
  378. */
  379. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  380. /*
  381. ** CAPI3REF: One-Step Query Execution Interface
  382. **
  383. ** The sqlite3_exec() interface is a convenience wrapper around
  384. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  385. ** that allows an application to run multiple statements of SQL
  386. ** without having to use a lot of C code.
  387. **
  388. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  389. ** semicolon-separate SQL statements passed into its 2nd argument,
  390. ** in the context of the [database connection] passed in as its 1st
  391. ** argument. ^If the callback function of the 3rd argument to
  392. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  393. ** coming out of the evaluated SQL statements. ^The 4th argument to
  394. ** sqlite3_exec() is relayed through to the 1st argument of each
  395. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  396. ** is NULL, then no callback is ever invoked and result rows are
  397. ** ignored.
  398. **
  399. ** ^If an error occurs while evaluating the SQL statements passed into
  400. ** sqlite3_exec(), then execution of the current statement stops and
  401. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  402. ** is not NULL then any error message is written into memory obtained
  403. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  404. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  405. ** on error message strings returned through the 5th parameter of
  406. ** of sqlite3_exec() after the error message string is no longer needed.
  407. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  408. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  409. ** NULL before returning.
  410. **
  411. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  412. ** routine returns SQLITE_ABORT without invoking the callback again and
  413. ** without running any subsequent SQL statements.
  414. **
  415. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  416. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  417. ** callback is an array of pointers to strings obtained as if from
  418. ** [sqlite3_column_text()], one for each column. ^If an element of a
  419. ** result row is NULL then the corresponding string pointer for the
  420. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  421. ** sqlite3_exec() callback is an array of pointers to strings where each
  422. ** entry represents the name of corresponding result column as obtained
  423. ** from [sqlite3_column_name()].
  424. **
  425. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  426. ** to an empty string, or a pointer that contains only whitespace and/or
  427. ** SQL comments, then no SQL statements are evaluated and the database
  428. ** is not changed.
  429. **
  430. ** Restrictions:
  431. **
  432. ** <ul>
  433. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  434. ** is a valid and open [database connection].
  435. ** <li> The application must not close [database connection] specified by
  436. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  437. ** <li> The application must not modify the SQL statement text passed into
  438. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  439. ** </ul>
  440. */
  441. SQLITE_API int sqlite3_exec(
  442. sqlite3*, /* An open database */
  443. const char *sql, /* SQL to be evaluated */
  444. int (*callback)(void*,int,char**,char**), /* Callback function */
  445. void *, /* 1st argument to callback */
  446. char **errmsg /* Error msg written here */
  447. );
  448. /*
  449. ** CAPI3REF: Result Codes
  450. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  451. ** KEYWORDS: {result code} {result codes}
  452. **
  453. ** Many SQLite functions return an integer result code from the set shown
  454. ** here in order to indicate success or failure.
  455. **
  456. ** New error codes may be added in future versions of SQLite.
  457. **
  458. ** See also: [SQLITE_IOERR_READ | extended result codes],
  459. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  460. */
  461. #define SQLITE_OK 0 /* Successful result */
  462. /* beginning-of-error-codes */
  463. #define SQLITE_ERROR 1 /* SQL error or missing database */
  464. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  465. #define SQLITE_PERM 3 /* Access permission denied */
  466. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  467. #define SQLITE_BUSY 5 /* The database file is locked */
  468. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  469. #define SQLITE_NOMEM 7 /* A malloc() failed */
  470. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  471. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  472. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  473. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  474. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  475. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  476. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  477. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  478. #define SQLITE_EMPTY 16 /* Database is empty */
  479. #define SQLITE_SCHEMA 17 /* The database schema changed */
  480. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  481. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  482. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  483. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  484. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  485. #define SQLITE_AUTH 23 /* Authorization denied */
  486. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  487. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  488. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  489. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  490. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  491. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  492. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  493. /* end-of-error-codes */
  494. /*
  495. ** CAPI3REF: Extended Result Codes
  496. ** KEYWORDS: {extended error code} {extended error codes}
  497. ** KEYWORDS: {extended result code} {extended result codes}
  498. **
  499. ** In its default configuration, SQLite API routines return one of 26 integer
  500. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  501. ** these result codes are too coarse-grained. They do not provide as
  502. ** much information about problems as programmers might like. In an effort to
  503. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  504. ** support for additional result codes that provide more detailed information
  505. ** about errors. The extended result codes are enabled or disabled
  506. ** on a per database connection basis using the
  507. ** [sqlite3_extended_result_codes()] API.
  508. **
  509. ** Some of the available extended result codes are listed here.
  510. ** One may expect the number of extended result codes will be expand
  511. ** over time. Software that uses extended result codes should expect
  512. ** to see new result codes in future releases of SQLite.
  513. **
  514. ** The SQLITE_OK result code will never be extended. It will always
  515. ** be exactly zero.
  516. */
  517. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  518. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  519. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  520. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  521. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  522. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  523. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  524. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  525. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  526. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  527. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  528. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  529. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  530. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  531. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  532. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  533. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  534. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  535. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  536. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  537. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  538. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  539. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  540. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  541. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  542. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  543. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  544. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  545. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  546. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  547. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  548. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  549. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  550. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  551. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  552. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  553. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  554. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  555. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  556. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  557. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  558. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  559. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  560. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  561. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  562. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  563. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  564. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  565. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  566. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  567. /*
  568. ** CAPI3REF: Flags For File Open Operations
  569. **
  570. ** These bit values are intended for use in the
  571. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  572. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  573. */
  574. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  575. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  576. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  577. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  578. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  579. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  580. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  581. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  582. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  583. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  584. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  585. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  586. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  587. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  588. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  589. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  590. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  591. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  592. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  593. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  594. /* Reserved: 0x00F00000 */
  595. /*
  596. ** CAPI3REF: Device Characteristics
  597. **
  598. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  599. ** object returns an integer which is a vector of these
  600. ** bit values expressing I/O characteristics of the mass storage
  601. ** device that holds the file that the [sqlite3_io_methods]
  602. ** refers to.
  603. **
  604. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  605. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  606. ** mean that writes of blocks that are nnn bytes in size and
  607. ** are aligned to an address which is an integer multiple of
  608. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  609. ** that when data is appended to a file, the data is appended
  610. ** first then the size of the file is extended, never the other
  611. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  612. ** information is written to disk in the same order as calls
  613. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  614. ** after reboot following a crash or power loss, the only bytes in a
  615. ** file that were written at the application level might have changed
  616. ** and that adjacent bytes, even bytes within the same sector are
  617. ** guaranteed to be unchanged.
  618. */
  619. #define SQLITE_IOCAP_ATOMIC 0x00000001
  620. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  621. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  622. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  623. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  624. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  625. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  626. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  627. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  628. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  629. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  630. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  631. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  632. /*
  633. ** CAPI3REF: File Locking Levels
  634. **
  635. ** SQLite uses one of these integer values as the second
  636. ** argument to calls it makes to the xLock() and xUnlock() methods
  637. ** of an [sqlite3_io_methods] object.
  638. */
  639. #define SQLITE_LOCK_NONE 0
  640. #define SQLITE_LOCK_SHARED 1
  641. #define SQLITE_LOCK_RESERVED 2
  642. #define SQLITE_LOCK_PENDING 3
  643. #define SQLITE_LOCK_EXCLUSIVE 4
  644. /*
  645. ** CAPI3REF: Synchronization Type Flags
  646. **
  647. ** When SQLite invokes the xSync() method of an
  648. ** [sqlite3_io_methods] object it uses a combination of
  649. ** these integer values as the second argument.
  650. **
  651. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  652. ** sync operation only needs to flush data to mass storage. Inode
  653. ** information need not be flushed. If the lower four bits of the flag
  654. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  655. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  656. ** to use Mac OS X style fullsync instead of fsync().
  657. **
  658. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  659. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  660. ** settings. The [synchronous pragma] determines when calls to the
  661. ** xSync VFS method occur and applies uniformly across all platforms.
  662. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  663. ** energetic or rigorous or forceful the sync operations are and
  664. ** only make a difference on Mac OSX for the default SQLite code.
  665. ** (Third-party VFS implementations might also make the distinction
  666. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  667. ** operating systems natively supported by SQLite, only Mac OSX
  668. ** cares about the difference.)
  669. */
  670. #define SQLITE_SYNC_NORMAL 0x00002
  671. #define SQLITE_SYNC_FULL 0x00003
  672. #define SQLITE_SYNC_DATAONLY 0x00010
  673. /*
  674. ** CAPI3REF: OS Interface Open File Handle
  675. **
  676. ** An [sqlite3_file] object represents an open file in the
  677. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  678. ** implementations will
  679. ** want to subclass this object by appending additional fields
  680. ** for their own use. The pMethods entry is a pointer to an
  681. ** [sqlite3_io_methods] object that defines methods for performing
  682. ** I/O operations on the open file.
  683. */
  684. typedef struct sqlite3_file sqlite3_file;
  685. struct sqlite3_file {
  686. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  687. };
  688. /*
  689. ** CAPI3REF: OS Interface File Virtual Methods Object
  690. **
  691. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  692. ** [sqlite3_file] object (or, more commonly, a subclass of the
  693. ** [sqlite3_file] object) with a pointer to an instance of this object.
  694. ** This object defines the methods used to perform various operations
  695. ** against the open file represented by the [sqlite3_file] object.
  696. **
  697. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  698. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  699. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  700. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  701. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  702. ** to NULL.
  703. **
  704. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  705. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  706. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  707. ** flag may be ORed in to indicate that only the data of the file
  708. ** and not its inode needs to be synced.
  709. **
  710. ** The integer values to xLock() and xUnlock() are one of
  711. ** <ul>
  712. ** <li> [SQLITE_LOCK_NONE],
  713. ** <li> [SQLITE_LOCK_SHARED],
  714. ** <li> [SQLITE_LOCK_RESERVED],
  715. ** <li> [SQLITE_LOCK_PENDING], or
  716. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  717. ** </ul>
  718. ** xLock() increases the lock. xUnlock() decreases the lock.
  719. ** The xCheckReservedLock() method checks whether any database connection,
  720. ** either in this process or in some other process, is holding a RESERVED,
  721. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  722. ** if such a lock exists and false otherwise.
  723. **
  724. ** The xFileControl() method is a generic interface that allows custom
  725. ** VFS implementations to directly control an open file using the
  726. ** [sqlite3_file_control()] interface. The second "op" argument is an
  727. ** integer opcode. The third argument is a generic pointer intended to
  728. ** point to a structure that may contain arguments or space in which to
  729. ** write return values. Potential uses for xFileControl() might be
  730. ** functions to enable blocking locks with timeouts, to change the
  731. ** locking strategy (for example to use dot-file locks), to inquire
  732. ** about the status of a lock, or to break stale locks. The SQLite
  733. ** core reserves all opcodes less than 100 for its own use.
  734. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  735. ** Applications that define a custom xFileControl method should use opcodes
  736. ** greater than 100 to avoid conflicts. VFS implementations should
  737. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  738. ** recognize.
  739. **
  740. ** The xSectorSize() method returns the sector size of the
  741. ** device that underlies the file. The sector size is the
  742. ** minimum write that can be performed without disturbing
  743. ** other bytes in the file. The xDeviceCharacteristics()
  744. ** method returns a bit vector describing behaviors of the
  745. ** underlying device:
  746. **
  747. ** <ul>
  748. ** <li> [SQLITE_IOCAP_ATOMIC]
  749. ** <li> [SQLITE_IOCAP_ATOMIC512]
  750. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  751. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  752. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  753. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  754. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  755. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  756. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  757. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  758. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  759. ** </ul>
  760. **
  761. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  762. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  763. ** mean that writes of blocks that are nnn bytes in size and
  764. ** are aligned to an address which is an integer multiple of
  765. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  766. ** that when data is appended to a file, the data is appended
  767. ** first then the size of the file is extended, never the other
  768. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  769. ** information is written to disk in the same order as calls
  770. ** to xWrite().
  771. **
  772. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  773. ** in the unread portions of the buffer with zeros. A VFS that
  774. ** fails to zero-fill short reads might seem to work. However,
  775. ** failure to zero-fill short reads will eventually lead to
  776. ** database corruption.
  777. */
  778. typedef struct sqlite3_io_methods sqlite3_io_methods;
  779. struct sqlite3_io_methods {
  780. int iVersion;
  781. int (*xClose)(sqlite3_file*);
  782. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  783. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  784. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  785. int (*xSync)(sqlite3_file*, int flags);
  786. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  787. int (*xLock)(sqlite3_file*, int);
  788. int (*xUnlock)(sqlite3_file*, int);
  789. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  790. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  791. int (*xSectorSize)(sqlite3_file*);
  792. int (*xDeviceCharacteristics)(sqlite3_file*);
  793. /* Methods above are valid for version 1 */
  794. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  795. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  796. void (*xShmBarrier)(sqlite3_file*);
  797. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  798. /* Methods above are valid for version 2 */
  799. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  800. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  801. /* Methods above are valid for version 3 */
  802. /* Additional methods may be added in future releases */
  803. };
  804. /*
  805. ** CAPI3REF: Standard File Control Opcodes
  806. **
  807. ** These integer constants are opcodes for the xFileControl method
  808. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  809. ** interface.
  810. **
  811. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  812. ** opcode causes the xFileControl method to write the current state of
  813. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  814. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  815. ** into an integer that the pArg argument points to. This capability
  816. ** is used during testing and only needs to be supported when SQLITE_TEST
  817. ** is defined.
  818. ** <ul>
  819. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  820. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  821. ** layer a hint of how large the database file will grow to be during the
  822. ** current transaction. This hint is not guaranteed to be accurate but it
  823. ** is often close. The underlying VFS might choose to preallocate database
  824. ** file space based on this hint in order to help writes to the database
  825. ** file run faster.
  826. **
  827. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  828. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  829. ** extends and truncates the database file in chunks of a size specified
  830. ** by the user. The fourth argument to [sqlite3_file_control()] should
  831. ** point to an integer (type int) containing the new chunk-size to use
  832. ** for the nominated database. Allocating database file space in large
  833. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  834. ** improve performance on some systems.
  835. **
  836. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  837. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  838. ** to the [sqlite3_file] object associated with a particular database
  839. ** connection. See the [sqlite3_file_control()] documentation for
  840. ** additional information.
  841. **
  842. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  843. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  844. ** SQLite and sent to all VFSes in place of a call to the xSync method
  845. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  846. ** Some specialized VFSes need this signal in order to operate correctly
  847. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  848. ** VFSes do not need this signal and should silently ignore this opcode.
  849. ** Applications should not call [sqlite3_file_control()] with this
  850. ** opcode as doing so may disrupt the operation of the specialized VFSes
  851. ** that do require it.
  852. **
  853. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  854. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  855. ** retry counts and intervals for certain disk I/O operations for the
  856. ** windows [VFS] in order to provide robustness in the presence of
  857. ** anti-virus programs. By default, the windows VFS will retry file read,
  858. ** file write, and file delete operations up to 10 times, with a delay
  859. ** of 25 milliseconds before the first retry and with the delay increasing
  860. ** by an additional 25 milliseconds with each subsequent retry. This
  861. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  862. ** to be adjusted. The values are changed for all database connections
  863. ** within the same process. The argument is a pointer to an array of two
  864. ** integers where the first integer i the new retry count and the second
  865. ** integer is the delay. If either integer is negative, then the setting
  866. ** is not changed but instead the prior value of that setting is written
  867. ** into the array entry, allowing the current retry settings to be
  868. ** interrogated. The zDbName parameter is ignored.
  869. **
  870. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  871. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  872. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  873. ** write ahead log and shared memory files used for transaction control
  874. ** are automatically deleted when the latest connection to the database
  875. ** closes. Setting persistent WAL mode causes those files to persist after
  876. ** close. Persisting the files is useful when other processes that do not
  877. ** have write permission on the directory containing the database file want
  878. ** to read the database file, as the WAL and shared memory files must exist
  879. ** in order for the database to be readable. The fourth parameter to
  880. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  881. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  882. ** WAL mode. If the integer is -1, then it is overwritten with the current
  883. ** WAL persistence setting.
  884. **
  885. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  886. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  887. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  888. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  889. ** xDeviceCharacteristics methods. The fourth parameter to
  890. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  891. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  892. ** mode. If the integer is -1, then it is overwritten with the current
  893. ** zero-damage mode setting.
  894. **
  895. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  896. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  897. ** a write transaction to indicate that, unless it is rolled back for some
  898. ** reason, the entire database file will be overwritten by the current
  899. ** transaction. This is used by VACUUM operations.
  900. **
  901. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  902. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  903. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  904. ** final bottom-level VFS are written into memory obtained from
  905. ** [sqlite3_malloc()] and the result is stored in the char* variable
  906. ** that the fourth parameter of [sqlite3_file_control()] points to.
  907. ** The caller is responsible for freeing the memory when done. As with
  908. ** all file-control actions, there is no guarantee that this will actually
  909. ** do anything. Callers should initialize the char* variable to a NULL
  910. ** pointer in case this file-control is not implemented. This file-control
  911. ** is intended for diagnostic use only.
  912. **
  913. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  914. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  915. ** file control is sent to the open [sqlite3_file] object corresponding
  916. ** to the database file to which the pragma statement refers. ^The argument
  917. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  918. ** pointers to strings (char**) in which the second element of the array
  919. ** is the name of the pragma and the third element is the argument to the
  920. ** pragma or NULL if the pragma has no argument. ^The handler for an
  921. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  922. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  923. ** or the equivalent and that string will become the result of the pragma or
  924. ** the error message if the pragma fails. ^If the
  925. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  926. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  927. ** file control returns [SQLITE_OK], then the parser assumes that the
  928. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  929. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  930. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  931. ** that the VFS encountered an error while handling the [PRAGMA] and the
  932. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  933. ** file control occurs at the beginning of pragma statement analysis and so
  934. ** it is able to override built-in [PRAGMA] statements.
  935. **
  936. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  937. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  938. ** file-control may be invoked by SQLite on the database file handle
  939. ** shortly after it is opened in order to provide a custom VFS with access
  940. ** to the connections busy-handler callback. The argument is of type (void **)
  941. ** - an array of two (void *) values. The first (void *) actually points
  942. ** to a function of type (int (*)(void *)). In order to invoke the connections
  943. ** busy-handler, this function should be invoked with the second (void *) in
  944. ** the array as the only argument. If it returns non-zero, then the operation
  945. ** should be retried. If it returns zero, the custom VFS should abandon the
  946. ** current operation.
  947. **
  948. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  949. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  950. ** to have SQLite generate a
  951. ** temporary filename using the same algorithm that is followed to generate
  952. ** temporary filenames for TEMP tables and other internal uses. The
  953. ** argument should be a char** which will be filled with the filename
  954. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  955. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  956. **
  957. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  958. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  959. ** maximum number of bytes that will be used for memory-mapped I/O.
  960. ** The argument is a pointer to a value of type sqlite3_int64 that
  961. ** is an advisory maximum number of bytes in the file to memory map. The
  962. ** pointer is overwritten with the old value. The limit is not changed if
  963. ** the value originally pointed to is negative, and so the current limit
  964. ** can be queried by passing in a pointer to a negative number. This
  965. ** file-control is used internally to implement [PRAGMA mmap_size].
  966. **
  967. ** </ul>
  968. */
  969. #define SQLITE_FCNTL_LOCKSTATE 1
  970. #define SQLITE_GET_LOCKPROXYFILE 2
  971. #define SQLITE_SET_LOCKPROXYFILE 3
  972. #define SQLITE_LAST_ERRNO 4
  973. #define SQLITE_FCNTL_SIZE_HINT 5
  974. #define SQLITE_FCNTL_CHUNK_SIZE 6
  975. #define SQLITE_FCNTL_FILE_POINTER 7
  976. #define SQLITE_FCNTL_SYNC_OMITTED 8
  977. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  978. #define SQLITE_FCNTL_PERSIST_WAL 10
  979. #define SQLITE_FCNTL_OVERWRITE 11
  980. #define SQLITE_FCNTL_VFSNAME 12
  981. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  982. #define SQLITE_FCNTL_PRAGMA 14
  983. #define SQLITE_FCNTL_BUSYHANDLER 15
  984. #define SQLITE_FCNTL_TEMPFILENAME 16
  985. #define SQLITE_FCNTL_MMAP_SIZE 18
  986. /*
  987. ** CAPI3REF: Mutex Handle
  988. **
  989. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  990. ** abstract type for a mutex object. The SQLite core never looks
  991. ** at the internal representation of an [sqlite3_mutex]. It only
  992. ** deals with pointers to the [sqlite3_mutex] object.
  993. **
  994. ** Mutexes are created using [sqlite3_mutex_alloc()].
  995. */
  996. typedef struct sqlite3_mutex sqlite3_mutex;
  997. /*
  998. ** CAPI3REF: OS Interface Object
  999. **
  1000. ** An instance of the sqlite3_vfs object defines the interface between
  1001. ** the SQLite core and the underlying operating system. The "vfs"
  1002. ** in the name of the object stands for "virtual file system". See
  1003. ** the [VFS | VFS documentation] for further information.
  1004. **
  1005. ** The value of the iVersion field is initially 1 but may be larger in
  1006. ** future versions of SQLite. Additional fields may be appended to this
  1007. ** object when the iVersion value is increased. Note that the structure
  1008. ** of the sqlite3_vfs object changes in the transaction between
  1009. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1010. ** modified.
  1011. **
  1012. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1013. ** structure used by this VFS. mxPathname is the maximum length of
  1014. ** a pathname in this VFS.
  1015. **
  1016. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1017. ** the pNext pointer. The [sqlite3_vfs_register()]
  1018. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1019. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1020. ** searches the list. Neither the application code nor the VFS
  1021. ** implementation should use the pNext pointer.
  1022. **
  1023. ** The pNext field is the only field in the sqlite3_vfs
  1024. ** structure that SQLite will ever modify. SQLite will only access
  1025. ** or modify this field while holding a particular static mutex.
  1026. ** The application should never modify anything within the sqlite3_vfs
  1027. ** object once the object has been registered.
  1028. **
  1029. ** The zName field holds the name of the VFS module. The name must
  1030. ** be unique across all VFS modules.
  1031. **
  1032. ** [[sqlite3_vfs.xOpen]]
  1033. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1034. ** is either a NULL pointer or string obtained
  1035. ** from xFullPathname() with an optional suffix added.
  1036. ** ^If a suffix is added to the zFilename parameter, it will
  1037. ** consist of a single "-" character followed by no more than
  1038. ** 11 alphanumeric and/or "-" characters.
  1039. ** ^SQLite further guarantees that
  1040. ** the string will be valid and unchanged until xClose() is
  1041. ** called. Because of the previous sentence,
  1042. ** the [sqlite3_file] can safely store a pointer to the
  1043. ** filename if it needs to remember the filename for some reason.
  1044. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1045. ** must invent its own temporary name for the file. ^Whenever the
  1046. ** xFilename parameter is NULL it will also be the case that the
  1047. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1048. **
  1049. ** The flags argument to xOpen() includes all bits set in
  1050. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1051. ** or [sqlite3_open16()] is used, then flags includes at least
  1052. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1053. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1054. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1055. **
  1056. ** ^(SQLite will also add one of the following flags to the xOpen()
  1057. ** call, depending on the object being opened:
  1058. **
  1059. ** <ul>
  1060. ** <li> [SQLITE_OPEN_MAIN_DB]
  1061. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1062. ** <li> [SQLITE_OPEN_TEMP_DB]
  1063. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1064. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1065. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1066. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1067. ** <li> [SQLITE_OPEN_WAL]
  1068. ** </ul>)^
  1069. **
  1070. ** The file I/O implementation can use the object type flags to
  1071. ** change the way it deals with files. For example, an application
  1072. ** that does not care about crash recovery or rollback might make
  1073. ** the open of a journal file a no-op. Writes to this journal would
  1074. ** also be no-ops, and any attempt to read the journal would return
  1075. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1076. ** file will be doing page-aligned sector reads and writes in a random
  1077. ** order and set up its I/O subsystem accordingly.
  1078. **
  1079. ** SQLite might also add one of the following flags to the xOpen method:
  1080. **
  1081. ** <ul>
  1082. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1083. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1084. ** </ul>
  1085. **
  1086. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1087. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1088. ** will be set for TEMP databases and their journals, transient
  1089. ** databases, and subjournals.
  1090. **
  1091. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1092. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1093. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1094. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1095. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1096. ** be created, and that it is an error if it already exists.
  1097. ** It is <i>not</i> used to indicate the file should be opened
  1098. ** for exclusive access.
  1099. **
  1100. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1101. ** to hold the [sqlite3_file] structure passed as the third
  1102. ** argument to xOpen. The xOpen method does not have to
  1103. ** allocate the structure; it should just fill it in. Note that
  1104. ** the xOpen method must set the sqlite3_file.pMethods to either
  1105. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1106. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1107. ** element will be valid after xOpen returns regardless of the success
  1108. ** or failure of the xOpen call.
  1109. **
  1110. ** [[sqlite3_vfs.xAccess]]
  1111. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1112. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1113. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1114. ** to test whether a file is at least readable. The file can be a
  1115. ** directory.
  1116. **
  1117. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1118. ** output buffer xFullPathname. The exact size of the output buffer
  1119. ** is also passed as a parameter to both methods. If the output buffer
  1120. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1121. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1122. ** to prevent this by setting mxPathname to a sufficiently large value.
  1123. **
  1124. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1125. ** interfaces are not strictly a part of the filesystem, but they are
  1126. ** included in the VFS structure for completeness.
  1127. ** The xRandomness() function attempts to return nBytes bytes
  1128. ** of good-quality randomness into zOut. The return value is
  1129. ** the actual number of bytes of randomness obtained.
  1130. ** The xSleep() method causes the calling thread to sleep for at
  1131. ** least the number of microseconds given. ^The xCurrentTime()
  1132. ** method returns a Julian Day Number for the current date and time as
  1133. ** a floating point value.
  1134. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1135. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1136. ** a 24-hour day).
  1137. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1138. ** date and time if that method is available (if iVersion is 2 or
  1139. ** greater and the function pointer is not NULL) and will fall back
  1140. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1141. **
  1142. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1143. ** are not used by the SQLite core. These optional interfaces are provided
  1144. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1145. ** system calls with functions under its control, a test program can
  1146. ** simulate faults and error conditions that would otherwise be difficult
  1147. ** or impossible to induce. The set of system calls that can be overridden
  1148. ** varies from one VFS to another, and from one version of the same VFS to the
  1149. ** next. Applications that use these interfaces must be prepared for any
  1150. ** or all of these interfaces to be NULL or for their behavior to change
  1151. ** from one release to the next. Applications must not attempt to access
  1152. ** any of these methods if the iVersion of the VFS is less than 3.
  1153. */
  1154. typedef struct sqlite3_vfs sqlite3_vfs;
  1155. typedef void (*sqlite3_syscall_ptr)(void);
  1156. struct sqlite3_vfs {
  1157. int iVersion; /* Structure version number (currently 3) */
  1158. int szOsFile; /* Size of subclassed sqlite3_file */
  1159. int mxPathname; /* Maximum file pathname length */
  1160. sqlite3_vfs *pNext; /* Next registered VFS */
  1161. const char *zName; /* Name of this virtual file system */
  1162. void *pAppData; /* Pointer to application-specific data */
  1163. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1164. int flags, int *pOutFlags);
  1165. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1166. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1167. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1168. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1169. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1170. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1171. void (*xDlClose)(sqlite3_vfs*, void*);
  1172. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1173. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1174. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1175. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1176. /*
  1177. ** The methods above are in version 1 of the sqlite_vfs object
  1178. ** definition. Those that follow are added in version 2 or later
  1179. */
  1180. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1181. /*
  1182. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1183. ** Those below are for version 3 and greater.
  1184. */
  1185. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1186. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1187. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1188. /*
  1189. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1190. ** New fields may be appended in figure versions. The iVersion
  1191. ** value will increment whenever this happens.
  1192. */
  1193. };
  1194. /*
  1195. ** CAPI3REF: Flags for the xAccess VFS method
  1196. **
  1197. ** These integer constants can be used as the third parameter to
  1198. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1199. ** what kind of permissions the xAccess method is looking for.
  1200. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1201. ** simply checks whether the file exists.
  1202. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1203. ** checks whether the named directory is both readable and writable
  1204. ** (in other words, if files can be added, removed, and renamed within
  1205. ** the directory).
  1206. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1207. ** [temp_store_directory pragma], though this could change in a future
  1208. ** release of SQLite.
  1209. ** With SQLITE_ACCESS_READ, the xAccess method
  1210. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1211. ** currently unused, though it might be used in a future release of
  1212. ** SQLite.
  1213. */
  1214. #define SQLITE_ACCESS_EXISTS 0
  1215. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1216. #define SQLITE_ACCESS_READ 2 /* Unused */
  1217. /*
  1218. ** CAPI3REF: Flags for the xShmLock VFS method
  1219. **
  1220. ** These integer constants define the various locking operations
  1221. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1222. ** following are the only legal combinations of flags to the
  1223. ** xShmLock method:
  1224. **
  1225. ** <ul>
  1226. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1227. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1228. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1229. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1230. ** </ul>
  1231. **
  1232. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1233. ** was given no the corresponding lock.
  1234. **
  1235. ** The xShmLock method can transition between unlocked and SHARED or
  1236. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1237. ** and EXCLUSIVE.
  1238. */
  1239. #define SQLITE_SHM_UNLOCK 1
  1240. #define SQLITE_SHM_LOCK 2
  1241. #define SQLITE_SHM_SHARED 4
  1242. #define SQLITE_SHM_EXCLUSIVE 8
  1243. /*
  1244. ** CAPI3REF: Maximum xShmLock index
  1245. **
  1246. ** The xShmLock method on [sqlite3_io_methods] may use values
  1247. ** between 0 and this upper bound as its "offset" argument.
  1248. ** The SQLite core will never attempt to acquire or release a
  1249. ** lock outside of this range
  1250. */
  1251. #define SQLITE_SHM_NLOCK 8
  1252. /*
  1253. ** CAPI3REF: Initialize The SQLite Library
  1254. **
  1255. ** ^The sqlite3_initialize() routine initializes the
  1256. ** SQLite library. ^The sqlite3_shutdown() routine
  1257. ** deallocates any resources that were allocated by sqlite3_initialize().
  1258. ** These routines are designed to aid in process initialization and
  1259. ** shutdown on embedded systems. Workstation applications using
  1260. ** SQLite normally do not need to invoke either of these routines.
  1261. **
  1262. ** A call to sqlite3_initialize() is an "effective" call if it is
  1263. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1264. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1265. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1266. ** of sqlite3_initialize() does any initialization. All other calls
  1267. ** are harmless no-ops.)^
  1268. **
  1269. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1270. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1271. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1272. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1273. **
  1274. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1275. ** is not. The sqlite3_shutdown() interface must only be called from a
  1276. ** single thread. All open [database connections] must be closed and all
  1277. ** other SQLite resources must be deallocated prior to invoking
  1278. ** sqlite3_shutdown().
  1279. **
  1280. ** Among other things, ^sqlite3_initialize() will invoke
  1281. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1282. ** will invoke sqlite3_os_end().
  1283. **
  1284. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1285. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1286. ** the library (perhaps it is unable to allocate a needed resource such
  1287. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1288. **
  1289. ** ^The sqlite3_initialize() routine is called internally by many other
  1290. ** SQLite interfaces so that an application usually does not need to
  1291. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1292. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1293. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1294. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1295. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1296. ** are omitted and the application must call sqlite3_initialize() directly
  1297. ** prior to using any other SQLite interface. For maximum portability,
  1298. ** it is recommended that applications always invoke sqlite3_initialize()
  1299. ** directly prior to using any other SQLite interface. Future releases
  1300. ** of SQLite may require this. In other words, the behavior exhibited
  1301. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1302. ** default behavior in some future release of SQLite.
  1303. **
  1304. ** The sqlite3_os_init() routine does operating-system specific
  1305. ** initialization of the SQLite library. The sqlite3_os_end()
  1306. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1307. ** performed by these routines include allocation or deallocation
  1308. ** of static resources, initialization of global variables,
  1309. ** setting up a default [sqlite3_vfs] module, or setting up
  1310. ** a default configuration using [sqlite3_config()].
  1311. **
  1312. ** The application should never invoke either sqlite3_os_init()
  1313. ** or sqlite3_os_end() directly. The application should only invoke
  1314. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1315. ** interface is called automatically by sqlite3_initialize() and
  1316. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1317. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1318. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1319. ** When [custom builds | built for other platforms]
  1320. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1321. ** option) the application must supply a suitable implementation for
  1322. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1323. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1324. ** must return [SQLITE_OK] on success and some other [error code] upon
  1325. ** failure.
  1326. */
  1327. SQLITE_API int sqlite3_initialize(void);
  1328. SQLITE_API int sqlite3_shutdown(void);
  1329. SQLITE_API int sqlite3_os_init(void);
  1330. SQLITE_API int sqlite3_os_end(void);
  1331. /*
  1332. ** CAPI3REF: Configuring The SQLite Library
  1333. **
  1334. ** The sqlite3_config() interface is used to make global configuration
  1335. ** changes to SQLite in order to tune SQLite to the specific needs of
  1336. ** the application. The default configuration is recommended for most
  1337. ** applications and so this routine is usually not necessary. It is
  1338. ** provided to support rare applications with unusual needs.
  1339. **
  1340. ** The sqlite3_config() interface is not threadsafe. The application
  1341. ** must insure that no other SQLite interfaces are invoked by other
  1342. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1343. ** may only be invoked prior to library initialization using
  1344. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1345. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1346. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1347. ** Note, however, that ^sqlite3_config() can be called as part of the
  1348. ** implementation of an application-defined [sqlite3_os_init()].
  1349. **
  1350. ** The first argument to sqlite3_config() is an integer
  1351. ** [configuration option] that determines
  1352. ** what property of SQLite is to be configured. Subsequent arguments
  1353. ** vary depending on the [configuration option]
  1354. ** in the first argument.
  1355. **
  1356. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1357. ** ^If the option is unknown or SQLite is unable to set the option
  1358. ** then this routine returns a non-zero [error code].
  1359. */
  1360. SQLITE_API int sqlite3_config(int, ...);
  1361. /*
  1362. ** CAPI3REF: Configure database connections
  1363. **
  1364. ** The sqlite3_db_config() interface is used to make configuration
  1365. ** changes to a [database connection]. The interface is similar to
  1366. ** [sqlite3_config()] except that the changes apply to a single
  1367. ** [database connection] (specified in the first argument).
  1368. **
  1369. ** The second argument to sqlite3_db_config(D,V,...) is the
  1370. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1371. ** that indicates what aspect of the [database connection] is being configured.
  1372. ** Subsequent arguments vary depending on the configuration verb.
  1373. **
  1374. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1375. ** the call is considered successful.
  1376. */
  1377. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1378. /*
  1379. ** CAPI3REF: Memory Allocation Routines
  1380. **
  1381. ** An instance of this object defines the interface between SQLite
  1382. ** and low-level memory allocation routines.
  1383. **
  1384. ** This object is used in only one place in the SQLite interface.
  1385. ** A pointer to an instance of this object is the argument to
  1386. ** [sqlite3_config()] when the configuration option is
  1387. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1388. ** By creating an instance of this object
  1389. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1390. ** during configuration, an application can specify an alternative
  1391. ** memory allocation subsystem for SQLite to use for all of its
  1392. ** dynamic memory needs.
  1393. **
  1394. ** Note that SQLite comes with several [built-in memory allocators]
  1395. ** that are perfectly adequate for the overwhelming majority of applications
  1396. ** and that this object is only useful to a tiny minority of applications
  1397. ** with specialized memory allocation requirements. This object is
  1398. ** also used during testing of SQLite in order to specify an alternative
  1399. ** memory allocator that simulates memory out-of-memory conditions in
  1400. ** order to verify that SQLite recovers gracefully from such
  1401. ** conditions.
  1402. **
  1403. ** The xMalloc, xRealloc, and xFree methods must work like the
  1404. ** malloc(), realloc() and free() functions from the standard C library.
  1405. ** ^SQLite guarantees that the second argument to
  1406. ** xRealloc is always a value returned by a prior call to xRoundup.
  1407. **
  1408. ** xSize should return the allocated size of a memory allocation
  1409. ** previously obtained from xMalloc or xRealloc. The allocated size
  1410. ** is always at least as big as the requested size but may be larger.
  1411. **
  1412. ** The xRoundup method returns what would be the allocated size of
  1413. ** a memory allocation given a particular requested size. Most memory
  1414. ** allocators round up memory allocations at least to the next multiple
  1415. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1416. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1417. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1418. ** that causes the corresponding memory allocation to fail.
  1419. **
  1420. ** The xInit method initializes the memory allocator. (For example,
  1421. ** it might allocate any require mutexes or initialize internal data
  1422. ** structures. The xShutdown method is invoked (indirectly) by
  1423. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1424. ** by xInit. The pAppData pointer is used as the only parameter to
  1425. ** xInit and xShutdown.
  1426. **
  1427. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1428. ** the xInit method, so the xInit method need not be threadsafe. The
  1429. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1430. ** not need to be threadsafe either. For all other methods, SQLite
  1431. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1432. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1433. ** it is by default) and so the methods are automatically serialized.
  1434. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1435. ** methods must be threadsafe or else make their own arrangements for
  1436. ** serialization.
  1437. **
  1438. ** SQLite will never invoke xInit() more than once without an intervening
  1439. ** call to xShutdown().
  1440. */
  1441. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1442. struct sqlite3_mem_methods {
  1443. void *(*xMalloc)(int); /* Memory allocation function */
  1444. void (*xFree)(void*); /* Free a prior allocation */
  1445. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1446. int (*xSize)(void*); /* Return the size of an allocation */
  1447. int (*xRoundup)(int); /* Round up request size to allocation size */
  1448. int (*xInit)(void*); /* Initialize the memory allocator */
  1449. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1450. void *pAppData; /* Argument to xInit() and xShutdown() */
  1451. };
  1452. /*
  1453. ** CAPI3REF: Configuration Options
  1454. ** KEYWORDS: {configuration option}
  1455. **
  1456. ** These constants are the available integer configuration options that
  1457. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1458. **
  1459. ** New configuration options may be added in future releases of SQLite.
  1460. ** Existing configuration options might be discontinued. Applications
  1461. ** should check the return code from [sqlite3_config()] to make sure that
  1462. ** the call worked. The [sqlite3_config()] interface will return a
  1463. ** non-zero [error code] if a discontinued or unsupported configuration option
  1464. ** is invoked.
  1465. **
  1466. ** <dl>
  1467. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1468. ** <dd>There are no arguments to this option. ^This option sets the
  1469. ** [threading mode] to Single-thread. In other words, it disables
  1470. ** all mutexing and puts SQLite into a mode where it can only be used
  1471. ** by a single thread. ^If SQLite is compiled with
  1472. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1473. ** it is not possible to change the [threading mode] from its default
  1474. ** value of Single-thread and so [sqlite3_config()] will return
  1475. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1476. ** configuration option.</dd>
  1477. **
  1478. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1479. ** <dd>There are no arguments to this option. ^This option sets the
  1480. ** [threading mode] to Multi-thread. In other words, it disables
  1481. ** mutexing on [database connection] and [prepared statement] objects.
  1482. ** The application is responsible for serializing access to
  1483. ** [database connections] and [prepared statements]. But other mutexes
  1484. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1485. ** environment as long as no two threads attempt to use the same
  1486. ** [database connection] at the same time. ^If SQLite is compiled with
  1487. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1488. ** it is not possible to set the Multi-thread [threading mode] and
  1489. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1490. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1491. **
  1492. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1493. ** <dd>There are no arguments to this option. ^This option sets the
  1494. ** [threading mode] to Serialized. In other words, this option enables
  1495. ** all mutexes including the recursive
  1496. ** mutexes on [database connection] and [prepared statement] objects.
  1497. ** In this mode (which is the default when SQLite is compiled with
  1498. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1499. ** to [database connections] and [prepared statements] so that the
  1500. ** application is free to use the same [database connection] or the
  1501. ** same [prepared statement] in different threads at the same time.
  1502. ** ^If SQLite is compiled with
  1503. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1504. ** it is not possible to set the Serialized [threading mode] and
  1505. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1506. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1507. **
  1508. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1509. ** <dd> ^(This option takes a single argument which is a pointer to an
  1510. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1511. ** alternative low-level memory allocation routines to be used in place of
  1512. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1513. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1514. ** before the [sqlite3_config()] call returns.</dd>
  1515. **
  1516. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1517. ** <dd> ^(This option takes a single argument which is a pointer to an
  1518. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1519. ** structure is filled with the currently defined memory allocation routines.)^
  1520. ** This option can be used to overload the default memory allocation
  1521. ** routines with a wrapper that simulations memory allocation failure or
  1522. ** tracks memory usage, for example. </dd>
  1523. **
  1524. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1525. ** <dd> ^This option takes single argument of type int, interpreted as a
  1526. ** boolean, which enables or disables the collection of memory allocation
  1527. ** statistics. ^(When memory allocation statistics are disabled, the
  1528. ** following SQLite interfaces become non-operational:
  1529. ** <ul>
  1530. ** <li> [sqlite3_memory_used()]
  1531. ** <li> [sqlite3_memory_highwater()]
  1532. ** <li> [sqlite3_soft_heap_limit64()]
  1533. ** <li> [sqlite3_status()]
  1534. ** </ul>)^
  1535. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1536. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1537. ** allocation statistics are disabled by default.
  1538. ** </dd>
  1539. **
  1540. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1541. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1542. ** scratch memory. There are three arguments: A pointer an 8-byte
  1543. ** aligned memory buffer from which the scratch allocations will be
  1544. ** drawn, the size of each scratch allocation (sz),
  1545. ** and the maximum number of scratch allocations (N). The sz
  1546. ** argument must be a multiple of 16.
  1547. ** The first argument must be a pointer to an 8-byte aligned buffer
  1548. ** of at least sz*N bytes of memory.
  1549. ** ^SQLite will use no more than two scratch buffers per thread. So
  1550. ** N should be set to twice the expected maximum number of threads.
  1551. ** ^SQLite will never require a scratch buffer that is more than 6
  1552. ** times the database page size. ^If SQLite needs needs additional
  1553. ** scratch memory beyond what is provided by this configuration option, then
  1554. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1555. **
  1556. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1557. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1558. ** the database page cache with the default page cache implementation.
  1559. ** This configuration should not be used if an application-define page
  1560. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1561. ** There are three arguments to this option: A pointer to 8-byte aligned
  1562. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1563. ** The sz argument should be the size of the largest database page
  1564. ** (a power of two between 512 and 32768) plus a little extra for each
  1565. ** page header. ^The page header size is 20 to 40 bytes depending on
  1566. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1567. ** to make sz a little too large. The first
  1568. ** argument should point to an allocation of at least sz*N bytes of memory.
  1569. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1570. ** memory needs for the first N pages that it adds to cache. ^If additional
  1571. ** page cache memory is needed beyond what is provided by this option, then
  1572. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1573. ** The pointer in the first argument must
  1574. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1575. ** will be undefined.</dd>
  1576. **
  1577. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1578. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1579. ** for all of its dynamic memory allocation needs beyond those provided
  1580. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1581. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1582. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1583. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1584. ** to using its default memory allocator (the system malloc() implementation),
  1585. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1586. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1587. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1588. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1589. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1590. ** boundary or subsequent behavior of SQLite will be undefined.
  1591. ** The minimum allocation size is capped at 2**12. Reasonable values
  1592. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1593. **
  1594. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1595. ** <dd> ^(This option takes a single argument which is a pointer to an
  1596. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1597. ** alternative low-level mutex routines to be used in place
  1598. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1599. ** content of the [sqlite3_mutex_methods] structure before the call to
  1600. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1601. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1602. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1603. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1604. ** return [SQLITE_ERROR].</dd>
  1605. **
  1606. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1607. ** <dd> ^(This option takes a single argument which is a pointer to an
  1608. ** instance of the [sqlite3_mutex_methods] structure. The
  1609. ** [sqlite3_mutex_methods]
  1610. ** structure is filled with the currently defined mutex routines.)^
  1611. ** This option can be used to overload the default mutex allocation
  1612. ** routines with a wrapper used to track mutex usage for performance
  1613. ** profiling or testing, for example. ^If SQLite is compiled with
  1614. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1615. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1616. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1617. ** return [SQLITE_ERROR].</dd>
  1618. **
  1619. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1620. ** <dd> ^(This option takes two arguments that determine the default
  1621. ** memory allocation for the lookaside memory allocator on each
  1622. ** [database connection]. The first argument is the
  1623. ** size of each lookaside buffer slot and the second is the number of
  1624. ** slots allocated to each database connection.)^ ^(This option sets the
  1625. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1626. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1627. ** configuration on individual connections.)^ </dd>
  1628. **
  1629. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1630. ** <dd> ^(This option takes a single argument which is a pointer to
  1631. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1632. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1633. ** object and uses it for page cache memory allocations.</dd>
  1634. **
  1635. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1636. ** <dd> ^(This option takes a single argument which is a pointer to an
  1637. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1638. ** page cache implementation into that object.)^ </dd>
  1639. **
  1640. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1641. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1642. ** global [error log].
  1643. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1644. ** function with a call signature of void(*)(void*,int,const char*),
  1645. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1646. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1647. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1648. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1649. ** passed through as the first parameter to the application-defined logger
  1650. ** function whenever that function is invoked. ^The second parameter to
  1651. ** the logger function is a copy of the first parameter to the corresponding
  1652. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1653. ** [extended result code]. ^The third parameter passed to the logger is
  1654. ** log message after formatting via [sqlite3_snprintf()].
  1655. ** The SQLite logging interface is not reentrant; the logger function
  1656. ** supplied by the application must not invoke any SQLite interface.
  1657. ** In a multi-threaded application, the application-defined logger
  1658. ** function must be threadsafe. </dd>
  1659. **
  1660. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1661. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1662. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1663. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1664. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1665. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1666. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1667. ** connection is opened. ^If it is globally disabled, filenames are
  1668. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1669. ** database connection is opened. ^(By default, URI handling is globally
  1670. ** disabled. The default value may be changed by compiling with the
  1671. ** [SQLITE_USE_URI] symbol defined.)^
  1672. **
  1673. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1674. ** <dd>^This option takes a single integer argument which is interpreted as
  1675. ** a boolean in order to enable or disable the use of covering indices for
  1676. ** full table scans in the query optimizer. ^The default setting is determined
  1677. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1678. ** if that compile-time option is omitted.
  1679. ** The ability to disable the use of covering indices for full table scans
  1680. ** is because some incorrectly coded legacy applications might malfunction
  1681. ** when the optimization is enabled. Providing the ability to
  1682. ** disable the optimization allows the older, buggy application code to work
  1683. ** without change even with newer versions of SQLite.
  1684. **
  1685. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1686. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1687. ** <dd> These options are obsolete and should not be used by new code.
  1688. ** They are retained for backwards compatibility but are now no-ops.
  1689. ** </dd>
  1690. **
  1691. ** [[SQLITE_CONFIG_SQLLOG]]
  1692. ** <dt>SQLITE_CONFIG_SQLLOG
  1693. ** <dd>This option is only available if sqlite is compiled with the
  1694. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1695. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1696. ** The second should be of type (void*). The callback is invoked by the library
  1697. ** in three separate circumstances, identified by the value passed as the
  1698. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1699. ** passed as the second argument has just been opened. The third argument
  1700. ** points to a buffer containing the name of the main database file. If the
  1701. ** fourth parameter is 1, then the SQL statement that the third parameter
  1702. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1703. ** the connection being passed as the second parameter is being closed. The
  1704. ** third parameter is passed NULL In this case. An example of using this
  1705. ** configuration option can be seen in the "test_sqllog.c" source file in
  1706. ** the canonical SQLite source tree.</dd>
  1707. **
  1708. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1709. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1710. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1711. ** that are the default mmap size limit (the default setting for
  1712. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1713. ** ^The default setting can be overridden by each database connection using
  1714. ** either the [PRAGMA mmap_size] command, or by using the
  1715. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1716. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1717. ** exceed the compile-time maximum mmap size set by the
  1718. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1719. ** ^If either argument to this option is negative, then that argument is
  1720. ** changed to its compile-time default.
  1721. ** </dl>
  1722. */
  1723. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1724. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1725. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1726. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1727. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1728. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1729. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1730. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1731. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1732. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1733. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1734. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1735. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1736. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1737. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1738. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1739. #define SQLITE_CONFIG_URI 17 /* int */
  1740. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1741. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1742. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1743. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1744. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1745. /*
  1746. ** CAPI3REF: Database Connection Configuration Options
  1747. **
  1748. ** These constants are the available integer configuration options that
  1749. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1750. **
  1751. ** New configuration options may be added in future releases of SQLite.
  1752. ** Existing configuration options might be discontinued. Applications
  1753. ** should check the return code from [sqlite3_db_config()] to make sure that
  1754. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1755. ** non-zero [error code] if a discontinued or unsupported configuration option
  1756. ** is invoked.
  1757. **
  1758. ** <dl>
  1759. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1760. ** <dd> ^This option takes three additional arguments that determine the
  1761. ** [lookaside memory allocator] configuration for the [database connection].
  1762. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1763. ** pointer to a memory buffer to use for lookaside memory.
  1764. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1765. ** may be NULL in which case SQLite will allocate the
  1766. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1767. ** size of each lookaside buffer slot. ^The third argument is the number of
  1768. ** slots. The size of the buffer in the first argument must be greater than
  1769. ** or equal to the product of the second and third arguments. The buffer
  1770. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1771. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1772. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1773. ** configuration for a database connection can only be changed when that
  1774. ** connection is not currently using lookaside memory, or in other words
  1775. ** when the "current value" returned by
  1776. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1777. ** Any attempt to change the lookaside memory configuration when lookaside
  1778. ** memory is in use leaves the configuration unchanged and returns
  1779. ** [SQLITE_BUSY].)^</dd>
  1780. **
  1781. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1782. ** <dd> ^This option is used to enable or disable the enforcement of
  1783. ** [foreign key constraints]. There should be two additional arguments.
  1784. ** The first argument is an integer which is 0 to disable FK enforcement,
  1785. ** positive to enable FK enforcement or negative to leave FK enforcement
  1786. ** unchanged. The second parameter is a pointer to an integer into which
  1787. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1788. ** following this call. The second parameter may be a NULL pointer, in
  1789. ** which case the FK enforcement setting is not reported back. </dd>
  1790. **
  1791. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1792. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1793. ** There should be two additional arguments.
  1794. ** The first argument is an integer which is 0 to disable triggers,
  1795. ** positive to enable triggers or negative to leave the setting unchanged.
  1796. ** The second parameter is a pointer to an integer into which
  1797. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1798. ** following this call. The second parameter may be a NULL pointer, in
  1799. ** which case the trigger setting is not reported back. </dd>
  1800. **
  1801. ** </dl>
  1802. */
  1803. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1804. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1805. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1806. /*
  1807. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1808. **
  1809. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1810. ** [extended result codes] feature of SQLite. ^The extended result
  1811. ** codes are disabled by default for historical compatibility.
  1812. */
  1813. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1814. /*
  1815. ** CAPI3REF: Last Insert Rowid
  1816. **
  1817. ** ^Each entry in an SQLite table has a unique 64-bit signed
  1818. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1819. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1820. ** names are not also used by explicitly declared columns. ^If
  1821. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1822. ** is another alias for the rowid.
  1823. **
  1824. ** ^This routine returns the [rowid] of the most recent
  1825. ** successful [INSERT] into the database from the [database connection]
  1826. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  1827. ** records the last insert rowid of both ordinary tables and [virtual tables].
  1828. ** ^If no successful [INSERT]s
  1829. ** have ever occurred on that database connection, zero is returned.
  1830. **
  1831. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1832. ** method, then this routine will return the [rowid] of the inserted
  1833. ** row as long as the trigger or virtual table method is running.
  1834. ** But once the trigger or virtual table method ends, the value returned
  1835. ** by this routine reverts to what it was before the trigger or virtual
  1836. ** table method began.)^
  1837. **
  1838. ** ^An [INSERT] that fails due to a constraint violation is not a
  1839. ** successful [INSERT] and does not change the value returned by this
  1840. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1841. ** and INSERT OR ABORT make no changes to the return value of this
  1842. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1843. ** encounters a constraint violation, it does not fail. The
  1844. ** INSERT continues to completion after deleting rows that caused
  1845. ** the constraint problem so INSERT OR REPLACE will always change
  1846. ** the return value of this interface.)^
  1847. **
  1848. ** ^For the purposes of this routine, an [INSERT] is considered to
  1849. ** be successful even if it is subsequently rolled back.
  1850. **
  1851. ** This function is accessible to SQL statements via the
  1852. ** [last_insert_rowid() SQL function].
  1853. **
  1854. ** If a separate thread performs a new [INSERT] on the same
  1855. ** database connection while the [sqlite3_last_insert_rowid()]
  1856. ** function is running and thus changes the last insert [rowid],
  1857. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1858. ** unpredictable and might not equal either the old or the new
  1859. ** last insert [rowid].
  1860. */
  1861. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1862. /*
  1863. ** CAPI3REF: Count The Number Of Rows Modified
  1864. **
  1865. ** ^This function returns the number of database rows that were changed
  1866. ** or inserted or deleted by the most recently completed SQL statement
  1867. ** on the [database connection] specified by the first parameter.
  1868. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1869. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1870. ** triggers or [foreign key actions] are not counted.)^ Use the
  1871. ** [sqlite3_total_changes()] function to find the total number of changes
  1872. ** including changes caused by triggers and foreign key actions.
  1873. **
  1874. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1875. ** are not counted. Only real table changes are counted.
  1876. **
  1877. ** ^(A "row change" is a change to a single row of a single table
  1878. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1879. ** are changed as side effects of [REPLACE] constraint resolution,
  1880. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1881. ** mechanisms do not count as direct row changes.)^
  1882. **
  1883. ** A "trigger context" is a scope of execution that begins and
  1884. ** ends with the script of a [CREATE TRIGGER | trigger].
  1885. ** Most SQL statements are
  1886. ** evaluated outside of any trigger. This is the "top level"
  1887. ** trigger context. If a trigger fires from the top level, a
  1888. ** new trigger context is entered for the duration of that one
  1889. ** trigger. Subtriggers create subcontexts for their duration.
  1890. **
  1891. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1892. ** not create a new trigger context.
  1893. **
  1894. ** ^This function returns the number of direct row changes in the
  1895. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1896. ** trigger context.
  1897. **
  1898. ** ^Thus, when called from the top level, this function returns the
  1899. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1900. ** that also occurred at the top level. ^(Within the body of a trigger,
  1901. ** the sqlite3_changes() interface can be called to find the number of
  1902. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1903. ** statement within the body of the same trigger.
  1904. ** However, the number returned does not include changes
  1905. ** caused by subtriggers since those have their own context.)^
  1906. **
  1907. ** See also the [sqlite3_total_changes()] interface, the
  1908. ** [count_changes pragma], and the [changes() SQL function].
  1909. **
  1910. ** If a separate thread makes changes on the same database connection
  1911. ** while [sqlite3_changes()] is running then the value returned
  1912. ** is unpredictable and not meaningful.
  1913. */
  1914. SQLITE_API int sqlite3_changes(sqlite3*);
  1915. /*
  1916. ** CAPI3REF: Total Number Of Rows Modified
  1917. **
  1918. ** ^This function returns the number of row changes caused by [INSERT],
  1919. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  1920. ** ^(The count returned by sqlite3_total_changes() includes all changes
  1921. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  1922. ** [foreign key actions]. However,
  1923. ** the count does not include changes used to implement [REPLACE] constraints,
  1924. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  1925. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  1926. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  1927. ** are counted.)^
  1928. ** ^The sqlite3_total_changes() function counts the changes as soon as
  1929. ** the statement that makes them is completed (when the statement handle
  1930. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  1931. **
  1932. ** See also the [sqlite3_changes()] interface, the
  1933. ** [count_changes pragma], and the [total_changes() SQL function].
  1934. **
  1935. ** If a separate thread makes changes on the same database connection
  1936. ** while [sqlite3_total_changes()] is running then the value
  1937. ** returned is unpredictable and not meaningful.
  1938. */
  1939. SQLITE_API int sqlite3_total_changes(sqlite3*);
  1940. /*
  1941. ** CAPI3REF: Interrupt A Long-Running Query
  1942. **
  1943. ** ^This function causes any pending database operation to abort and
  1944. ** return at its earliest opportunity. This routine is typically
  1945. ** called in response to a user action such as pressing "Cancel"
  1946. ** or Ctrl-C where the user wants a long query operation to halt
  1947. ** immediately.
  1948. **
  1949. ** ^It is safe to call this routine from a thread different from the
  1950. ** thread that is currently running the database operation. But it
  1951. ** is not safe to call this routine with a [database connection] that
  1952. ** is closed or might close before sqlite3_interrupt() returns.
  1953. **
  1954. ** ^If an SQL operation is very nearly finished at the time when
  1955. ** sqlite3_interrupt() is called, then it might not have an opportunity
  1956. ** to be interrupted and might continue to completion.
  1957. **
  1958. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1959. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1960. ** that is inside an explicit transaction, then the entire transaction
  1961. ** will be rolled back automatically.
  1962. **
  1963. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  1964. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  1965. ** that are started after the sqlite3_interrupt() call and before the
  1966. ** running statements reaches zero are interrupted as if they had been
  1967. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  1968. ** that are started after the running statement count reaches zero are
  1969. ** not effected by the sqlite3_interrupt().
  1970. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  1971. ** SQL statements is a no-op and has no effect on SQL statements
  1972. ** that are started after the sqlite3_interrupt() call returns.
  1973. **
  1974. ** If the database connection closes while [sqlite3_interrupt()]
  1975. ** is running then bad things will likely happen.
  1976. */
  1977. SQLITE_API void sqlite3_interrupt(sqlite3*);
  1978. /*
  1979. ** CAPI3REF: Determine If An SQL Statement Is Complete
  1980. **
  1981. ** These routines are useful during command-line input to determine if the
  1982. ** currently entered text seems to form a complete SQL statement or
  1983. ** if additional input is needed before sending the text into
  1984. ** SQLite for parsing. ^These routines return 1 if the input string
  1985. ** appears to be a complete SQL statement. ^A statement is judged to be
  1986. ** complete if it ends with a semicolon token and is not a prefix of a
  1987. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  1988. ** string literals or quoted identifier names or comments are not
  1989. ** independent tokens (they are part of the token in which they are
  1990. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  1991. ** and comments that follow the final semicolon are ignored.
  1992. **
  1993. ** ^These routines return 0 if the statement is incomplete. ^If a
  1994. ** memory allocation fails, then SQLITE_NOMEM is returned.
  1995. **
  1996. ** ^These routines do not parse the SQL statements thus
  1997. ** will not detect syntactically incorrect SQL.
  1998. **
  1999. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2000. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2001. ** automatically by sqlite3_complete16(). If that initialization fails,
  2002. ** then the return value from sqlite3_complete16() will be non-zero
  2003. ** regardless of whether or not the input SQL is complete.)^
  2004. **
  2005. ** The input to [sqlite3_complete()] must be a zero-terminated
  2006. ** UTF-8 string.
  2007. **
  2008. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2009. ** UTF-16 string in native byte order.
  2010. */
  2011. SQLITE_API int sqlite3_complete(const char *sql);
  2012. SQLITE_API int sqlite3_complete16(const void *sql);
  2013. /*
  2014. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2015. **
  2016. ** ^This routine sets a callback function that might be invoked whenever
  2017. ** an attempt is made to open a database table that another thread
  2018. ** or process has locked.
  2019. **
  2020. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2021. ** is returned immediately upon encountering the lock. ^If the busy callback
  2022. ** is not NULL, then the callback might be invoked with two arguments.
  2023. **
  2024. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2025. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2026. ** the busy handler callback is the number of times that the busy handler has
  2027. ** been invoked for this locking event. ^If the
  2028. ** busy callback returns 0, then no additional attempts are made to
  2029. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2030. ** ^If the callback returns non-zero, then another attempt
  2031. ** is made to open the database for reading and the cycle repeats.
  2032. **
  2033. ** The presence of a busy handler does not guarantee that it will be invoked
  2034. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2035. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2036. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2037. ** Consider a scenario where one process is holding a read lock that
  2038. ** it is trying to promote to a reserved lock and
  2039. ** a second process is holding a reserved lock that it is trying
  2040. ** to promote to an exclusive lock. The first process cannot proceed
  2041. ** because it is blocked by the second and the second process cannot
  2042. ** proceed because it is blocked by the first. If both processes
  2043. ** invoke the busy handlers, neither will make any progress. Therefore,
  2044. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2045. ** will induce the first process to release its read lock and allow
  2046. ** the second process to proceed.
  2047. **
  2048. ** ^The default busy callback is NULL.
  2049. **
  2050. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2051. ** when SQLite is in the middle of a large transaction where all the
  2052. ** changes will not fit into the in-memory cache. SQLite will
  2053. ** already hold a RESERVED lock on the database file, but it needs
  2054. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2055. ** pages into the database file without harm to concurrent
  2056. ** readers. ^If it is unable to promote the lock, then the in-memory
  2057. ** cache will be left in an inconsistent state and so the error
  2058. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2059. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2060. ** forces an automatic rollback of the changes. See the
  2061. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2062. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2063. ** this is important.
  2064. **
  2065. ** ^(There can only be a single busy handler defined for each
  2066. ** [database connection]. Setting a new busy handler clears any
  2067. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2068. ** will also set or clear the busy handler.
  2069. **
  2070. ** The busy callback should not take any actions which modify the
  2071. ** database connection that invoked the busy handler. Any such actions
  2072. ** result in undefined behavior.
  2073. **
  2074. ** A busy handler must not close the database connection
  2075. ** or [prepared statement] that invoked the busy handler.
  2076. */
  2077. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2078. /*
  2079. ** CAPI3REF: Set A Busy Timeout
  2080. **
  2081. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2082. ** for a specified amount of time when a table is locked. ^The handler
  2083. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2084. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2085. ** the handler returns 0 which causes [sqlite3_step()] to return
  2086. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2087. **
  2088. ** ^Calling this routine with an argument less than or equal to zero
  2089. ** turns off all busy handlers.
  2090. **
  2091. ** ^(There can only be a single busy handler for a particular
  2092. ** [database connection] any any given moment. If another busy handler
  2093. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2094. ** this routine, that other busy handler is cleared.)^
  2095. */
  2096. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2097. /*
  2098. ** CAPI3REF: Convenience Routines For Running Queries
  2099. **
  2100. ** This is a legacy interface that is preserved for backwards compatibility.
  2101. ** Use of this interface is not recommended.
  2102. **
  2103. ** Definition: A <b>result table</b> is memory data structure created by the
  2104. ** [sqlite3_get_table()] interface. A result table records the
  2105. ** complete query results from one or more queries.
  2106. **
  2107. ** The table conceptually has a number of rows and columns. But
  2108. ** these numbers are not part of the result table itself. These
  2109. ** numbers are obtained separately. Let N be the number of rows
  2110. ** and M be the number of columns.
  2111. **
  2112. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2113. ** There are (N+1)*M elements in the array. The first M pointers point
  2114. ** to zero-terminated strings that contain the names of the columns.
  2115. ** The remaining entries all point to query results. NULL values result
  2116. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2117. ** string representation as returned by [sqlite3_column_text()].
  2118. **
  2119. ** A result table might consist of one or more memory allocations.
  2120. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2121. ** A result table should be deallocated using [sqlite3_free_table()].
  2122. **
  2123. ** ^(As an example of the result table format, suppose a query result
  2124. ** is as follows:
  2125. **
  2126. ** <blockquote><pre>
  2127. ** Name | Age
  2128. ** -----------------------
  2129. ** Alice | 43
  2130. ** Bob | 28
  2131. ** Cindy | 21
  2132. ** </pre></blockquote>
  2133. **
  2134. ** There are two column (M==2) and three rows (N==3). Thus the
  2135. ** result table has 8 entries. Suppose the result table is stored
  2136. ** in an array names azResult. Then azResult holds this content:
  2137. **
  2138. ** <blockquote><pre>
  2139. ** azResult&#91;0] = "Name";
  2140. ** azResult&#91;1] = "Age";
  2141. ** azResult&#91;2] = "Alice";
  2142. ** azResult&#91;3] = "43";
  2143. ** azResult&#91;4] = "Bob";
  2144. ** azResult&#91;5] = "28";
  2145. ** azResult&#91;6] = "Cindy";
  2146. ** azResult&#91;7] = "21";
  2147. ** </pre></blockquote>)^
  2148. **
  2149. ** ^The sqlite3_get_table() function evaluates one or more
  2150. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2151. ** string of its 2nd parameter and returns a result table to the
  2152. ** pointer given in its 3rd parameter.
  2153. **
  2154. ** After the application has finished with the result from sqlite3_get_table(),
  2155. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2156. ** release the memory that was malloced. Because of the way the
  2157. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2158. ** function must not try to call [sqlite3_free()] directly. Only
  2159. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2160. **
  2161. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2162. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2163. ** to any internal data structures of SQLite. It uses only the public
  2164. ** interface defined here. As a consequence, errors that occur in the
  2165. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2166. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2167. ** [sqlite3_errmsg()].
  2168. */
  2169. SQLITE_API int sqlite3_get_table(
  2170. sqlite3 *db, /* An open database */
  2171. const char *zSql, /* SQL to be evaluated */
  2172. char ***pazResult, /* Results of the query */
  2173. int *pnRow, /* Number of result rows written here */
  2174. int *pnColumn, /* Number of result columns written here */
  2175. char **pzErrmsg /* Error msg written here */
  2176. );
  2177. SQLITE_API void sqlite3_free_table(char **result);
  2178. /*
  2179. ** CAPI3REF: Formatted String Printing Functions
  2180. **
  2181. ** These routines are work-alikes of the "printf()" family of functions
  2182. ** from the standard C library.
  2183. **
  2184. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2185. ** results into memory obtained from [sqlite3_malloc()].
  2186. ** The strings returned by these two routines should be
  2187. ** released by [sqlite3_free()]. ^Both routines return a
  2188. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2189. ** memory to hold the resulting string.
  2190. **
  2191. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2192. ** the standard C library. The result is written into the
  2193. ** buffer supplied as the second parameter whose size is given by
  2194. ** the first parameter. Note that the order of the
  2195. ** first two parameters is reversed from snprintf().)^ This is an
  2196. ** historical accident that cannot be fixed without breaking
  2197. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2198. ** returns a pointer to its buffer instead of the number of
  2199. ** characters actually written into the buffer.)^ We admit that
  2200. ** the number of characters written would be a more useful return
  2201. ** value but we cannot change the implementation of sqlite3_snprintf()
  2202. ** now without breaking compatibility.
  2203. **
  2204. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2205. ** guarantees that the buffer is always zero-terminated. ^The first
  2206. ** parameter "n" is the total size of the buffer, including space for
  2207. ** the zero terminator. So the longest string that can be completely
  2208. ** written will be n-1 characters.
  2209. **
  2210. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2211. **
  2212. ** These routines all implement some additional formatting
  2213. ** options that are useful for constructing SQL statements.
  2214. ** All of the usual printf() formatting options apply. In addition, there
  2215. ** is are "%q", "%Q", and "%z" options.
  2216. **
  2217. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2218. ** string from the argument list. But %q also doubles every '\'' character.
  2219. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2220. ** character it escapes that character and allows it to be inserted into
  2221. ** the string.
  2222. **
  2223. ** For example, assume the string variable zText contains text as follows:
  2224. **
  2225. ** <blockquote><pre>
  2226. ** char *zText = "It's a happy day!";
  2227. ** </pre></blockquote>
  2228. **
  2229. ** One can use this text in an SQL statement as follows:
  2230. **
  2231. ** <blockquote><pre>
  2232. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2233. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2234. ** sqlite3_free(zSQL);
  2235. ** </pre></blockquote>
  2236. **
  2237. ** Because the %q format string is used, the '\'' character in zText
  2238. ** is escaped and the SQL generated is as follows:
  2239. **
  2240. ** <blockquote><pre>
  2241. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2242. ** </pre></blockquote>
  2243. **
  2244. ** This is correct. Had we used %s instead of %q, the generated SQL
  2245. ** would have looked like this:
  2246. **
  2247. ** <blockquote><pre>
  2248. ** INSERT INTO table1 VALUES('It's a happy day!');
  2249. ** </pre></blockquote>
  2250. **
  2251. ** This second example is an SQL syntax error. As a general rule you should
  2252. ** always use %q instead of %s when inserting text into a string literal.
  2253. **
  2254. ** ^(The %Q option works like %q except it also adds single quotes around
  2255. ** the outside of the total string. Additionally, if the parameter in the
  2256. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2257. ** single quotes).)^ So, for example, one could say:
  2258. **
  2259. ** <blockquote><pre>
  2260. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2261. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2262. ** sqlite3_free(zSQL);
  2263. ** </pre></blockquote>
  2264. **
  2265. ** The code above will render a correct SQL statement in the zSQL
  2266. ** variable even if the zText variable is a NULL pointer.
  2267. **
  2268. ** ^(The "%z" formatting option works like "%s" but with the
  2269. ** addition that after the string has been read and copied into
  2270. ** the result, [sqlite3_free()] is called on the input string.)^
  2271. */
  2272. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2273. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2274. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2275. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2276. /*
  2277. ** CAPI3REF: Memory Allocation Subsystem
  2278. **
  2279. ** The SQLite core uses these three routines for all of its own
  2280. ** internal memory allocation needs. "Core" in the previous sentence
  2281. ** does not include operating-system specific VFS implementation. The
  2282. ** Windows VFS uses native malloc() and free() for some operations.
  2283. **
  2284. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2285. ** of memory at least N bytes in length, where N is the parameter.
  2286. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2287. ** memory, it returns a NULL pointer. ^If the parameter N to
  2288. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2289. ** a NULL pointer.
  2290. **
  2291. ** ^Calling sqlite3_free() with a pointer previously returned
  2292. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2293. ** that it might be reused. ^The sqlite3_free() routine is
  2294. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2295. ** to sqlite3_free() is harmless. After being freed, memory
  2296. ** should neither be read nor written. Even reading previously freed
  2297. ** memory might result in a segmentation fault or other severe error.
  2298. ** Memory corruption, a segmentation fault, or other severe error
  2299. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2300. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2301. **
  2302. ** ^(The sqlite3_realloc() interface attempts to resize a
  2303. ** prior memory allocation to be at least N bytes, where N is the
  2304. ** second parameter. The memory allocation to be resized is the first
  2305. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2306. ** is a NULL pointer then its behavior is identical to calling
  2307. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2308. ** ^If the second parameter to sqlite3_realloc() is zero or
  2309. ** negative then the behavior is exactly the same as calling
  2310. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2311. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2312. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2313. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2314. ** of the prior allocation are copied into the beginning of buffer returned
  2315. ** by sqlite3_realloc() and the prior allocation is freed.
  2316. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2317. ** is not freed.
  2318. **
  2319. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2320. ** is always aligned to at least an 8 byte boundary, or to a
  2321. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2322. ** option is used.
  2323. **
  2324. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2325. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2326. ** implementation of these routines to be omitted. That capability
  2327. ** is no longer provided. Only built-in memory allocators can be used.
  2328. **
  2329. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2330. ** the system malloc() and free() directly when converting
  2331. ** filenames between the UTF-8 encoding used by SQLite
  2332. ** and whatever filename encoding is used by the particular Windows
  2333. ** installation. Memory allocation errors were detected, but
  2334. ** they were reported back as [SQLITE_CANTOPEN] or
  2335. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2336. **
  2337. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2338. ** must be either NULL or else pointers obtained from a prior
  2339. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2340. ** not yet been released.
  2341. **
  2342. ** The application must not read or write any part of
  2343. ** a block of memory after it has been released using
  2344. ** [sqlite3_free()] or [sqlite3_realloc()].
  2345. */
  2346. SQLITE_API void *sqlite3_malloc(int);
  2347. SQLITE_API void *sqlite3_realloc(void*, int);
  2348. SQLITE_API void sqlite3_free(void*);
  2349. /*
  2350. ** CAPI3REF: Memory Allocator Statistics
  2351. **
  2352. ** SQLite provides these two interfaces for reporting on the status
  2353. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2354. ** routines, which form the built-in memory allocation subsystem.
  2355. **
  2356. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2357. ** of memory currently outstanding (malloced but not freed).
  2358. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2359. ** value of [sqlite3_memory_used()] since the high-water mark
  2360. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2361. ** [sqlite3_memory_highwater()] include any overhead
  2362. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2363. ** but not overhead added by the any underlying system library
  2364. ** routines that [sqlite3_malloc()] may call.
  2365. **
  2366. ** ^The memory high-water mark is reset to the current value of
  2367. ** [sqlite3_memory_used()] if and only if the parameter to
  2368. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2369. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2370. ** prior to the reset.
  2371. */
  2372. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2373. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2374. /*
  2375. ** CAPI3REF: Pseudo-Random Number Generator
  2376. **
  2377. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2378. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2379. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2380. ** the build-in random() and randomblob() SQL functions. This interface allows
  2381. ** applications to access the same PRNG for other purposes.
  2382. **
  2383. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2384. **
  2385. ** ^The first time this routine is invoked (either internally or by
  2386. ** the application) the PRNG is seeded using randomness obtained
  2387. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2388. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2389. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2390. ** method.
  2391. */
  2392. SQLITE_API void sqlite3_randomness(int N, void *P);
  2393. /*
  2394. ** CAPI3REF: Compile-Time Authorization Callbacks
  2395. **
  2396. ** ^This routine registers an authorizer callback with a particular
  2397. ** [database connection], supplied in the first argument.
  2398. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2399. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2400. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2401. ** points during the compilation process, as logic is being created
  2402. ** to perform various actions, the authorizer callback is invoked to
  2403. ** see if those actions are allowed. ^The authorizer callback should
  2404. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2405. ** specific action but allow the SQL statement to continue to be
  2406. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2407. ** rejected with an error. ^If the authorizer callback returns
  2408. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2409. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2410. ** the authorizer will fail with an error message.
  2411. **
  2412. ** When the callback returns [SQLITE_OK], that means the operation
  2413. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2414. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2415. ** authorizer will fail with an error message explaining that
  2416. ** access is denied.
  2417. **
  2418. ** ^The first parameter to the authorizer callback is a copy of the third
  2419. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2420. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2421. ** the particular action to be authorized. ^The third through sixth parameters
  2422. ** to the callback are zero-terminated strings that contain additional
  2423. ** details about the action to be authorized.
  2424. **
  2425. ** ^If the action code is [SQLITE_READ]
  2426. ** and the callback returns [SQLITE_IGNORE] then the
  2427. ** [prepared statement] statement is constructed to substitute
  2428. ** a NULL value in place of the table column that would have
  2429. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2430. ** return can be used to deny an untrusted user access to individual
  2431. ** columns of a table.
  2432. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2433. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2434. ** [truncate optimization] is disabled and all rows are deleted individually.
  2435. **
  2436. ** An authorizer is used when [sqlite3_prepare | preparing]
  2437. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2438. ** do not try to access data they are not allowed to see, or that they do not
  2439. ** try to execute malicious statements that damage the database. For
  2440. ** example, an application may allow a user to enter arbitrary
  2441. ** SQL queries for evaluation by a database. But the application does
  2442. ** not want the user to be able to make arbitrary changes to the
  2443. ** database. An authorizer could then be put in place while the
  2444. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2445. ** disallows everything except [SELECT] statements.
  2446. **
  2447. ** Applications that need to process SQL from untrusted sources
  2448. ** might also consider lowering resource limits using [sqlite3_limit()]
  2449. ** and limiting database size using the [max_page_count] [PRAGMA]
  2450. ** in addition to using an authorizer.
  2451. **
  2452. ** ^(Only a single authorizer can be in place on a database connection
  2453. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2454. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2455. ** The authorizer is disabled by default.
  2456. **
  2457. ** The authorizer callback must not do anything that will modify
  2458. ** the database connection that invoked the authorizer callback.
  2459. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2460. ** database connections for the meaning of "modify" in this paragraph.
  2461. **
  2462. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2463. ** statement might be re-prepared during [sqlite3_step()] due to a
  2464. ** schema change. Hence, the application should ensure that the
  2465. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2466. **
  2467. ** ^Note that the authorizer callback is invoked only during
  2468. ** [sqlite3_prepare()] or its variants. Authorization is not
  2469. ** performed during statement evaluation in [sqlite3_step()], unless
  2470. ** as stated in the previous paragraph, sqlite3_step() invokes
  2471. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2472. */
  2473. SQLITE_API int sqlite3_set_authorizer(
  2474. sqlite3*,
  2475. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2476. void *pUserData
  2477. );
  2478. /*
  2479. ** CAPI3REF: Authorizer Return Codes
  2480. **
  2481. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2482. ** return either [SQLITE_OK] or one of these two constants in order
  2483. ** to signal SQLite whether or not the action is permitted. See the
  2484. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2485. ** information.
  2486. **
  2487. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2488. ** from the [sqlite3_vtab_on_conflict()] interface.
  2489. */
  2490. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2491. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2492. /*
  2493. ** CAPI3REF: Authorizer Action Codes
  2494. **
  2495. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2496. ** that is invoked to authorize certain SQL statement actions. The
  2497. ** second parameter to the callback is an integer code that specifies
  2498. ** what action is being authorized. These are the integer action codes that
  2499. ** the authorizer callback may be passed.
  2500. **
  2501. ** These action code values signify what kind of operation is to be
  2502. ** authorized. The 3rd and 4th parameters to the authorization
  2503. ** callback function will be parameters or NULL depending on which of these
  2504. ** codes is used as the second parameter. ^(The 5th parameter to the
  2505. ** authorizer callback is the name of the database ("main", "temp",
  2506. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2507. ** is the name of the inner-most trigger or view that is responsible for
  2508. ** the access attempt or NULL if this access attempt is directly from
  2509. ** top-level SQL code.
  2510. */
  2511. /******************************************* 3rd ************ 4th ***********/
  2512. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2513. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2514. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2515. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2516. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2517. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2518. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2519. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2520. #define SQLITE_DELETE 9 /* Table Name NULL */
  2521. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2522. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2523. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2524. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2525. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2526. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2527. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2528. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2529. #define SQLITE_INSERT 18 /* Table Name NULL */
  2530. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2531. #define SQLITE_READ 20 /* Table Name Column Name */
  2532. #define SQLITE_SELECT 21 /* NULL NULL */
  2533. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2534. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2535. #define SQLITE_ATTACH 24 /* Filename NULL */
  2536. #define SQLITE_DETACH 25 /* Database Name NULL */
  2537. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2538. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2539. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2540. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2541. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2542. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2543. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2544. #define SQLITE_COPY 0 /* No longer used */
  2545. /*
  2546. ** CAPI3REF: Tracing And Profiling Functions
  2547. **
  2548. ** These routines register callback functions that can be used for
  2549. ** tracing and profiling the execution of SQL statements.
  2550. **
  2551. ** ^The callback function registered by sqlite3_trace() is invoked at
  2552. ** various times when an SQL statement is being run by [sqlite3_step()].
  2553. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2554. ** SQL statement text as the statement first begins executing.
  2555. ** ^(Additional sqlite3_trace() callbacks might occur
  2556. ** as each triggered subprogram is entered. The callbacks for triggers
  2557. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2558. **
  2559. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2560. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2561. **
  2562. ** ^The callback function registered by sqlite3_profile() is invoked
  2563. ** as each SQL statement finishes. ^The profile callback contains
  2564. ** the original statement text and an estimate of wall-clock time
  2565. ** of how long that statement took to run. ^The profile callback
  2566. ** time is in units of nanoseconds, however the current implementation
  2567. ** is only capable of millisecond resolution so the six least significant
  2568. ** digits in the time are meaningless. Future versions of SQLite
  2569. ** might provide greater resolution on the profiler callback. The
  2570. ** sqlite3_profile() function is considered experimental and is
  2571. ** subject to change in future versions of SQLite.
  2572. */
  2573. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2574. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2575. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2576. /*
  2577. ** CAPI3REF: Query Progress Callbacks
  2578. **
  2579. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2580. ** function X to be invoked periodically during long running calls to
  2581. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2582. ** database connection D. An example use for this
  2583. ** interface is to keep a GUI updated during a large query.
  2584. **
  2585. ** ^The parameter P is passed through as the only parameter to the
  2586. ** callback function X. ^The parameter N is the approximate number of
  2587. ** [virtual machine instructions] that are evaluated between successive
  2588. ** invocations of the callback X. ^If N is less than one then the progress
  2589. ** handler is disabled.
  2590. **
  2591. ** ^Only a single progress handler may be defined at one time per
  2592. ** [database connection]; setting a new progress handler cancels the
  2593. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2594. ** ^The progress handler is also disabled by setting N to a value less
  2595. ** than 1.
  2596. **
  2597. ** ^If the progress callback returns non-zero, the operation is
  2598. ** interrupted. This feature can be used to implement a
  2599. ** "Cancel" button on a GUI progress dialog box.
  2600. **
  2601. ** The progress handler callback must not do anything that will modify
  2602. ** the database connection that invoked the progress handler.
  2603. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2604. ** database connections for the meaning of "modify" in this paragraph.
  2605. **
  2606. */
  2607. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2608. /*
  2609. ** CAPI3REF: Opening A New Database Connection
  2610. **
  2611. ** ^These routines open an SQLite database file as specified by the
  2612. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2613. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2614. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2615. ** returned in *ppDb, even if an error occurs. The only exception is that
  2616. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2617. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2618. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2619. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2620. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2621. ** an English language description of the error following a failure of any
  2622. ** of the sqlite3_open() routines.
  2623. **
  2624. ** ^The default encoding for the database will be UTF-8 if
  2625. ** sqlite3_open() or sqlite3_open_v2() is called and
  2626. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2627. **
  2628. ** Whether or not an error occurs when it is opened, resources
  2629. ** associated with the [database connection] handle should be released by
  2630. ** passing it to [sqlite3_close()] when it is no longer required.
  2631. **
  2632. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2633. ** except that it accepts two additional parameters for additional control
  2634. ** over the new database connection. ^(The flags parameter to
  2635. ** sqlite3_open_v2() can take one of
  2636. ** the following three values, optionally combined with the
  2637. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2638. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2639. **
  2640. ** <dl>
  2641. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2642. ** <dd>The database is opened in read-only mode. If the database does not
  2643. ** already exist, an error is returned.</dd>)^
  2644. **
  2645. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2646. ** <dd>The database is opened for reading and writing if possible, or reading
  2647. ** only if the file is write protected by the operating system. In either
  2648. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2649. **
  2650. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2651. ** <dd>The database is opened for reading and writing, and is created if
  2652. ** it does not already exist. This is the behavior that is always used for
  2653. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2654. ** </dl>
  2655. **
  2656. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2657. ** combinations shown above optionally combined with other
  2658. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2659. ** then the behavior is undefined.
  2660. **
  2661. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2662. ** opens in the multi-thread [threading mode] as long as the single-thread
  2663. ** mode has not been set at compile-time or start-time. ^If the
  2664. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2665. ** in the serialized [threading mode] unless single-thread was
  2666. ** previously selected at compile-time or start-time.
  2667. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2668. ** eligible to use [shared cache mode], regardless of whether or not shared
  2669. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2670. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2671. ** participate in [shared cache mode] even if it is enabled.
  2672. **
  2673. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2674. ** [sqlite3_vfs] object that defines the operating system interface that
  2675. ** the new database connection should use. ^If the fourth parameter is
  2676. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2677. **
  2678. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2679. ** is created for the connection. ^This in-memory database will vanish when
  2680. ** the database connection is closed. Future versions of SQLite might
  2681. ** make use of additional special filenames that begin with the ":" character.
  2682. ** It is recommended that when a database filename actually does begin with
  2683. ** a ":" character you should prefix the filename with a pathname such as
  2684. ** "./" to avoid ambiguity.
  2685. **
  2686. ** ^If the filename is an empty string, then a private, temporary
  2687. ** on-disk database will be created. ^This private database will be
  2688. ** automatically deleted as soon as the database connection is closed.
  2689. **
  2690. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2691. **
  2692. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2693. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2694. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2695. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2696. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2697. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2698. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2699. ** by default, but future releases of SQLite might enable URI filename
  2700. ** interpretation by default. See "[URI filenames]" for additional
  2701. ** information.
  2702. **
  2703. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2704. ** authority, then it must be either an empty string or the string
  2705. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2706. ** error is returned to the caller. ^The fragment component of a URI, if
  2707. ** present, is ignored.
  2708. **
  2709. ** ^SQLite uses the path component of the URI as the name of the disk file
  2710. ** which contains the database. ^If the path begins with a '/' character,
  2711. ** then it is interpreted as an absolute path. ^If the path does not begin
  2712. ** with a '/' (meaning that the authority section is omitted from the URI)
  2713. ** then the path is interpreted as a relative path.
  2714. ** ^On windows, the first component of an absolute path
  2715. ** is a drive specification (e.g. "C:").
  2716. **
  2717. ** [[core URI query parameters]]
  2718. ** The query component of a URI may contain parameters that are interpreted
  2719. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2720. ** SQLite interprets the following three query parameters:
  2721. **
  2722. ** <ul>
  2723. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2724. ** a VFS object that provides the operating system interface that should
  2725. ** be used to access the database file on disk. ^If this option is set to
  2726. ** an empty string the default VFS object is used. ^Specifying an unknown
  2727. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2728. ** present, then the VFS specified by the option takes precedence over
  2729. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2730. **
  2731. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2732. ** "rwc", or "memory". Attempting to set it to any other value is
  2733. ** an error)^.
  2734. ** ^If "ro" is specified, then the database is opened for read-only
  2735. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2736. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2737. ** "rw", then the database is opened for read-write (but not create)
  2738. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2739. ** been set. ^Value "rwc" is equivalent to setting both
  2740. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2741. ** set to "memory" then a pure [in-memory database] that never reads
  2742. ** or writes from disk is used. ^It is an error to specify a value for
  2743. ** the mode parameter that is less restrictive than that specified by
  2744. ** the flags passed in the third parameter to sqlite3_open_v2().
  2745. **
  2746. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2747. ** "private". ^Setting it to "shared" is equivalent to setting the
  2748. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2749. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2750. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2751. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2752. ** a URI filename, its value overrides any behavior requested by setting
  2753. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2754. ** </ul>
  2755. **
  2756. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2757. ** error. Future versions of SQLite might understand additional query
  2758. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2759. ** additional information.
  2760. **
  2761. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2762. **
  2763. ** <table border="1" align=center cellpadding=5>
  2764. ** <tr><th> URI filenames <th> Results
  2765. ** <tr><td> file:data.db <td>
  2766. ** Open the file "data.db" in the current directory.
  2767. ** <tr><td> file:/home/fred/data.db<br>
  2768. ** file:///home/fred/data.db <br>
  2769. ** file://localhost/home/fred/data.db <br> <td>
  2770. ** Open the database file "/home/fred/data.db".
  2771. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2772. ** An error. "darkstar" is not a recognized authority.
  2773. ** <tr><td style="white-space:nowrap">
  2774. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2775. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2776. ** C:. Note that the %20 escaping in this example is not strictly
  2777. ** necessary - space characters can be used literally
  2778. ** in URI filenames.
  2779. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2780. ** Open file "data.db" in the current directory for read-only access.
  2781. ** Regardless of whether or not shared-cache mode is enabled by
  2782. ** default, use a private cache.
  2783. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  2784. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  2785. ** <tr><td> file:data.db?mode=readonly <td>
  2786. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2787. ** </table>
  2788. **
  2789. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2790. ** query components of a URI. A hexadecimal escape sequence consists of a
  2791. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2792. ** specifying an octet value. ^Before the path or query components of a
  2793. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2794. ** hexadecimal escape sequences replaced by a single byte containing the
  2795. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2796. ** the results are undefined.
  2797. **
  2798. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2799. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2800. ** codepage is currently defined. Filenames containing international
  2801. ** characters must be converted to UTF-8 prior to passing them into
  2802. ** sqlite3_open() or sqlite3_open_v2().
  2803. **
  2804. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2805. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2806. ** features that require the use of temporary files may fail.
  2807. **
  2808. ** See also: [sqlite3_temp_directory]
  2809. */
  2810. SQLITE_API int sqlite3_open(
  2811. const char *filename, /* Database filename (UTF-8) */
  2812. sqlite3 **ppDb /* OUT: SQLite db handle */
  2813. );
  2814. SQLITE_API int sqlite3_open16(
  2815. const void *filename, /* Database filename (UTF-16) */
  2816. sqlite3 **ppDb /* OUT: SQLite db handle */
  2817. );
  2818. SQLITE_API int sqlite3_open_v2(
  2819. const char *filename, /* Database filename (UTF-8) */
  2820. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2821. int flags, /* Flags */
  2822. const char *zVfs /* Name of VFS module to use */
  2823. );
  2824. /*
  2825. ** CAPI3REF: Obtain Values For URI Parameters
  2826. **
  2827. ** These are utility routines, useful to VFS implementations, that check
  2828. ** to see if a database file was a URI that contained a specific query
  2829. ** parameter, and if so obtains the value of that query parameter.
  2830. **
  2831. ** If F is the database filename pointer passed into the xOpen() method of
  2832. ** a VFS implementation when the flags parameter to xOpen() has one or
  2833. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2834. ** P is the name of the query parameter, then
  2835. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2836. ** parameter if it exists or a NULL pointer if P does not appear as a
  2837. ** query parameter on F. If P is a query parameter of F
  2838. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2839. ** a pointer to an empty string.
  2840. **
  2841. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2842. ** parameter and returns true (1) or false (0) according to the value
  2843. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2844. ** value of query parameter P is one of "yes", "true", or "on" in any
  2845. ** case or if the value begins with a non-zero number. The
  2846. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2847. ** query parameter P is one of "no", "false", or "off" in any case or
  2848. ** if the value begins with a numeric zero. If P is not a query
  2849. ** parameter on F or if the value of P is does not match any of the
  2850. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2851. **
  2852. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2853. ** 64-bit signed integer and returns that integer, or D if P does not
  2854. ** exist. If the value of P is something other than an integer, then
  2855. ** zero is returned.
  2856. **
  2857. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2858. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2859. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2860. ** VFS method, then the behavior of this routine is undefined and probably
  2861. ** undesirable.
  2862. */
  2863. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2864. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  2865. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2866. /*
  2867. ** CAPI3REF: Error Codes And Messages
  2868. **
  2869. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2870. ** [extended result code] for the most recent failed sqlite3_* API call
  2871. ** associated with a [database connection]. If a prior API call failed
  2872. ** but the most recent API call succeeded, the return value from
  2873. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  2874. ** interface is the same except that it always returns the
  2875. ** [extended result code] even when extended result codes are
  2876. ** disabled.
  2877. **
  2878. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2879. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2880. ** ^(Memory to hold the error message string is managed internally.
  2881. ** The application does not need to worry about freeing the result.
  2882. ** However, the error string might be overwritten or deallocated by
  2883. ** subsequent calls to other SQLite interface functions.)^
  2884. **
  2885. ** ^The sqlite3_errstr() interface returns the English-language text
  2886. ** that describes the [result code], as UTF-8.
  2887. ** ^(Memory to hold the error message string is managed internally
  2888. ** and must not be freed by the application)^.
  2889. **
  2890. ** When the serialized [threading mode] is in use, it might be the
  2891. ** case that a second error occurs on a separate thread in between
  2892. ** the time of the first error and the call to these interfaces.
  2893. ** When that happens, the second error will be reported since these
  2894. ** interfaces always report the most recent result. To avoid
  2895. ** this, each thread can obtain exclusive use of the [database connection] D
  2896. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2897. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2898. ** all calls to the interfaces listed here are completed.
  2899. **
  2900. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2901. ** was invoked incorrectly by the application. In that case, the
  2902. ** error code and message may or may not be set.
  2903. */
  2904. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2905. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2906. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2907. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2908. SQLITE_API const char *sqlite3_errstr(int);
  2909. /*
  2910. ** CAPI3REF: SQL Statement Object
  2911. ** KEYWORDS: {prepared statement} {prepared statements}
  2912. **
  2913. ** An instance of this object represents a single SQL statement.
  2914. ** This object is variously known as a "prepared statement" or a
  2915. ** "compiled SQL statement" or simply as a "statement".
  2916. **
  2917. ** The life of a statement object goes something like this:
  2918. **
  2919. ** <ol>
  2920. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2921. ** function.
  2922. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2923. ** interfaces.
  2924. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2925. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2926. ** to step 2. Do this zero or more times.
  2927. ** <li> Destroy the object using [sqlite3_finalize()].
  2928. ** </ol>
  2929. **
  2930. ** Refer to documentation on individual methods above for additional
  2931. ** information.
  2932. */
  2933. typedef struct sqlite3_stmt sqlite3_stmt;
  2934. /*
  2935. ** CAPI3REF: Run-time Limits
  2936. **
  2937. ** ^(This interface allows the size of various constructs to be limited
  2938. ** on a connection by connection basis. The first parameter is the
  2939. ** [database connection] whose limit is to be set or queried. The
  2940. ** second parameter is one of the [limit categories] that define a
  2941. ** class of constructs to be size limited. The third parameter is the
  2942. ** new limit for that construct.)^
  2943. **
  2944. ** ^If the new limit is a negative number, the limit is unchanged.
  2945. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  2946. ** [limits | hard upper bound]
  2947. ** set at compile-time by a C preprocessor macro called
  2948. ** [limits | SQLITE_MAX_<i>NAME</i>].
  2949. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  2950. ** ^Attempts to increase a limit above its hard upper bound are
  2951. ** silently truncated to the hard upper bound.
  2952. **
  2953. ** ^Regardless of whether or not the limit was changed, the
  2954. ** [sqlite3_limit()] interface returns the prior value of the limit.
  2955. ** ^Hence, to find the current value of a limit without changing it,
  2956. ** simply invoke this interface with the third parameter set to -1.
  2957. **
  2958. ** Run-time limits are intended for use in applications that manage
  2959. ** both their own internal database and also databases that are controlled
  2960. ** by untrusted external sources. An example application might be a
  2961. ** web browser that has its own databases for storing history and
  2962. ** separate databases controlled by JavaScript applications downloaded
  2963. ** off the Internet. The internal databases can be given the
  2964. ** large, default limits. Databases managed by external sources can
  2965. ** be given much smaller limits designed to prevent a denial of service
  2966. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2967. ** interface to further control untrusted SQL. The size of the database
  2968. ** created by an untrusted script can be contained using the
  2969. ** [max_page_count] [PRAGMA].
  2970. **
  2971. ** New run-time limit categories may be added in future releases.
  2972. */
  2973. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2974. /*
  2975. ** CAPI3REF: Run-Time Limit Categories
  2976. ** KEYWORDS: {limit category} {*limit categories}
  2977. **
  2978. ** These constants define various performance limits
  2979. ** that can be lowered at run-time using [sqlite3_limit()].
  2980. ** The synopsis of the meanings of the various limits is shown below.
  2981. ** Additional information is available at [limits | Limits in SQLite].
  2982. **
  2983. ** <dl>
  2984. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  2985. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  2986. **
  2987. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2988. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  2989. **
  2990. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  2991. ** <dd>The maximum number of columns in a table definition or in the
  2992. ** result set of a [SELECT] or the maximum number of columns in an index
  2993. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  2994. **
  2995. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2996. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  2997. **
  2998. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2999. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3000. **
  3001. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3002. ** <dd>The maximum number of instructions in a virtual machine program
  3003. ** used to implement an SQL statement. This limit is not currently
  3004. ** enforced, though that might be added in some future release of
  3005. ** SQLite.</dd>)^
  3006. **
  3007. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3008. ** <dd>The maximum number of arguments on a function.</dd>)^
  3009. **
  3010. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3011. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3012. **
  3013. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3014. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3015. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3016. ** [GLOB] operators.</dd>)^
  3017. **
  3018. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3019. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3020. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3021. **
  3022. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3023. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3024. ** </dl>
  3025. */
  3026. #define SQLITE_LIMIT_LENGTH 0
  3027. #define SQLITE_LIMIT_SQL_LENGTH 1
  3028. #define SQLITE_LIMIT_COLUMN 2
  3029. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3030. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3031. #define SQLITE_LIMIT_VDBE_OP 5
  3032. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3033. #define SQLITE_LIMIT_ATTACHED 7
  3034. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3035. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3036. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3037. /*
  3038. ** CAPI3REF: Compiling An SQL Statement
  3039. ** KEYWORDS: {SQL statement compiler}
  3040. **
  3041. ** To execute an SQL query, it must first be compiled into a byte-code
  3042. ** program using one of these routines.
  3043. **
  3044. ** The first argument, "db", is a [database connection] obtained from a
  3045. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3046. ** [sqlite3_open16()]. The database connection must not have been closed.
  3047. **
  3048. ** The second argument, "zSql", is the statement to be compiled, encoded
  3049. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3050. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3051. ** use UTF-16.
  3052. **
  3053. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3054. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3055. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3056. ** zSql string ends at either the first '\000' or '\u0000' character or
  3057. ** the nByte-th byte, whichever comes first. If the caller knows
  3058. ** that the supplied string is nul-terminated, then there is a small
  3059. ** performance advantage to be gained by passing an nByte parameter that
  3060. ** is equal to the number of bytes in the input string <i>including</i>
  3061. ** the nul-terminator bytes as this saves SQLite from having to
  3062. ** make a copy of the input string.
  3063. **
  3064. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3065. ** past the end of the first SQL statement in zSql. These routines only
  3066. ** compile the first statement in zSql, so *pzTail is left pointing to
  3067. ** what remains uncompiled.
  3068. **
  3069. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3070. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3071. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3072. ** string or a comment) then *ppStmt is set to NULL.
  3073. ** The calling procedure is responsible for deleting the compiled
  3074. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3075. ** ppStmt may not be NULL.
  3076. **
  3077. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3078. ** otherwise an [error code] is returned.
  3079. **
  3080. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3081. ** recommended for all new programs. The two older interfaces are retained
  3082. ** for backwards compatibility, but their use is discouraged.
  3083. ** ^In the "v2" interfaces, the prepared statement
  3084. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3085. ** original SQL text. This causes the [sqlite3_step()] interface to
  3086. ** behave differently in three ways:
  3087. **
  3088. ** <ol>
  3089. ** <li>
  3090. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3091. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3092. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3093. ** retries will occur before sqlite3_step() gives up and returns an error.
  3094. ** </li>
  3095. **
  3096. ** <li>
  3097. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3098. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3099. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3100. ** and the application would have to make a second call to [sqlite3_reset()]
  3101. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3102. ** interfaces, the underlying reason for the error is returned immediately.
  3103. ** </li>
  3104. **
  3105. ** <li>
  3106. ** ^If the specific value bound to [parameter | host parameter] in the
  3107. ** WHERE clause might influence the choice of query plan for a statement,
  3108. ** then the statement will be automatically recompiled, as if there had been
  3109. ** a schema change, on the first [sqlite3_step()] call following any change
  3110. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3111. ** ^The specific value of WHERE-clause [parameter] might influence the
  3112. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3113. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3114. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3115. ** the
  3116. ** </li>
  3117. ** </ol>
  3118. */
  3119. SQLITE_API int sqlite3_prepare(
  3120. sqlite3 *db, /* Database handle */
  3121. const char *zSql, /* SQL statement, UTF-8 encoded */
  3122. int nByte, /* Maximum length of zSql in bytes. */
  3123. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3124. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3125. );
  3126. SQLITE_API int sqlite3_prepare_v2(
  3127. sqlite3 *db, /* Database handle */
  3128. const char *zSql, /* SQL statement, UTF-8 encoded */
  3129. int nByte, /* Maximum length of zSql in bytes. */
  3130. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3131. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3132. );
  3133. SQLITE_API int sqlite3_prepare16(
  3134. sqlite3 *db, /* Database handle */
  3135. const void *zSql, /* SQL statement, UTF-16 encoded */
  3136. int nByte, /* Maximum length of zSql in bytes. */
  3137. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3138. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3139. );
  3140. SQLITE_API int sqlite3_prepare16_v2(
  3141. sqlite3 *db, /* Database handle */
  3142. const void *zSql, /* SQL statement, UTF-16 encoded */
  3143. int nByte, /* Maximum length of zSql in bytes. */
  3144. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3145. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3146. );
  3147. /*
  3148. ** CAPI3REF: Retrieving Statement SQL
  3149. **
  3150. ** ^This interface can be used to retrieve a saved copy of the original
  3151. ** SQL text used to create a [prepared statement] if that statement was
  3152. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3153. */
  3154. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3155. /*
  3156. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3157. **
  3158. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3159. ** and only if the [prepared statement] X makes no direct changes to
  3160. ** the content of the database file.
  3161. **
  3162. ** Note that [application-defined SQL functions] or
  3163. ** [virtual tables] might change the database indirectly as a side effect.
  3164. ** ^(For example, if an application defines a function "eval()" that
  3165. ** calls [sqlite3_exec()], then the following SQL statement would
  3166. ** change the database file through side-effects:
  3167. **
  3168. ** <blockquote><pre>
  3169. ** SELECT eval('DELETE FROM t1') FROM t2;
  3170. ** </pre></blockquote>
  3171. **
  3172. ** But because the [SELECT] statement does not change the database file
  3173. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3174. **
  3175. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3176. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3177. ** since the statements themselves do not actually modify the database but
  3178. ** rather they control the timing of when other statements modify the
  3179. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3180. ** sqlite3_stmt_readonly() to return true since, while those statements
  3181. ** change the configuration of a database connection, they do not make
  3182. ** changes to the content of the database files on disk.
  3183. */
  3184. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3185. /*
  3186. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3187. **
  3188. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3189. ** [prepared statement] S has been stepped at least once using
  3190. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3191. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3192. ** interface returns false if S is a NULL pointer. If S is not a
  3193. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3194. ** object, then the behavior is undefined and probably undesirable.
  3195. **
  3196. ** This interface can be used in combination [sqlite3_next_stmt()]
  3197. ** to locate all prepared statements associated with a database
  3198. ** connection that are in need of being reset. This can be used,
  3199. ** for example, in diagnostic routines to search for prepared
  3200. ** statements that are holding a transaction open.
  3201. */
  3202. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3203. /*
  3204. ** CAPI3REF: Dynamically Typed Value Object
  3205. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3206. **
  3207. ** SQLite uses the sqlite3_value object to represent all values
  3208. ** that can be stored in a database table. SQLite uses dynamic typing
  3209. ** for the values it stores. ^Values stored in sqlite3_value objects
  3210. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3211. **
  3212. ** An sqlite3_value object may be either "protected" or "unprotected".
  3213. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3214. ** will accept either a protected or an unprotected sqlite3_value.
  3215. ** Every interface that accepts sqlite3_value arguments specifies
  3216. ** whether or not it requires a protected sqlite3_value.
  3217. **
  3218. ** The terms "protected" and "unprotected" refer to whether or not
  3219. ** a mutex is held. An internal mutex is held for a protected
  3220. ** sqlite3_value object but no mutex is held for an unprotected
  3221. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3222. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3223. ** or if SQLite is run in one of reduced mutex modes
  3224. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3225. ** then there is no distinction between protected and unprotected
  3226. ** sqlite3_value objects and they can be used interchangeably. However,
  3227. ** for maximum code portability it is recommended that applications
  3228. ** still make the distinction between protected and unprotected
  3229. ** sqlite3_value objects even when not strictly required.
  3230. **
  3231. ** ^The sqlite3_value objects that are passed as parameters into the
  3232. ** implementation of [application-defined SQL functions] are protected.
  3233. ** ^The sqlite3_value object returned by
  3234. ** [sqlite3_column_value()] is unprotected.
  3235. ** Unprotected sqlite3_value objects may only be used with
  3236. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3237. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3238. ** interfaces require protected sqlite3_value objects.
  3239. */
  3240. typedef struct Mem sqlite3_value;
  3241. /*
  3242. ** CAPI3REF: SQL Function Context Object
  3243. **
  3244. ** The context in which an SQL function executes is stored in an
  3245. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3246. ** is always first parameter to [application-defined SQL functions].
  3247. ** The application-defined SQL function implementation will pass this
  3248. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3249. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3250. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3251. ** and/or [sqlite3_set_auxdata()].
  3252. */
  3253. typedef struct sqlite3_context sqlite3_context;
  3254. /*
  3255. ** CAPI3REF: Binding Values To Prepared Statements
  3256. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3257. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3258. **
  3259. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3260. ** literals may be replaced by a [parameter] that matches one of following
  3261. ** templates:
  3262. **
  3263. ** <ul>
  3264. ** <li> ?
  3265. ** <li> ?NNN
  3266. ** <li> :VVV
  3267. ** <li> @VVV
  3268. ** <li> $VVV
  3269. ** </ul>
  3270. **
  3271. ** In the templates above, NNN represents an integer literal,
  3272. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3273. ** parameters (also called "host parameter names" or "SQL parameters")
  3274. ** can be set using the sqlite3_bind_*() routines defined here.
  3275. **
  3276. ** ^The first argument to the sqlite3_bind_*() routines is always
  3277. ** a pointer to the [sqlite3_stmt] object returned from
  3278. ** [sqlite3_prepare_v2()] or its variants.
  3279. **
  3280. ** ^The second argument is the index of the SQL parameter to be set.
  3281. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3282. ** SQL parameter is used more than once, second and subsequent
  3283. ** occurrences have the same index as the first occurrence.
  3284. ** ^The index for named parameters can be looked up using the
  3285. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3286. ** for "?NNN" parameters is the value of NNN.
  3287. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3288. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3289. **
  3290. ** ^The third argument is the value to bind to the parameter.
  3291. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3292. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3293. ** is ignored and the end result is the same as sqlite3_bind_null().
  3294. **
  3295. ** ^(In those routines that have a fourth argument, its value is the
  3296. ** number of bytes in the parameter. To be clear: the value is the
  3297. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3298. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3299. ** is negative, then the length of the string is
  3300. ** the number of bytes up to the first zero terminator.
  3301. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3302. ** the behavior is undefined.
  3303. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3304. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3305. ** where the NUL terminator would occur assuming the string were NUL
  3306. ** terminated. If any NUL characters occur at byte offsets less than
  3307. ** the value of the fourth parameter then the resulting string value will
  3308. ** contain embedded NULs. The result of expressions involving strings
  3309. ** with embedded NULs is undefined.
  3310. **
  3311. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3312. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3313. ** string after SQLite has finished with it. ^The destructor is called
  3314. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3315. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3316. ** ^If the fifth argument is
  3317. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3318. ** information is in static, unmanaged space and does not need to be freed.
  3319. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3320. ** SQLite makes its own private copy of the data immediately, before
  3321. ** the sqlite3_bind_*() routine returns.
  3322. **
  3323. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3324. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3325. ** (just an integer to hold its size) while it is being processed.
  3326. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3327. ** content is later written using
  3328. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3329. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3330. **
  3331. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3332. ** for the [prepared statement] or with a prepared statement for which
  3333. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3334. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3335. ** routine is passed a [prepared statement] that has been finalized, the
  3336. ** result is undefined and probably harmful.
  3337. **
  3338. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3339. ** ^Unbound parameters are interpreted as NULL.
  3340. **
  3341. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3342. ** [error code] if anything goes wrong.
  3343. ** ^[SQLITE_RANGE] is returned if the parameter
  3344. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3345. **
  3346. ** See also: [sqlite3_bind_parameter_count()],
  3347. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3348. */
  3349. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3350. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3351. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3352. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3353. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3354. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3355. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3356. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3357. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3358. /*
  3359. ** CAPI3REF: Number Of SQL Parameters
  3360. **
  3361. ** ^This routine can be used to find the number of [SQL parameters]
  3362. ** in a [prepared statement]. SQL parameters are tokens of the
  3363. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3364. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3365. ** to the parameters at a later time.
  3366. **
  3367. ** ^(This routine actually returns the index of the largest (rightmost)
  3368. ** parameter. For all forms except ?NNN, this will correspond to the
  3369. ** number of unique parameters. If parameters of the ?NNN form are used,
  3370. ** there may be gaps in the list.)^
  3371. **
  3372. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3373. ** [sqlite3_bind_parameter_name()], and
  3374. ** [sqlite3_bind_parameter_index()].
  3375. */
  3376. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3377. /*
  3378. ** CAPI3REF: Name Of A Host Parameter
  3379. **
  3380. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3381. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3382. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3383. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3384. ** respectively.
  3385. ** In other words, the initial ":" or "$" or "@" or "?"
  3386. ** is included as part of the name.)^
  3387. ** ^Parameters of the form "?" without a following integer have no name
  3388. ** and are referred to as "nameless" or "anonymous parameters".
  3389. **
  3390. ** ^The first host parameter has an index of 1, not 0.
  3391. **
  3392. ** ^If the value N is out of range or if the N-th parameter is
  3393. ** nameless, then NULL is returned. ^The returned string is
  3394. ** always in UTF-8 encoding even if the named parameter was
  3395. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3396. ** [sqlite3_prepare16_v2()].
  3397. **
  3398. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3399. ** [sqlite3_bind_parameter_count()], and
  3400. ** [sqlite3_bind_parameter_index()].
  3401. */
  3402. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3403. /*
  3404. ** CAPI3REF: Index Of A Parameter With A Given Name
  3405. **
  3406. ** ^Return the index of an SQL parameter given its name. ^The
  3407. ** index value returned is suitable for use as the second
  3408. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3409. ** is returned if no matching parameter is found. ^The parameter
  3410. ** name must be given in UTF-8 even if the original statement
  3411. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3412. **
  3413. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3414. ** [sqlite3_bind_parameter_count()], and
  3415. ** [sqlite3_bind_parameter_index()].
  3416. */
  3417. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3418. /*
  3419. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3420. **
  3421. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3422. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3423. ** ^Use this routine to reset all host parameters to NULL.
  3424. */
  3425. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3426. /*
  3427. ** CAPI3REF: Number Of Columns In A Result Set
  3428. **
  3429. ** ^Return the number of columns in the result set returned by the
  3430. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3431. ** statement that does not return data (for example an [UPDATE]).
  3432. **
  3433. ** See also: [sqlite3_data_count()]
  3434. */
  3435. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3436. /*
  3437. ** CAPI3REF: Column Names In A Result Set
  3438. **
  3439. ** ^These routines return the name assigned to a particular column
  3440. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3441. ** interface returns a pointer to a zero-terminated UTF-8 string
  3442. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3443. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3444. ** that implements the [SELECT] statement. ^The second parameter is the
  3445. ** column number. ^The leftmost column is number 0.
  3446. **
  3447. ** ^The returned string pointer is valid until either the [prepared statement]
  3448. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3449. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3450. ** or until the next call to
  3451. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3452. **
  3453. ** ^If sqlite3_malloc() fails during the processing of either routine
  3454. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3455. ** NULL pointer is returned.
  3456. **
  3457. ** ^The name of a result column is the value of the "AS" clause for
  3458. ** that column, if there is an AS clause. If there is no AS clause
  3459. ** then the name of the column is unspecified and may change from
  3460. ** one release of SQLite to the next.
  3461. */
  3462. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3463. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3464. /*
  3465. ** CAPI3REF: Source Of Data In A Query Result
  3466. **
  3467. ** ^These routines provide a means to determine the database, table, and
  3468. ** table column that is the origin of a particular result column in
  3469. ** [SELECT] statement.
  3470. ** ^The name of the database or table or column can be returned as
  3471. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3472. ** the database name, the _table_ routines return the table name, and
  3473. ** the origin_ routines return the column name.
  3474. ** ^The returned string is valid until the [prepared statement] is destroyed
  3475. ** using [sqlite3_finalize()] or until the statement is automatically
  3476. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3477. ** or until the same information is requested
  3478. ** again in a different encoding.
  3479. **
  3480. ** ^The names returned are the original un-aliased names of the
  3481. ** database, table, and column.
  3482. **
  3483. ** ^The first argument to these interfaces is a [prepared statement].
  3484. ** ^These functions return information about the Nth result column returned by
  3485. ** the statement, where N is the second function argument.
  3486. ** ^The left-most column is column 0 for these routines.
  3487. **
  3488. ** ^If the Nth column returned by the statement is an expression or
  3489. ** subquery and is not a column value, then all of these functions return
  3490. ** NULL. ^These routine might also return NULL if a memory allocation error
  3491. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3492. ** or column that query result column was extracted from.
  3493. **
  3494. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3495. ** UTF-16 encoded strings and the other functions return UTF-8.
  3496. **
  3497. ** ^These APIs are only available if the library was compiled with the
  3498. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3499. **
  3500. ** If two or more threads call one or more of these routines against the same
  3501. ** prepared statement and column at the same time then the results are
  3502. ** undefined.
  3503. **
  3504. ** If two or more threads call one or more
  3505. ** [sqlite3_column_database_name | column metadata interfaces]
  3506. ** for the same [prepared statement] and result column
  3507. ** at the same time then the results are undefined.
  3508. */
  3509. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3510. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3511. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3512. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3513. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3514. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3515. /*
  3516. ** CAPI3REF: Declared Datatype Of A Query Result
  3517. **
  3518. ** ^(The first parameter is a [prepared statement].
  3519. ** If this statement is a [SELECT] statement and the Nth column of the
  3520. ** returned result set of that [SELECT] is a table column (not an
  3521. ** expression or subquery) then the declared type of the table
  3522. ** column is returned.)^ ^If the Nth column of the result set is an
  3523. ** expression or subquery, then a NULL pointer is returned.
  3524. ** ^The returned string is always UTF-8 encoded.
  3525. **
  3526. ** ^(For example, given the database schema:
  3527. **
  3528. ** CREATE TABLE t1(c1 VARIANT);
  3529. **
  3530. ** and the following statement to be compiled:
  3531. **
  3532. ** SELECT c1 + 1, c1 FROM t1;
  3533. **
  3534. ** this routine would return the string "VARIANT" for the second result
  3535. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3536. **
  3537. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3538. ** is declared to contain a particular type does not mean that the
  3539. ** data stored in that column is of the declared type. SQLite is
  3540. ** strongly typed, but the typing is dynamic not static. ^Type
  3541. ** is associated with individual values, not with the containers
  3542. ** used to hold those values.
  3543. */
  3544. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3545. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3546. /*
  3547. ** CAPI3REF: Evaluate An SQL Statement
  3548. **
  3549. ** After a [prepared statement] has been prepared using either
  3550. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3551. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3552. ** must be called one or more times to evaluate the statement.
  3553. **
  3554. ** The details of the behavior of the sqlite3_step() interface depend
  3555. ** on whether the statement was prepared using the newer "v2" interface
  3556. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3557. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3558. ** new "v2" interface is recommended for new applications but the legacy
  3559. ** interface will continue to be supported.
  3560. **
  3561. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3562. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3563. ** ^With the "v2" interface, any of the other [result codes] or
  3564. ** [extended result codes] might be returned as well.
  3565. **
  3566. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3567. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3568. ** or occurs outside of an explicit transaction, then you can retry the
  3569. ** statement. If the statement is not a [COMMIT] and occurs within an
  3570. ** explicit transaction then you should rollback the transaction before
  3571. ** continuing.
  3572. **
  3573. ** ^[SQLITE_DONE] means that the statement has finished executing
  3574. ** successfully. sqlite3_step() should not be called again on this virtual
  3575. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3576. ** machine back to its initial state.
  3577. **
  3578. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3579. ** is returned each time a new row of data is ready for processing by the
  3580. ** caller. The values may be accessed using the [column access functions].
  3581. ** sqlite3_step() is called again to retrieve the next row of data.
  3582. **
  3583. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3584. ** violation) has occurred. sqlite3_step() should not be called again on
  3585. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3586. ** ^With the legacy interface, a more specific error code (for example,
  3587. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3588. ** can be obtained by calling [sqlite3_reset()] on the
  3589. ** [prepared statement]. ^In the "v2" interface,
  3590. ** the more specific error code is returned directly by sqlite3_step().
  3591. **
  3592. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3593. ** Perhaps it was called on a [prepared statement] that has
  3594. ** already been [sqlite3_finalize | finalized] or on one that had
  3595. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3596. ** be the case that the same database connection is being used by two or
  3597. ** more threads at the same moment in time.
  3598. **
  3599. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3600. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3601. ** other than [SQLITE_ROW] before any subsequent invocation of
  3602. ** sqlite3_step(). Failure to reset the prepared statement using
  3603. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3604. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3605. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3606. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3607. ** break because any application that ever receives an SQLITE_MISUSE error
  3608. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3609. ** can be used to restore the legacy behavior.
  3610. **
  3611. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3612. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3613. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3614. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3615. ** specific [error codes] that better describes the error.
  3616. ** We admit that this is a goofy design. The problem has been fixed
  3617. ** with the "v2" interface. If you prepare all of your SQL statements
  3618. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3619. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3620. ** then the more specific [error codes] are returned directly
  3621. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3622. */
  3623. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3624. /*
  3625. ** CAPI3REF: Number of columns in a result set
  3626. **
  3627. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3628. ** current row of the result set of [prepared statement] P.
  3629. ** ^If prepared statement P does not have results ready to return
  3630. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3631. ** interfaces) then sqlite3_data_count(P) returns 0.
  3632. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3633. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3634. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3635. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3636. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3637. ** where it always returns zero since each step of that multi-step
  3638. ** pragma returns 0 columns of data.
  3639. **
  3640. ** See also: [sqlite3_column_count()]
  3641. */
  3642. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3643. /*
  3644. ** CAPI3REF: Fundamental Datatypes
  3645. ** KEYWORDS: SQLITE_TEXT
  3646. **
  3647. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3648. **
  3649. ** <ul>
  3650. ** <li> 64-bit signed integer
  3651. ** <li> 64-bit IEEE floating point number
  3652. ** <li> string
  3653. ** <li> BLOB
  3654. ** <li> NULL
  3655. ** </ul>)^
  3656. **
  3657. ** These constants are codes for each of those types.
  3658. **
  3659. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3660. ** for a completely different meaning. Software that links against both
  3661. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3662. ** SQLITE_TEXT.
  3663. */
  3664. #define SQLITE_INTEGER 1
  3665. #define SQLITE_FLOAT 2
  3666. #define SQLITE_BLOB 4
  3667. #define SQLITE_NULL 5
  3668. #ifdef SQLITE_TEXT
  3669. # undef SQLITE_TEXT
  3670. #else
  3671. # define SQLITE_TEXT 3
  3672. #endif
  3673. #define SQLITE3_TEXT 3
  3674. /*
  3675. ** CAPI3REF: Result Values From A Query
  3676. ** KEYWORDS: {column access functions}
  3677. **
  3678. ** These routines form the "result set" interface.
  3679. **
  3680. ** ^These routines return information about a single column of the current
  3681. ** result row of a query. ^In every case the first argument is a pointer
  3682. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3683. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3684. ** and the second argument is the index of the column for which information
  3685. ** should be returned. ^The leftmost column of the result set has the index 0.
  3686. ** ^The number of columns in the result can be determined using
  3687. ** [sqlite3_column_count()].
  3688. **
  3689. ** If the SQL statement does not currently point to a valid row, or if the
  3690. ** column index is out of range, the result is undefined.
  3691. ** These routines may only be called when the most recent call to
  3692. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3693. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3694. ** If any of these routines are called after [sqlite3_reset()] or
  3695. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3696. ** something other than [SQLITE_ROW], the results are undefined.
  3697. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3698. ** are called from a different thread while any of these routines
  3699. ** are pending, then the results are undefined.
  3700. **
  3701. ** ^The sqlite3_column_type() routine returns the
  3702. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3703. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3704. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3705. ** returned by sqlite3_column_type() is only meaningful if no type
  3706. ** conversions have occurred as described below. After a type conversion,
  3707. ** the value returned by sqlite3_column_type() is undefined. Future
  3708. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3709. ** following a type conversion.
  3710. **
  3711. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3712. ** routine returns the number of bytes in that BLOB or string.
  3713. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3714. ** the string to UTF-8 and then returns the number of bytes.
  3715. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3716. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3717. ** the number of bytes in that string.
  3718. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3719. **
  3720. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3721. ** routine returns the number of bytes in that BLOB or string.
  3722. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3723. ** the string to UTF-16 and then returns the number of bytes.
  3724. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3725. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3726. ** the number of bytes in that string.
  3727. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3728. **
  3729. ** ^The values returned by [sqlite3_column_bytes()] and
  3730. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3731. ** of the string. ^For clarity: the values returned by
  3732. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3733. ** bytes in the string, not the number of characters.
  3734. **
  3735. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3736. ** even empty strings, are always zero-terminated. ^The return
  3737. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3738. **
  3739. ** ^The object returned by [sqlite3_column_value()] is an
  3740. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3741. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3742. ** If the [unprotected sqlite3_value] object returned by
  3743. ** [sqlite3_column_value()] is used in any other way, including calls
  3744. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3745. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3746. **
  3747. ** These routines attempt to convert the value where appropriate. ^For
  3748. ** example, if the internal representation is FLOAT and a text result
  3749. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3750. ** conversion automatically. ^(The following table details the conversions
  3751. ** that are applied:
  3752. **
  3753. ** <blockquote>
  3754. ** <table border="1">
  3755. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3756. **
  3757. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3758. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3759. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3760. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3761. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3762. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3763. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3764. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3765. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3766. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3767. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3768. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3769. ** <tr><td> TEXT <td> BLOB <td> No change
  3770. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3771. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3772. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3773. ** </table>
  3774. ** </blockquote>)^
  3775. **
  3776. ** The table above makes reference to standard C library functions atoi()
  3777. ** and atof(). SQLite does not really use these functions. It has its
  3778. ** own equivalent internal routines. The atoi() and atof() names are
  3779. ** used in the table for brevity and because they are familiar to most
  3780. ** C programmers.
  3781. **
  3782. ** Note that when type conversions occur, pointers returned by prior
  3783. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3784. ** sqlite3_column_text16() may be invalidated.
  3785. ** Type conversions and pointer invalidations might occur
  3786. ** in the following cases:
  3787. **
  3788. ** <ul>
  3789. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3790. ** sqlite3_column_text16() is called. A zero-terminator might
  3791. ** need to be added to the string.</li>
  3792. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3793. ** sqlite3_column_text16() is called. The content must be converted
  3794. ** to UTF-16.</li>
  3795. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3796. ** sqlite3_column_text() is called. The content must be converted
  3797. ** to UTF-8.</li>
  3798. ** </ul>
  3799. **
  3800. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3801. ** not invalidate a prior pointer, though of course the content of the buffer
  3802. ** that the prior pointer references will have been modified. Other kinds
  3803. ** of conversion are done in place when it is possible, but sometimes they
  3804. ** are not possible and in those cases prior pointers are invalidated.
  3805. **
  3806. ** The safest and easiest to remember policy is to invoke these routines
  3807. ** in one of the following ways:
  3808. **
  3809. ** <ul>
  3810. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3811. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3812. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3813. ** </ul>
  3814. **
  3815. ** In other words, you should call sqlite3_column_text(),
  3816. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3817. ** into the desired format, then invoke sqlite3_column_bytes() or
  3818. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3819. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3820. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3821. ** with calls to sqlite3_column_bytes().
  3822. **
  3823. ** ^The pointers returned are valid until a type conversion occurs as
  3824. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3825. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3826. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3827. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3828. ** [sqlite3_free()].
  3829. **
  3830. ** ^(If a memory allocation error occurs during the evaluation of any
  3831. ** of these routines, a default value is returned. The default value
  3832. ** is either the integer 0, the floating point number 0.0, or a NULL
  3833. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3834. ** [SQLITE_NOMEM].)^
  3835. */
  3836. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3837. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3838. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3839. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3840. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3841. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3842. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3843. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3844. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3845. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3846. /*
  3847. ** CAPI3REF: Destroy A Prepared Statement Object
  3848. **
  3849. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  3850. ** ^If the most recent evaluation of the statement encountered no errors
  3851. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  3852. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  3853. ** sqlite3_finalize(S) returns the appropriate [error code] or
  3854. ** [extended error code].
  3855. **
  3856. ** ^The sqlite3_finalize(S) routine can be called at any point during
  3857. ** the life cycle of [prepared statement] S:
  3858. ** before statement S is ever evaluated, after
  3859. ** one or more calls to [sqlite3_reset()], or after any call
  3860. ** to [sqlite3_step()] regardless of whether or not the statement has
  3861. ** completed execution.
  3862. **
  3863. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  3864. **
  3865. ** The application must finalize every [prepared statement] in order to avoid
  3866. ** resource leaks. It is a grievous error for the application to try to use
  3867. ** a prepared statement after it has been finalized. Any use of a prepared
  3868. ** statement after it has been finalized can result in undefined and
  3869. ** undesirable behavior such as segfaults and heap corruption.
  3870. */
  3871. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3872. /*
  3873. ** CAPI3REF: Reset A Prepared Statement Object
  3874. **
  3875. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3876. ** object back to its initial state, ready to be re-executed.
  3877. ** ^Any SQL statement variables that had values bound to them using
  3878. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3879. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3880. **
  3881. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3882. ** back to the beginning of its program.
  3883. **
  3884. ** ^If the most recent call to [sqlite3_step(S)] for the
  3885. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3886. ** or if [sqlite3_step(S)] has never before been called on S,
  3887. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3888. **
  3889. ** ^If the most recent call to [sqlite3_step(S)] for the
  3890. ** [prepared statement] S indicated an error, then
  3891. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3892. **
  3893. ** ^The [sqlite3_reset(S)] interface does not change the values
  3894. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3895. */
  3896. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3897. /*
  3898. ** CAPI3REF: Create Or Redefine SQL Functions
  3899. ** KEYWORDS: {function creation routines}
  3900. ** KEYWORDS: {application-defined SQL function}
  3901. ** KEYWORDS: {application-defined SQL functions}
  3902. **
  3903. ** ^These functions (collectively known as "function creation routines")
  3904. ** are used to add SQL functions or aggregates or to redefine the behavior
  3905. ** of existing SQL functions or aggregates. The only differences between
  3906. ** these routines are the text encoding expected for
  3907. ** the second parameter (the name of the function being created)
  3908. ** and the presence or absence of a destructor callback for
  3909. ** the application data pointer.
  3910. **
  3911. ** ^The first parameter is the [database connection] to which the SQL
  3912. ** function is to be added. ^If an application uses more than one database
  3913. ** connection then application-defined SQL functions must be added
  3914. ** to each database connection separately.
  3915. **
  3916. ** ^The second parameter is the name of the SQL function to be created or
  3917. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  3918. ** representation, exclusive of the zero-terminator. ^Note that the name
  3919. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  3920. ** ^Any attempt to create a function with a longer name
  3921. ** will result in [SQLITE_MISUSE] being returned.
  3922. **
  3923. ** ^The third parameter (nArg)
  3924. ** is the number of arguments that the SQL function or
  3925. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  3926. ** aggregate may take any number of arguments between 0 and the limit
  3927. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  3928. ** parameter is less than -1 or greater than 127 then the behavior is
  3929. ** undefined.
  3930. **
  3931. ** ^The fourth parameter, eTextRep, specifies what
  3932. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3933. ** its parameters. Every SQL function implementation must be able to work
  3934. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3935. ** more efficient with one encoding than another. ^An application may
  3936. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3937. ** times with the same function but with different values of eTextRep.
  3938. ** ^When multiple implementations of the same function are available, SQLite
  3939. ** will pick the one that involves the least amount of data conversion.
  3940. ** If there is only a single implementation which does not care what text
  3941. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3942. **
  3943. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  3944. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  3945. **
  3946. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  3947. ** pointers to C-language functions that implement the SQL function or
  3948. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  3949. ** callback only; NULL pointers must be passed as the xStep and xFinal
  3950. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  3951. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  3952. ** SQL function or aggregate, pass NULL pointers for all three function
  3953. ** callbacks.
  3954. **
  3955. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  3956. ** then it is destructor for the application data pointer.
  3957. ** The destructor is invoked when the function is deleted, either by being
  3958. ** overloaded or when the database connection closes.)^
  3959. ** ^The destructor is also invoked if the call to
  3960. ** sqlite3_create_function_v2() fails.
  3961. ** ^When the destructor callback of the tenth parameter is invoked, it
  3962. ** is passed a single argument which is a copy of the application data
  3963. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  3964. **
  3965. ** ^It is permitted to register multiple implementations of the same
  3966. ** functions with the same name but with either differing numbers of
  3967. ** arguments or differing preferred text encodings. ^SQLite will use
  3968. ** the implementation that most closely matches the way in which the
  3969. ** SQL function is used. ^A function implementation with a non-negative
  3970. ** nArg parameter is a better match than a function implementation with
  3971. ** a negative nArg. ^A function where the preferred text encoding
  3972. ** matches the database encoding is a better
  3973. ** match than a function where the encoding is different.
  3974. ** ^A function where the encoding difference is between UTF16le and UTF16be
  3975. ** is a closer match than a function where the encoding difference is
  3976. ** between UTF8 and UTF16.
  3977. **
  3978. ** ^Built-in functions may be overloaded by new application-defined functions.
  3979. **
  3980. ** ^An application-defined function is permitted to call other
  3981. ** SQLite interfaces. However, such calls must not
  3982. ** close the database connection nor finalize or reset the prepared
  3983. ** statement in which the function is running.
  3984. */
  3985. SQLITE_API int sqlite3_create_function(
  3986. sqlite3 *db,
  3987. const char *zFunctionName,
  3988. int nArg,
  3989. int eTextRep,
  3990. void *pApp,
  3991. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3992. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3993. void (*xFinal)(sqlite3_context*)
  3994. );
  3995. SQLITE_API int sqlite3_create_function16(
  3996. sqlite3 *db,
  3997. const void *zFunctionName,
  3998. int nArg,
  3999. int eTextRep,
  4000. void *pApp,
  4001. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4002. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4003. void (*xFinal)(sqlite3_context*)
  4004. );
  4005. SQLITE_API int sqlite3_create_function_v2(
  4006. sqlite3 *db,
  4007. const char *zFunctionName,
  4008. int nArg,
  4009. int eTextRep,
  4010. void *pApp,
  4011. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4012. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4013. void (*xFinal)(sqlite3_context*),
  4014. void(*xDestroy)(void*)
  4015. );
  4016. /*
  4017. ** CAPI3REF: Text Encodings
  4018. **
  4019. ** These constant define integer codes that represent the various
  4020. ** text encodings supported by SQLite.
  4021. */
  4022. #define SQLITE_UTF8 1
  4023. #define SQLITE_UTF16LE 2
  4024. #define SQLITE_UTF16BE 3
  4025. #define SQLITE_UTF16 4 /* Use native byte order */
  4026. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  4027. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4028. /*
  4029. ** CAPI3REF: Deprecated Functions
  4030. ** DEPRECATED
  4031. **
  4032. ** These functions are [deprecated]. In order to maintain
  4033. ** backwards compatibility with older code, these functions continue
  4034. ** to be supported. However, new applications should avoid
  4035. ** the use of these functions. To help encourage people to avoid
  4036. ** using these functions, we are not going to tell you what they do.
  4037. */
  4038. #ifndef SQLITE_OMIT_DEPRECATED
  4039. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4040. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4041. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4042. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4043. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4044. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4045. void*,sqlite3_int64);
  4046. #endif
  4047. /*
  4048. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4049. **
  4050. ** The C-language implementation of SQL functions and aggregates uses
  4051. ** this set of interface routines to access the parameter values on
  4052. ** the function or aggregate.
  4053. **
  4054. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4055. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4056. ** define callbacks that implement the SQL functions and aggregates.
  4057. ** The 3rd parameter to these callbacks is an array of pointers to
  4058. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4059. ** each parameter to the SQL function. These routines are used to
  4060. ** extract values from the [sqlite3_value] objects.
  4061. **
  4062. ** These routines work only with [protected sqlite3_value] objects.
  4063. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4064. ** object results in undefined behavior.
  4065. **
  4066. ** ^These routines work just like the corresponding [column access functions]
  4067. ** except that these routines take a single [protected sqlite3_value] object
  4068. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4069. **
  4070. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4071. ** in the native byte-order of the host machine. ^The
  4072. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4073. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4074. **
  4075. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4076. ** numeric affinity to the value. This means that an attempt is
  4077. ** made to convert the value to an integer or floating point. If
  4078. ** such a conversion is possible without loss of information (in other
  4079. ** words, if the value is a string that looks like a number)
  4080. ** then the conversion is performed. Otherwise no conversion occurs.
  4081. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4082. **
  4083. ** Please pay particular attention to the fact that the pointer returned
  4084. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4085. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4086. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4087. ** or [sqlite3_value_text16()].
  4088. **
  4089. ** These routines must be called from the same thread as
  4090. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4091. */
  4092. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4093. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4094. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4095. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4096. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4097. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4098. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4099. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4100. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4101. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4102. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4103. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4104. /*
  4105. ** CAPI3REF: Obtain Aggregate Function Context
  4106. **
  4107. ** Implementations of aggregate SQL functions use this
  4108. ** routine to allocate memory for storing their state.
  4109. **
  4110. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4111. ** for a particular aggregate function, SQLite
  4112. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4113. ** to the new memory. ^On second and subsequent calls to
  4114. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4115. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4116. ** called once for each invocation of the xStep callback and then one
  4117. ** last time when the xFinal callback is invoked. ^(When no rows match
  4118. ** an aggregate query, the xStep() callback of the aggregate function
  4119. ** implementation is never called and xFinal() is called exactly once.
  4120. ** In those cases, sqlite3_aggregate_context() might be called for the
  4121. ** first time from within xFinal().)^
  4122. **
  4123. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4124. ** when first called if N is less than or equal to zero or if a memory
  4125. ** allocate error occurs.
  4126. **
  4127. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4128. ** determined by the N parameter on first successful call. Changing the
  4129. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4130. ** the same aggregate function instance will not resize the memory
  4131. ** allocation.)^ Within the xFinal callback, it is customary to set
  4132. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4133. ** pointless memory allocations occur.
  4134. **
  4135. ** ^SQLite automatically frees the memory allocated by
  4136. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4137. **
  4138. ** The first parameter must be a copy of the
  4139. ** [sqlite3_context | SQL function context] that is the first parameter
  4140. ** to the xStep or xFinal callback routine that implements the aggregate
  4141. ** function.
  4142. **
  4143. ** This routine must be called from the same thread in which
  4144. ** the aggregate SQL function is running.
  4145. */
  4146. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4147. /*
  4148. ** CAPI3REF: User Data For Functions
  4149. **
  4150. ** ^The sqlite3_user_data() interface returns a copy of
  4151. ** the pointer that was the pUserData parameter (the 5th parameter)
  4152. ** of the [sqlite3_create_function()]
  4153. ** and [sqlite3_create_function16()] routines that originally
  4154. ** registered the application defined function.
  4155. **
  4156. ** This routine must be called from the same thread in which
  4157. ** the application-defined function is running.
  4158. */
  4159. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4160. /*
  4161. ** CAPI3REF: Database Connection For Functions
  4162. **
  4163. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4164. ** the pointer to the [database connection] (the 1st parameter)
  4165. ** of the [sqlite3_create_function()]
  4166. ** and [sqlite3_create_function16()] routines that originally
  4167. ** registered the application defined function.
  4168. */
  4169. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4170. /*
  4171. ** CAPI3REF: Function Auxiliary Data
  4172. **
  4173. ** These functions may be used by (non-aggregate) SQL functions to
  4174. ** associate metadata with argument values. If the same value is passed to
  4175. ** multiple invocations of the same SQL function during query execution, under
  4176. ** some circumstances the associated metadata may be preserved. An example
  4177. ** of where this might be useful is in a regular-expression matching
  4178. ** function. The compiled version of the regular expression can be stored as
  4179. ** metadata associated with the pattern string.
  4180. ** Then as long as the pattern string remains the same,
  4181. ** the compiled regular expression can be reused on multiple
  4182. ** invocations of the same function.
  4183. **
  4184. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4185. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4186. ** value to the application-defined function. ^If there is no metadata
  4187. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4188. ** returns a NULL pointer.
  4189. **
  4190. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4191. ** argument of the application-defined function. ^Subsequent
  4192. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4193. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4194. ** NULL if the metadata has been discarded.
  4195. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4196. ** SQLite will invoke the destructor function X with parameter P exactly
  4197. ** once, when the metadata is discarded.
  4198. ** SQLite is free to discard the metadata at any time, including: <ul>
  4199. ** <li> when the corresponding function parameter changes, or
  4200. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4201. ** SQL statement, or
  4202. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4203. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4204. ** allocation error occurs. </ul>)^
  4205. **
  4206. ** Note the last bullet in particular. The destructor X in
  4207. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4208. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4209. ** should be called near the end of the function implementation and the
  4210. ** function implementation should not make any use of P after
  4211. ** sqlite3_set_auxdata() has been called.
  4212. **
  4213. ** ^(In practice, metadata is preserved between function calls for
  4214. ** function parameters that are compile-time constants, including literal
  4215. ** values and [parameters] and expressions composed from the same.)^
  4216. **
  4217. ** These routines must be called from the same thread in which
  4218. ** the SQL function is running.
  4219. */
  4220. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4221. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4222. /*
  4223. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4224. **
  4225. ** These are special values for the destructor that is passed in as the
  4226. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4227. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4228. ** and will never change. It does not need to be destroyed. ^The
  4229. ** SQLITE_TRANSIENT value means that the content will likely change in
  4230. ** the near future and that SQLite should make its own private copy of
  4231. ** the content before returning.
  4232. **
  4233. ** The typedef is necessary to work around problems in certain
  4234. ** C++ compilers.
  4235. */
  4236. typedef void (*sqlite3_destructor_type)(void*);
  4237. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4238. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4239. /*
  4240. ** CAPI3REF: Setting The Result Of An SQL Function
  4241. **
  4242. ** These routines are used by the xFunc or xFinal callbacks that
  4243. ** implement SQL functions and aggregates. See
  4244. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4245. ** for additional information.
  4246. **
  4247. ** These functions work very much like the [parameter binding] family of
  4248. ** functions used to bind values to host parameters in prepared statements.
  4249. ** Refer to the [SQL parameter] documentation for additional information.
  4250. **
  4251. ** ^The sqlite3_result_blob() interface sets the result from
  4252. ** an application-defined function to be the BLOB whose content is pointed
  4253. ** to by the second parameter and which is N bytes long where N is the
  4254. ** third parameter.
  4255. **
  4256. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4257. ** the application-defined function to be a BLOB containing all zero
  4258. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4259. **
  4260. ** ^The sqlite3_result_double() interface sets the result from
  4261. ** an application-defined function to be a floating point value specified
  4262. ** by its 2nd argument.
  4263. **
  4264. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4265. ** cause the implemented SQL function to throw an exception.
  4266. ** ^SQLite uses the string pointed to by the
  4267. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4268. ** as the text of an error message. ^SQLite interprets the error
  4269. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4270. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4271. ** byte order. ^If the third parameter to sqlite3_result_error()
  4272. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4273. ** message all text up through the first zero character.
  4274. ** ^If the third parameter to sqlite3_result_error() or
  4275. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4276. ** bytes (not characters) from the 2nd parameter as the error message.
  4277. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4278. ** routines make a private copy of the error message text before
  4279. ** they return. Hence, the calling function can deallocate or
  4280. ** modify the text after they return without harm.
  4281. ** ^The sqlite3_result_error_code() function changes the error code
  4282. ** returned by SQLite as a result of an error in a function. ^By default,
  4283. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4284. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4285. **
  4286. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4287. ** error indicating that a string or BLOB is too long to represent.
  4288. **
  4289. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4290. ** error indicating that a memory allocation failed.
  4291. **
  4292. ** ^The sqlite3_result_int() interface sets the return value
  4293. ** of the application-defined function to be the 32-bit signed integer
  4294. ** value given in the 2nd argument.
  4295. ** ^The sqlite3_result_int64() interface sets the return value
  4296. ** of the application-defined function to be the 64-bit signed integer
  4297. ** value given in the 2nd argument.
  4298. **
  4299. ** ^The sqlite3_result_null() interface sets the return value
  4300. ** of the application-defined function to be NULL.
  4301. **
  4302. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4303. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4304. ** set the return value of the application-defined function to be
  4305. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4306. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4307. ** ^SQLite takes the text result from the application from
  4308. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4309. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4310. ** is negative, then SQLite takes result text from the 2nd parameter
  4311. ** through the first zero character.
  4312. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4313. ** is non-negative, then as many bytes (not characters) of the text
  4314. ** pointed to by the 2nd parameter are taken as the application-defined
  4315. ** function result. If the 3rd parameter is non-negative, then it
  4316. ** must be the byte offset into the string where the NUL terminator would
  4317. ** appear if the string where NUL terminated. If any NUL characters occur
  4318. ** in the string at a byte offset that is less than the value of the 3rd
  4319. ** parameter, then the resulting string will contain embedded NULs and the
  4320. ** result of expressions operating on strings with embedded NULs is undefined.
  4321. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4322. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4323. ** function as the destructor on the text or BLOB result when it has
  4324. ** finished using that result.
  4325. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4326. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4327. ** assumes that the text or BLOB result is in constant space and does not
  4328. ** copy the content of the parameter nor call a destructor on the content
  4329. ** when it has finished using that result.
  4330. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4331. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4332. ** then SQLite makes a copy of the result into space obtained from
  4333. ** from [sqlite3_malloc()] before it returns.
  4334. **
  4335. ** ^The sqlite3_result_value() interface sets the result of
  4336. ** the application-defined function to be a copy the
  4337. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4338. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4339. ** so that the [sqlite3_value] specified in the parameter may change or
  4340. ** be deallocated after sqlite3_result_value() returns without harm.
  4341. ** ^A [protected sqlite3_value] object may always be used where an
  4342. ** [unprotected sqlite3_value] object is required, so either
  4343. ** kind of [sqlite3_value] object can be used with this interface.
  4344. **
  4345. ** If these routines are called from within the different thread
  4346. ** than the one containing the application-defined function that received
  4347. ** the [sqlite3_context] pointer, the results are undefined.
  4348. */
  4349. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4350. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4351. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4352. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4353. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4354. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4355. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4356. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4357. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4358. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4359. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4360. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4361. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4362. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4363. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4364. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4365. /*
  4366. ** CAPI3REF: Define New Collating Sequences
  4367. **
  4368. ** ^These functions add, remove, or modify a [collation] associated
  4369. ** with the [database connection] specified as the first argument.
  4370. **
  4371. ** ^The name of the collation is a UTF-8 string
  4372. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4373. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4374. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4375. ** considered to be the same name.
  4376. **
  4377. ** ^(The third argument (eTextRep) must be one of the constants:
  4378. ** <ul>
  4379. ** <li> [SQLITE_UTF8],
  4380. ** <li> [SQLITE_UTF16LE],
  4381. ** <li> [SQLITE_UTF16BE],
  4382. ** <li> [SQLITE_UTF16], or
  4383. ** <li> [SQLITE_UTF16_ALIGNED].
  4384. ** </ul>)^
  4385. ** ^The eTextRep argument determines the encoding of strings passed
  4386. ** to the collating function callback, xCallback.
  4387. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4388. ** force strings to be UTF16 with native byte order.
  4389. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4390. ** on an even byte address.
  4391. **
  4392. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4393. ** through as the first argument to the collating function callback.
  4394. **
  4395. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4396. ** ^Multiple collating functions can be registered using the same name but
  4397. ** with different eTextRep parameters and SQLite will use whichever
  4398. ** function requires the least amount of data transformation.
  4399. ** ^If the xCallback argument is NULL then the collating function is
  4400. ** deleted. ^When all collating functions having the same name are deleted,
  4401. ** that collation is no longer usable.
  4402. **
  4403. ** ^The collating function callback is invoked with a copy of the pArg
  4404. ** application data pointer and with two strings in the encoding specified
  4405. ** by the eTextRep argument. The collating function must return an
  4406. ** integer that is negative, zero, or positive
  4407. ** if the first string is less than, equal to, or greater than the second,
  4408. ** respectively. A collating function must always return the same answer
  4409. ** given the same inputs. If two or more collating functions are registered
  4410. ** to the same collation name (using different eTextRep values) then all
  4411. ** must give an equivalent answer when invoked with equivalent strings.
  4412. ** The collating function must obey the following properties for all
  4413. ** strings A, B, and C:
  4414. **
  4415. ** <ol>
  4416. ** <li> If A==B then B==A.
  4417. ** <li> If A==B and B==C then A==C.
  4418. ** <li> If A&lt;B THEN B&gt;A.
  4419. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4420. ** </ol>
  4421. **
  4422. ** If a collating function fails any of the above constraints and that
  4423. ** collating function is registered and used, then the behavior of SQLite
  4424. ** is undefined.
  4425. **
  4426. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4427. ** with the addition that the xDestroy callback is invoked on pArg when
  4428. ** the collating function is deleted.
  4429. ** ^Collating functions are deleted when they are overridden by later
  4430. ** calls to the collation creation functions or when the
  4431. ** [database connection] is closed using [sqlite3_close()].
  4432. **
  4433. ** ^The xDestroy callback is <u>not</u> called if the
  4434. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4435. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4436. ** check the return code and dispose of the application data pointer
  4437. ** themselves rather than expecting SQLite to deal with it for them.
  4438. ** This is different from every other SQLite interface. The inconsistency
  4439. ** is unfortunate but cannot be changed without breaking backwards
  4440. ** compatibility.
  4441. **
  4442. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4443. */
  4444. SQLITE_API int sqlite3_create_collation(
  4445. sqlite3*,
  4446. const char *zName,
  4447. int eTextRep,
  4448. void *pArg,
  4449. int(*xCompare)(void*,int,const void*,int,const void*)
  4450. );
  4451. SQLITE_API int sqlite3_create_collation_v2(
  4452. sqlite3*,
  4453. const char *zName,
  4454. int eTextRep,
  4455. void *pArg,
  4456. int(*xCompare)(void*,int,const void*,int,const void*),
  4457. void(*xDestroy)(void*)
  4458. );
  4459. SQLITE_API int sqlite3_create_collation16(
  4460. sqlite3*,
  4461. const void *zName,
  4462. int eTextRep,
  4463. void *pArg,
  4464. int(*xCompare)(void*,int,const void*,int,const void*)
  4465. );
  4466. /*
  4467. ** CAPI3REF: Collation Needed Callbacks
  4468. **
  4469. ** ^To avoid having to register all collation sequences before a database
  4470. ** can be used, a single callback function may be registered with the
  4471. ** [database connection] to be invoked whenever an undefined collation
  4472. ** sequence is required.
  4473. **
  4474. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4475. ** then it is passed the names of undefined collation sequences as strings
  4476. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4477. ** the names are passed as UTF-16 in machine native byte order.
  4478. ** ^A call to either function replaces the existing collation-needed callback.
  4479. **
  4480. ** ^(When the callback is invoked, the first argument passed is a copy
  4481. ** of the second argument to sqlite3_collation_needed() or
  4482. ** sqlite3_collation_needed16(). The second argument is the database
  4483. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4484. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4485. ** sequence function required. The fourth parameter is the name of the
  4486. ** required collation sequence.)^
  4487. **
  4488. ** The callback function should register the desired collation using
  4489. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4490. ** [sqlite3_create_collation_v2()].
  4491. */
  4492. SQLITE_API int sqlite3_collation_needed(
  4493. sqlite3*,
  4494. void*,
  4495. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4496. );
  4497. SQLITE_API int sqlite3_collation_needed16(
  4498. sqlite3*,
  4499. void*,
  4500. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4501. );
  4502. #ifdef SQLITE_HAS_CODEC
  4503. /*
  4504. ** Specify the key for an encrypted database. This routine should be
  4505. ** called right after sqlite3_open().
  4506. **
  4507. ** The code to implement this API is not available in the public release
  4508. ** of SQLite.
  4509. */
  4510. SQLITE_API int sqlite3_key(
  4511. sqlite3 *db, /* Database to be rekeyed */
  4512. const void *pKey, int nKey /* The key */
  4513. );
  4514. SQLITE_API int sqlite3_key_v2(
  4515. sqlite3 *db, /* Database to be rekeyed */
  4516. const char *zDbName, /* Name of the database */
  4517. const void *pKey, int nKey /* The key */
  4518. );
  4519. /*
  4520. ** Change the key on an open database. If the current database is not
  4521. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4522. ** database is decrypted.
  4523. **
  4524. ** The code to implement this API is not available in the public release
  4525. ** of SQLite.
  4526. */
  4527. SQLITE_API int sqlite3_rekey(
  4528. sqlite3 *db, /* Database to be rekeyed */
  4529. const void *pKey, int nKey /* The new key */
  4530. );
  4531. SQLITE_API int sqlite3_rekey_v2(
  4532. sqlite3 *db, /* Database to be rekeyed */
  4533. const char *zDbName, /* Name of the database */
  4534. const void *pKey, int nKey /* The new key */
  4535. );
  4536. /*
  4537. ** Specify the activation key for a SEE database. Unless
  4538. ** activated, none of the SEE routines will work.
  4539. */
  4540. SQLITE_API void sqlite3_activate_see(
  4541. const char *zPassPhrase /* Activation phrase */
  4542. );
  4543. #endif
  4544. #ifdef SQLITE_ENABLE_CEROD
  4545. /*
  4546. ** Specify the activation key for a CEROD database. Unless
  4547. ** activated, none of the CEROD routines will work.
  4548. */
  4549. SQLITE_API void sqlite3_activate_cerod(
  4550. const char *zPassPhrase /* Activation phrase */
  4551. );
  4552. #endif
  4553. /*
  4554. ** CAPI3REF: Suspend Execution For A Short Time
  4555. **
  4556. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4557. ** for at least a number of milliseconds specified in its parameter.
  4558. **
  4559. ** If the operating system does not support sleep requests with
  4560. ** millisecond time resolution, then the time will be rounded up to
  4561. ** the nearest second. The number of milliseconds of sleep actually
  4562. ** requested from the operating system is returned.
  4563. **
  4564. ** ^SQLite implements this interface by calling the xSleep()
  4565. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4566. ** of the default VFS is not implemented correctly, or not implemented at
  4567. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4568. ** in the previous paragraphs.
  4569. */
  4570. SQLITE_API int sqlite3_sleep(int);
  4571. /*
  4572. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4573. **
  4574. ** ^(If this global variable is made to point to a string which is
  4575. ** the name of a folder (a.k.a. directory), then all temporary files
  4576. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4577. ** will be placed in that directory.)^ ^If this variable
  4578. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4579. ** temporary file directory.
  4580. **
  4581. ** It is not safe to read or modify this variable in more than one
  4582. ** thread at a time. It is not safe to read or modify this variable
  4583. ** if a [database connection] is being used at the same time in a separate
  4584. ** thread.
  4585. ** It is intended that this variable be set once
  4586. ** as part of process initialization and before any SQLite interface
  4587. ** routines have been called and that this variable remain unchanged
  4588. ** thereafter.
  4589. **
  4590. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4591. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4592. ** the [temp_store_directory pragma] always assumes that any string
  4593. ** that this variable points to is held in memory obtained from
  4594. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4595. ** using [sqlite3_free].
  4596. ** Hence, if this variable is modified directly, either it should be
  4597. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4598. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4599. **
  4600. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4601. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4602. ** features that require the use of temporary files may fail. Here is an
  4603. ** example of how to do this using C++ with the Windows Runtime:
  4604. **
  4605. ** <blockquote><pre>
  4606. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4607. ** &nbsp; TemporaryFolder->Path->Data();
  4608. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4609. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4610. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4611. ** &nbsp; NULL, NULL);
  4612. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4613. ** </pre></blockquote>
  4614. */
  4615. SQLITE_API char *sqlite3_temp_directory;
  4616. /*
  4617. ** CAPI3REF: Name Of The Folder Holding Database Files
  4618. **
  4619. ** ^(If this global variable is made to point to a string which is
  4620. ** the name of a folder (a.k.a. directory), then all database files
  4621. ** specified with a relative pathname and created or accessed by
  4622. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4623. ** to be relative to that directory.)^ ^If this variable is a NULL
  4624. ** pointer, then SQLite assumes that all database files specified
  4625. ** with a relative pathname are relative to the current directory
  4626. ** for the process. Only the windows VFS makes use of this global
  4627. ** variable; it is ignored by the unix VFS.
  4628. **
  4629. ** Changing the value of this variable while a database connection is
  4630. ** open can result in a corrupt database.
  4631. **
  4632. ** It is not safe to read or modify this variable in more than one
  4633. ** thread at a time. It is not safe to read or modify this variable
  4634. ** if a [database connection] is being used at the same time in a separate
  4635. ** thread.
  4636. ** It is intended that this variable be set once
  4637. ** as part of process initialization and before any SQLite interface
  4638. ** routines have been called and that this variable remain unchanged
  4639. ** thereafter.
  4640. **
  4641. ** ^The [data_store_directory pragma] may modify this variable and cause
  4642. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4643. ** the [data_store_directory pragma] always assumes that any string
  4644. ** that this variable points to is held in memory obtained from
  4645. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4646. ** using [sqlite3_free].
  4647. ** Hence, if this variable is modified directly, either it should be
  4648. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4649. ** or else the use of the [data_store_directory pragma] should be avoided.
  4650. */
  4651. SQLITE_API char *sqlite3_data_directory;
  4652. /*
  4653. ** CAPI3REF: Test For Auto-Commit Mode
  4654. ** KEYWORDS: {autocommit mode}
  4655. **
  4656. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4657. ** zero if the given database connection is or is not in autocommit mode,
  4658. ** respectively. ^Autocommit mode is on by default.
  4659. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4660. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4661. **
  4662. ** If certain kinds of errors occur on a statement within a multi-statement
  4663. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4664. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4665. ** transaction might be rolled back automatically. The only way to
  4666. ** find out whether SQLite automatically rolled back the transaction after
  4667. ** an error is to use this function.
  4668. **
  4669. ** If another thread changes the autocommit status of the database
  4670. ** connection while this routine is running, then the return value
  4671. ** is undefined.
  4672. */
  4673. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4674. /*
  4675. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4676. **
  4677. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4678. ** to which a [prepared statement] belongs. ^The [database connection]
  4679. ** returned by sqlite3_db_handle is the same [database connection]
  4680. ** that was the first argument
  4681. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4682. ** create the statement in the first place.
  4683. */
  4684. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4685. /*
  4686. ** CAPI3REF: Return The Filename For A Database Connection
  4687. **
  4688. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4689. ** associated with database N of connection D. ^The main database file
  4690. ** has the name "main". If there is no attached database N on the database
  4691. ** connection D, or if database N is a temporary or in-memory database, then
  4692. ** a NULL pointer is returned.
  4693. **
  4694. ** ^The filename returned by this function is the output of the
  4695. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4696. ** will be an absolute pathname, even if the filename used
  4697. ** to open the database originally was a URI or relative pathname.
  4698. */
  4699. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4700. /*
  4701. ** CAPI3REF: Determine if a database is read-only
  4702. **
  4703. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4704. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4705. ** the name of a database on connection D.
  4706. */
  4707. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4708. /*
  4709. ** CAPI3REF: Find the next prepared statement
  4710. **
  4711. ** ^This interface returns a pointer to the next [prepared statement] after
  4712. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4713. ** then this interface returns a pointer to the first prepared statement
  4714. ** associated with the database connection pDb. ^If no prepared statement
  4715. ** satisfies the conditions of this routine, it returns NULL.
  4716. **
  4717. ** The [database connection] pointer D in a call to
  4718. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4719. ** connection and in particular must not be a NULL pointer.
  4720. */
  4721. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4722. /*
  4723. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4724. **
  4725. ** ^The sqlite3_commit_hook() interface registers a callback
  4726. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4727. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4728. ** for the same database connection is overridden.
  4729. ** ^The sqlite3_rollback_hook() interface registers a callback
  4730. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4731. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4732. ** for the same database connection is overridden.
  4733. ** ^The pArg argument is passed through to the callback.
  4734. ** ^If the callback on a commit hook function returns non-zero,
  4735. ** then the commit is converted into a rollback.
  4736. **
  4737. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4738. ** return the P argument from the previous call of the same function
  4739. ** on the same [database connection] D, or NULL for
  4740. ** the first call for each function on D.
  4741. **
  4742. ** The commit and rollback hook callbacks are not reentrant.
  4743. ** The callback implementation must not do anything that will modify
  4744. ** the database connection that invoked the callback. Any actions
  4745. ** to modify the database connection must be deferred until after the
  4746. ** completion of the [sqlite3_step()] call that triggered the commit
  4747. ** or rollback hook in the first place.
  4748. ** Note that running any other SQL statements, including SELECT statements,
  4749. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4750. ** the database connections for the meaning of "modify" in this paragraph.
  4751. **
  4752. ** ^Registering a NULL function disables the callback.
  4753. **
  4754. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4755. ** operation is allowed to continue normally. ^If the commit hook
  4756. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4757. ** ^The rollback hook is invoked on a rollback that results from a commit
  4758. ** hook returning non-zero, just as it would be with any other rollback.
  4759. **
  4760. ** ^For the purposes of this API, a transaction is said to have been
  4761. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4762. ** an error or constraint causes an implicit rollback to occur.
  4763. ** ^The rollback callback is not invoked if a transaction is
  4764. ** automatically rolled back because the database connection is closed.
  4765. **
  4766. ** See also the [sqlite3_update_hook()] interface.
  4767. */
  4768. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4769. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4770. /*
  4771. ** CAPI3REF: Data Change Notification Callbacks
  4772. **
  4773. ** ^The sqlite3_update_hook() interface registers a callback function
  4774. ** with the [database connection] identified by the first argument
  4775. ** to be invoked whenever a row is updated, inserted or deleted.
  4776. ** ^Any callback set by a previous call to this function
  4777. ** for the same database connection is overridden.
  4778. **
  4779. ** ^The second argument is a pointer to the function to invoke when a
  4780. ** row is updated, inserted or deleted.
  4781. ** ^The first argument to the callback is a copy of the third argument
  4782. ** to sqlite3_update_hook().
  4783. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4784. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4785. ** to be invoked.
  4786. ** ^The third and fourth arguments to the callback contain pointers to the
  4787. ** database and table name containing the affected row.
  4788. ** ^The final callback parameter is the [rowid] of the row.
  4789. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4790. **
  4791. ** ^(The update hook is not invoked when internal system tables are
  4792. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4793. **
  4794. ** ^In the current implementation, the update hook
  4795. ** is not invoked when duplication rows are deleted because of an
  4796. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4797. ** invoked when rows are deleted using the [truncate optimization].
  4798. ** The exceptions defined in this paragraph might change in a future
  4799. ** release of SQLite.
  4800. **
  4801. ** The update hook implementation must not do anything that will modify
  4802. ** the database connection that invoked the update hook. Any actions
  4803. ** to modify the database connection must be deferred until after the
  4804. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4805. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4806. ** database connections for the meaning of "modify" in this paragraph.
  4807. **
  4808. ** ^The sqlite3_update_hook(D,C,P) function
  4809. ** returns the P argument from the previous call
  4810. ** on the same [database connection] D, or NULL for
  4811. ** the first call on D.
  4812. **
  4813. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4814. ** interfaces.
  4815. */
  4816. SQLITE_API void *sqlite3_update_hook(
  4817. sqlite3*,
  4818. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4819. void*
  4820. );
  4821. /*
  4822. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4823. **
  4824. ** ^(This routine enables or disables the sharing of the database cache
  4825. ** and schema data structures between [database connection | connections]
  4826. ** to the same database. Sharing is enabled if the argument is true
  4827. ** and disabled if the argument is false.)^
  4828. **
  4829. ** ^Cache sharing is enabled and disabled for an entire process.
  4830. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4831. ** sharing was enabled or disabled for each thread separately.
  4832. **
  4833. ** ^(The cache sharing mode set by this interface effects all subsequent
  4834. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4835. ** Existing database connections continue use the sharing mode
  4836. ** that was in effect at the time they were opened.)^
  4837. **
  4838. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4839. ** successfully. An [error code] is returned otherwise.)^
  4840. **
  4841. ** ^Shared cache is disabled by default. But this might change in
  4842. ** future releases of SQLite. Applications that care about shared
  4843. ** cache setting should set it explicitly.
  4844. **
  4845. ** This interface is threadsafe on processors where writing a
  4846. ** 32-bit integer is atomic.
  4847. **
  4848. ** See Also: [SQLite Shared-Cache Mode]
  4849. */
  4850. SQLITE_API int sqlite3_enable_shared_cache(int);
  4851. /*
  4852. ** CAPI3REF: Attempt To Free Heap Memory
  4853. **
  4854. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  4855. ** of heap memory by deallocating non-essential memory allocations
  4856. ** held by the database library. Memory used to cache database
  4857. ** pages to improve performance is an example of non-essential memory.
  4858. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4859. ** which might be more or less than the amount requested.
  4860. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4861. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4862. **
  4863. ** See also: [sqlite3_db_release_memory()]
  4864. */
  4865. SQLITE_API int sqlite3_release_memory(int);
  4866. /*
  4867. ** CAPI3REF: Free Memory Used By A Database Connection
  4868. **
  4869. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  4870. ** memory as possible from database connection D. Unlike the
  4871. ** [sqlite3_release_memory()] interface, this interface is effect even
  4872. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  4873. ** omitted.
  4874. **
  4875. ** See also: [sqlite3_release_memory()]
  4876. */
  4877. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  4878. /*
  4879. ** CAPI3REF: Impose A Limit On Heap Size
  4880. **
  4881. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4882. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4883. ** ^SQLite strives to keep heap memory utilization below the soft heap
  4884. ** limit by reducing the number of pages held in the page cache
  4885. ** as heap memory usages approaches the limit.
  4886. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4887. ** below the limit, it will exceed the limit rather than generate
  4888. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  4889. ** is advisory only.
  4890. **
  4891. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4892. ** the soft heap limit prior to the call, or negative in the case of an
  4893. ** error. ^If the argument N is negative
  4894. ** then no change is made to the soft heap limit. Hence, the current
  4895. ** size of the soft heap limit can be determined by invoking
  4896. ** sqlite3_soft_heap_limit64() with a negative argument.
  4897. **
  4898. ** ^If the argument N is zero then the soft heap limit is disabled.
  4899. **
  4900. ** ^(The soft heap limit is not enforced in the current implementation
  4901. ** if one or more of following conditions are true:
  4902. **
  4903. ** <ul>
  4904. ** <li> The soft heap limit is set to zero.
  4905. ** <li> Memory accounting is disabled using a combination of the
  4906. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4907. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4908. ** <li> An alternative page cache implementation is specified using
  4909. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  4910. ** <li> The page cache allocates from its own memory pool supplied
  4911. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4912. ** from the heap.
  4913. ** </ul>)^
  4914. **
  4915. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4916. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  4917. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  4918. ** the soft heap limit is enforced on every memory allocation. Without
  4919. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  4920. ** when memory is allocated by the page cache. Testing suggests that because
  4921. ** the page cache is the predominate memory user in SQLite, most
  4922. ** applications will achieve adequate soft heap limit enforcement without
  4923. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4924. **
  4925. ** The circumstances under which SQLite will enforce the soft heap limit may
  4926. ** changes in future releases of SQLite.
  4927. */
  4928. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  4929. /*
  4930. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  4931. ** DEPRECATED
  4932. **
  4933. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  4934. ** interface. This routine is provided for historical compatibility
  4935. ** only. All new applications should use the
  4936. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  4937. */
  4938. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  4939. /*
  4940. ** CAPI3REF: Extract Metadata About A Column Of A Table
  4941. **
  4942. ** ^This routine returns metadata about a specific column of a specific
  4943. ** database table accessible using the [database connection] handle
  4944. ** passed as the first function argument.
  4945. **
  4946. ** ^The column is identified by the second, third and fourth parameters to
  4947. ** this function. ^The second parameter is either the name of the database
  4948. ** (i.e. "main", "temp", or an attached database) containing the specified
  4949. ** table or NULL. ^If it is NULL, then all attached databases are searched
  4950. ** for the table using the same algorithm used by the database engine to
  4951. ** resolve unqualified table references.
  4952. **
  4953. ** ^The third and fourth parameters to this function are the table and column
  4954. ** name of the desired column, respectively. Neither of these parameters
  4955. ** may be NULL.
  4956. **
  4957. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  4958. ** and subsequent parameters to this function. ^Any of these arguments may be
  4959. ** NULL, in which case the corresponding element of metadata is omitted.
  4960. **
  4961. ** ^(<blockquote>
  4962. ** <table border="1">
  4963. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4964. **
  4965. ** <tr><td> 5th <td> const char* <td> Data type
  4966. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4967. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4968. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4969. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4970. ** </table>
  4971. ** </blockquote>)^
  4972. **
  4973. ** ^The memory pointed to by the character pointers returned for the
  4974. ** declaration type and collation sequence is valid only until the next
  4975. ** call to any SQLite API function.
  4976. **
  4977. ** ^If the specified table is actually a view, an [error code] is returned.
  4978. **
  4979. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  4980. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4981. ** parameters are set for the explicitly declared column. ^(If there is no
  4982. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4983. ** parameters are set as follows:
  4984. **
  4985. ** <pre>
  4986. ** data type: "INTEGER"
  4987. ** collation sequence: "BINARY"
  4988. ** not null: 0
  4989. ** primary key: 1
  4990. ** auto increment: 0
  4991. ** </pre>)^
  4992. **
  4993. ** ^(This function may load one or more schemas from database files. If an
  4994. ** error occurs during this process, or if the requested table or column
  4995. ** cannot be found, an [error code] is returned and an error message left
  4996. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  4997. **
  4998. ** ^This API is only available if the library was compiled with the
  4999. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5000. */
  5001. SQLITE_API int sqlite3_table_column_metadata(
  5002. sqlite3 *db, /* Connection handle */
  5003. const char *zDbName, /* Database name or NULL */
  5004. const char *zTableName, /* Table name */
  5005. const char *zColumnName, /* Column name */
  5006. char const **pzDataType, /* OUTPUT: Declared data type */
  5007. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5008. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5009. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5010. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5011. );
  5012. /*
  5013. ** CAPI3REF: Load An Extension
  5014. **
  5015. ** ^This interface loads an SQLite extension library from the named file.
  5016. **
  5017. ** ^The sqlite3_load_extension() interface attempts to load an
  5018. ** [SQLite extension] library contained in the file zFile. If
  5019. ** the file cannot be loaded directly, attempts are made to load
  5020. ** with various operating-system specific extensions added.
  5021. ** So for example, if "samplelib" cannot be loaded, then names like
  5022. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5023. ** be tried also.
  5024. **
  5025. ** ^The entry point is zProc.
  5026. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5027. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5028. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5029. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5030. ** characters in the filename from the last "/" to the first following
  5031. ** "." and omitting any initial "lib".)^
  5032. ** ^The sqlite3_load_extension() interface returns
  5033. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5034. ** ^If an error occurs and pzErrMsg is not 0, then the
  5035. ** [sqlite3_load_extension()] interface shall attempt to
  5036. ** fill *pzErrMsg with error message text stored in memory
  5037. ** obtained from [sqlite3_malloc()]. The calling function
  5038. ** should free this memory by calling [sqlite3_free()].
  5039. **
  5040. ** ^Extension loading must be enabled using
  5041. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5042. ** otherwise an error will be returned.
  5043. **
  5044. ** See also the [load_extension() SQL function].
  5045. */
  5046. SQLITE_API int sqlite3_load_extension(
  5047. sqlite3 *db, /* Load the extension into this database connection */
  5048. const char *zFile, /* Name of the shared library containing extension */
  5049. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5050. char **pzErrMsg /* Put error message here if not 0 */
  5051. );
  5052. /*
  5053. ** CAPI3REF: Enable Or Disable Extension Loading
  5054. **
  5055. ** ^So as not to open security holes in older applications that are
  5056. ** unprepared to deal with [extension loading], and as a means of disabling
  5057. ** [extension loading] while evaluating user-entered SQL, the following API
  5058. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5059. **
  5060. ** ^Extension loading is off by default.
  5061. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5062. ** to turn extension loading on and call it with onoff==0 to turn
  5063. ** it back off again.
  5064. */
  5065. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5066. /*
  5067. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5068. **
  5069. ** ^This interface causes the xEntryPoint() function to be invoked for
  5070. ** each new [database connection] that is created. The idea here is that
  5071. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5072. ** that is to be automatically loaded into all new database connections.
  5073. **
  5074. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5075. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5076. ** arguments and expects and integer result as if the signature of the
  5077. ** entry point where as follows:
  5078. **
  5079. ** <blockquote><pre>
  5080. ** &nbsp; int xEntryPoint(
  5081. ** &nbsp; sqlite3 *db,
  5082. ** &nbsp; const char **pzErrMsg,
  5083. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5084. ** &nbsp; );
  5085. ** </pre></blockquote>)^
  5086. **
  5087. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5088. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5089. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5090. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5091. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5092. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5093. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5094. **
  5095. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5096. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5097. ** will be called more than once for each database connection that is opened.
  5098. **
  5099. ** See also: [sqlite3_reset_auto_extension()]
  5100. ** and [sqlite3_cancel_auto_extension()]
  5101. */
  5102. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5103. /*
  5104. ** CAPI3REF: Cancel Automatic Extension Loading
  5105. **
  5106. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5107. ** initialization routine X that was registered using a prior call to
  5108. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5109. ** routine returns 1 if initialization routine X was successfully
  5110. ** unregistered and it returns 0 if X was not on the list of initialization
  5111. ** routines.
  5112. */
  5113. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5114. /*
  5115. ** CAPI3REF: Reset Automatic Extension Loading
  5116. **
  5117. ** ^This interface disables all automatic extensions previously
  5118. ** registered using [sqlite3_auto_extension()].
  5119. */
  5120. SQLITE_API void sqlite3_reset_auto_extension(void);
  5121. /*
  5122. ** The interface to the virtual-table mechanism is currently considered
  5123. ** to be experimental. The interface might change in incompatible ways.
  5124. ** If this is a problem for you, do not use the interface at this time.
  5125. **
  5126. ** When the virtual-table mechanism stabilizes, we will declare the
  5127. ** interface fixed, support it indefinitely, and remove this comment.
  5128. */
  5129. /*
  5130. ** Structures used by the virtual table interface
  5131. */
  5132. typedef struct sqlite3_vtab sqlite3_vtab;
  5133. typedef struct sqlite3_index_info sqlite3_index_info;
  5134. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5135. typedef struct sqlite3_module sqlite3_module;
  5136. /*
  5137. ** CAPI3REF: Virtual Table Object
  5138. ** KEYWORDS: sqlite3_module {virtual table module}
  5139. **
  5140. ** This structure, sometimes called a "virtual table module",
  5141. ** defines the implementation of a [virtual tables].
  5142. ** This structure consists mostly of methods for the module.
  5143. **
  5144. ** ^A virtual table module is created by filling in a persistent
  5145. ** instance of this structure and passing a pointer to that instance
  5146. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5147. ** ^The registration remains valid until it is replaced by a different
  5148. ** module or until the [database connection] closes. The content
  5149. ** of this structure must not change while it is registered with
  5150. ** any database connection.
  5151. */
  5152. struct sqlite3_module {
  5153. int iVersion;
  5154. int (*xCreate)(sqlite3*, void *pAux,
  5155. int argc, const char *const*argv,
  5156. sqlite3_vtab **ppVTab, char**);
  5157. int (*xConnect)(sqlite3*, void *pAux,
  5158. int argc, const char *const*argv,
  5159. sqlite3_vtab **ppVTab, char**);
  5160. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5161. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5162. int (*xDestroy)(sqlite3_vtab *pVTab);
  5163. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5164. int (*xClose)(sqlite3_vtab_cursor*);
  5165. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5166. int argc, sqlite3_value **argv);
  5167. int (*xNext)(sqlite3_vtab_cursor*);
  5168. int (*xEof)(sqlite3_vtab_cursor*);
  5169. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5170. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5171. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5172. int (*xBegin)(sqlite3_vtab *pVTab);
  5173. int (*xSync)(sqlite3_vtab *pVTab);
  5174. int (*xCommit)(sqlite3_vtab *pVTab);
  5175. int (*xRollback)(sqlite3_vtab *pVTab);
  5176. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5177. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5178. void **ppArg);
  5179. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5180. /* The methods above are in version 1 of the sqlite_module object. Those
  5181. ** below are for version 2 and greater. */
  5182. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5183. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5184. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5185. };
  5186. /*
  5187. ** CAPI3REF: Virtual Table Indexing Information
  5188. ** KEYWORDS: sqlite3_index_info
  5189. **
  5190. ** The sqlite3_index_info structure and its substructures is used as part
  5191. ** of the [virtual table] interface to
  5192. ** pass information into and receive the reply from the [xBestIndex]
  5193. ** method of a [virtual table module]. The fields under **Inputs** are the
  5194. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5195. ** results into the **Outputs** fields.
  5196. **
  5197. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5198. **
  5199. ** <blockquote>column OP expr</blockquote>
  5200. **
  5201. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5202. ** stored in aConstraint[].op using one of the
  5203. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5204. ** ^(The index of the column is stored in
  5205. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5206. ** expr on the right-hand side can be evaluated (and thus the constraint
  5207. ** is usable) and false if it cannot.)^
  5208. **
  5209. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5210. ** and makes other simplifications to the WHERE clause in an attempt to
  5211. ** get as many WHERE clause terms into the form shown above as possible.
  5212. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5213. ** relevant to the particular virtual table being queried.
  5214. **
  5215. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5216. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5217. **
  5218. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5219. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5220. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5221. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5222. ** is true, then the constraint is assumed to be fully handled by the
  5223. ** virtual table and is not checked again by SQLite.)^
  5224. **
  5225. ** ^The idxNum and idxPtr values are recorded and passed into the
  5226. ** [xFilter] method.
  5227. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5228. ** needToFreeIdxPtr is true.
  5229. **
  5230. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5231. ** the correct order to satisfy the ORDER BY clause so that no separate
  5232. ** sorting step is required.
  5233. **
  5234. ** ^The estimatedCost value is an estimate of the cost of doing the
  5235. ** particular lookup. A full scan of a table with N entries should have
  5236. ** a cost of N. A binary search of a table of N entries should have a
  5237. ** cost of approximately log(N).
  5238. */
  5239. struct sqlite3_index_info {
  5240. /* Inputs */
  5241. int nConstraint; /* Number of entries in aConstraint */
  5242. struct sqlite3_index_constraint {
  5243. int iColumn; /* Column on left-hand side of constraint */
  5244. unsigned char op; /* Constraint operator */
  5245. unsigned char usable; /* True if this constraint is usable */
  5246. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5247. } *aConstraint; /* Table of WHERE clause constraints */
  5248. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5249. struct sqlite3_index_orderby {
  5250. int iColumn; /* Column number */
  5251. unsigned char desc; /* True for DESC. False for ASC. */
  5252. } *aOrderBy; /* The ORDER BY clause */
  5253. /* Outputs */
  5254. struct sqlite3_index_constraint_usage {
  5255. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5256. unsigned char omit; /* Do not code a test for this constraint */
  5257. } *aConstraintUsage;
  5258. int idxNum; /* Number used to identify the index */
  5259. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5260. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5261. int orderByConsumed; /* True if output is already ordered */
  5262. double estimatedCost; /* Estimated cost of using this index */
  5263. };
  5264. /*
  5265. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5266. **
  5267. ** These macros defined the allowed values for the
  5268. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5269. ** an operator that is part of a constraint term in the wHERE clause of
  5270. ** a query that uses a [virtual table].
  5271. */
  5272. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5273. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5274. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5275. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5276. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5277. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5278. /*
  5279. ** CAPI3REF: Register A Virtual Table Implementation
  5280. **
  5281. ** ^These routines are used to register a new [virtual table module] name.
  5282. ** ^Module names must be registered before
  5283. ** creating a new [virtual table] using the module and before using a
  5284. ** preexisting [virtual table] for the module.
  5285. **
  5286. ** ^The module name is registered on the [database connection] specified
  5287. ** by the first parameter. ^The name of the module is given by the
  5288. ** second parameter. ^The third parameter is a pointer to
  5289. ** the implementation of the [virtual table module]. ^The fourth
  5290. ** parameter is an arbitrary client data pointer that is passed through
  5291. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5292. ** when a new virtual table is be being created or reinitialized.
  5293. **
  5294. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5295. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5296. ** invoke the destructor function (if it is not NULL) when SQLite
  5297. ** no longer needs the pClientData pointer. ^The destructor will also
  5298. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5299. ** ^The sqlite3_create_module()
  5300. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5301. ** destructor.
  5302. */
  5303. SQLITE_API int sqlite3_create_module(
  5304. sqlite3 *db, /* SQLite connection to register module with */
  5305. const char *zName, /* Name of the module */
  5306. const sqlite3_module *p, /* Methods for the module */
  5307. void *pClientData /* Client data for xCreate/xConnect */
  5308. );
  5309. SQLITE_API int sqlite3_create_module_v2(
  5310. sqlite3 *db, /* SQLite connection to register module with */
  5311. const char *zName, /* Name of the module */
  5312. const sqlite3_module *p, /* Methods for the module */
  5313. void *pClientData, /* Client data for xCreate/xConnect */
  5314. void(*xDestroy)(void*) /* Module destructor function */
  5315. );
  5316. /*
  5317. ** CAPI3REF: Virtual Table Instance Object
  5318. ** KEYWORDS: sqlite3_vtab
  5319. **
  5320. ** Every [virtual table module] implementation uses a subclass
  5321. ** of this object to describe a particular instance
  5322. ** of the [virtual table]. Each subclass will
  5323. ** be tailored to the specific needs of the module implementation.
  5324. ** The purpose of this superclass is to define certain fields that are
  5325. ** common to all module implementations.
  5326. **
  5327. ** ^Virtual tables methods can set an error message by assigning a
  5328. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5329. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5330. ** prior to assigning a new string to zErrMsg. ^After the error message
  5331. ** is delivered up to the client application, the string will be automatically
  5332. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5333. */
  5334. struct sqlite3_vtab {
  5335. const sqlite3_module *pModule; /* The module for this virtual table */
  5336. int nRef; /* NO LONGER USED */
  5337. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5338. /* Virtual table implementations will typically add additional fields */
  5339. };
  5340. /*
  5341. ** CAPI3REF: Virtual Table Cursor Object
  5342. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5343. **
  5344. ** Every [virtual table module] implementation uses a subclass of the
  5345. ** following structure to describe cursors that point into the
  5346. ** [virtual table] and are used
  5347. ** to loop through the virtual table. Cursors are created using the
  5348. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5349. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5350. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5351. ** of the module. Each module implementation will define
  5352. ** the content of a cursor structure to suit its own needs.
  5353. **
  5354. ** This superclass exists in order to define fields of the cursor that
  5355. ** are common to all implementations.
  5356. */
  5357. struct sqlite3_vtab_cursor {
  5358. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5359. /* Virtual table implementations will typically add additional fields */
  5360. };
  5361. /*
  5362. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5363. **
  5364. ** ^The [xCreate] and [xConnect] methods of a
  5365. ** [virtual table module] call this interface
  5366. ** to declare the format (the names and datatypes of the columns) of
  5367. ** the virtual tables they implement.
  5368. */
  5369. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5370. /*
  5371. ** CAPI3REF: Overload A Function For A Virtual Table
  5372. **
  5373. ** ^(Virtual tables can provide alternative implementations of functions
  5374. ** using the [xFindFunction] method of the [virtual table module].
  5375. ** But global versions of those functions
  5376. ** must exist in order to be overloaded.)^
  5377. **
  5378. ** ^(This API makes sure a global version of a function with a particular
  5379. ** name and number of parameters exists. If no such function exists
  5380. ** before this API is called, a new function is created.)^ ^The implementation
  5381. ** of the new function always causes an exception to be thrown. So
  5382. ** the new function is not good for anything by itself. Its only
  5383. ** purpose is to be a placeholder function that can be overloaded
  5384. ** by a [virtual table].
  5385. */
  5386. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5387. /*
  5388. ** The interface to the virtual-table mechanism defined above (back up
  5389. ** to a comment remarkably similar to this one) is currently considered
  5390. ** to be experimental. The interface might change in incompatible ways.
  5391. ** If this is a problem for you, do not use the interface at this time.
  5392. **
  5393. ** When the virtual-table mechanism stabilizes, we will declare the
  5394. ** interface fixed, support it indefinitely, and remove this comment.
  5395. */
  5396. /*
  5397. ** CAPI3REF: A Handle To An Open BLOB
  5398. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5399. **
  5400. ** An instance of this object represents an open BLOB on which
  5401. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5402. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5403. ** and destroyed by [sqlite3_blob_close()].
  5404. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5405. ** can be used to read or write small subsections of the BLOB.
  5406. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5407. */
  5408. typedef struct sqlite3_blob sqlite3_blob;
  5409. /*
  5410. ** CAPI3REF: Open A BLOB For Incremental I/O
  5411. **
  5412. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5413. ** in row iRow, column zColumn, table zTable in database zDb;
  5414. ** in other words, the same BLOB that would be selected by:
  5415. **
  5416. ** <pre>
  5417. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5418. ** </pre>)^
  5419. **
  5420. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5421. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5422. ** ^It is not possible to open a column that is part of an index or primary
  5423. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5424. ** not possible to open a column that is part of a [child key] for writing.
  5425. **
  5426. ** ^Note that the database name is not the filename that contains
  5427. ** the database but rather the symbolic name of the database that
  5428. ** appears after the AS keyword when the database is connected using [ATTACH].
  5429. ** ^For the main database file, the database name is "main".
  5430. ** ^For TEMP tables, the database name is "temp".
  5431. **
  5432. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5433. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5434. ** to be a null pointer.)^
  5435. ** ^This function sets the [database connection] error code and message
  5436. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5437. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5438. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5439. ** regardless of the success or failure of this routine.
  5440. **
  5441. ** ^(If the row that a BLOB handle points to is modified by an
  5442. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5443. ** then the BLOB handle is marked as "expired".
  5444. ** This is true if any column of the row is changed, even a column
  5445. ** other than the one the BLOB handle is open on.)^
  5446. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5447. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5448. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5449. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5450. ** commit if the transaction continues to completion.)^
  5451. **
  5452. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5453. ** the opened blob. ^The size of a blob may not be changed by this
  5454. ** interface. Use the [UPDATE] SQL command to change the size of a
  5455. ** blob.
  5456. **
  5457. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5458. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5459. ** to create an empty, zero-filled blob in which to read or write using
  5460. ** this interface.
  5461. **
  5462. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5463. ** be released by a call to [sqlite3_blob_close()].
  5464. */
  5465. SQLITE_API int sqlite3_blob_open(
  5466. sqlite3*,
  5467. const char *zDb,
  5468. const char *zTable,
  5469. const char *zColumn,
  5470. sqlite3_int64 iRow,
  5471. int flags,
  5472. sqlite3_blob **ppBlob
  5473. );
  5474. /*
  5475. ** CAPI3REF: Move a BLOB Handle to a New Row
  5476. **
  5477. ** ^This function is used to move an existing blob handle so that it points
  5478. ** to a different row of the same database table. ^The new row is identified
  5479. ** by the rowid value passed as the second argument. Only the row can be
  5480. ** changed. ^The database, table and column on which the blob handle is open
  5481. ** remain the same. Moving an existing blob handle to a new row can be
  5482. ** faster than closing the existing handle and opening a new one.
  5483. **
  5484. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5485. ** it must exist and there must be either a blob or text value stored in
  5486. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5487. ** it does not contain a blob or text value, or if another error occurs, an
  5488. ** SQLite error code is returned and the blob handle is considered aborted.
  5489. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5490. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5491. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5492. ** always returns zero.
  5493. **
  5494. ** ^This function sets the database handle error code and message.
  5495. */
  5496. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5497. /*
  5498. ** CAPI3REF: Close A BLOB Handle
  5499. **
  5500. ** ^Closes an open [BLOB handle].
  5501. **
  5502. ** ^Closing a BLOB shall cause the current transaction to commit
  5503. ** if there are no other BLOBs, no pending prepared statements, and the
  5504. ** database connection is in [autocommit mode].
  5505. ** ^If any writes were made to the BLOB, they might be held in cache
  5506. ** until the close operation if they will fit.
  5507. **
  5508. ** ^(Closing the BLOB often forces the changes
  5509. ** out to disk and so if any I/O errors occur, they will likely occur
  5510. ** at the time when the BLOB is closed. Any errors that occur during
  5511. ** closing are reported as a non-zero return value.)^
  5512. **
  5513. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5514. ** an error code, the BLOB is still closed.)^
  5515. **
  5516. ** ^Calling this routine with a null pointer (such as would be returned
  5517. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5518. */
  5519. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5520. /*
  5521. ** CAPI3REF: Return The Size Of An Open BLOB
  5522. **
  5523. ** ^Returns the size in bytes of the BLOB accessible via the
  5524. ** successfully opened [BLOB handle] in its only argument. ^The
  5525. ** incremental blob I/O routines can only read or overwriting existing
  5526. ** blob content; they cannot change the size of a blob.
  5527. **
  5528. ** This routine only works on a [BLOB handle] which has been created
  5529. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5530. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5531. ** to this routine results in undefined and probably undesirable behavior.
  5532. */
  5533. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5534. /*
  5535. ** CAPI3REF: Read Data From A BLOB Incrementally
  5536. **
  5537. ** ^(This function is used to read data from an open [BLOB handle] into a
  5538. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5539. ** from the open BLOB, starting at offset iOffset.)^
  5540. **
  5541. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5542. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5543. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5544. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5545. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5546. **
  5547. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5548. ** error code of [SQLITE_ABORT].
  5549. **
  5550. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5551. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5552. **
  5553. ** This routine only works on a [BLOB handle] which has been created
  5554. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5555. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5556. ** to this routine results in undefined and probably undesirable behavior.
  5557. **
  5558. ** See also: [sqlite3_blob_write()].
  5559. */
  5560. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5561. /*
  5562. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5563. **
  5564. ** ^This function is used to write data into an open [BLOB handle] from a
  5565. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5566. ** into the open BLOB, starting at offset iOffset.
  5567. **
  5568. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5569. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5570. ** this function returns [SQLITE_READONLY].
  5571. **
  5572. ** ^This function may only modify the contents of the BLOB; it is
  5573. ** not possible to increase the size of a BLOB using this API.
  5574. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5575. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5576. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5577. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5578. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5579. **
  5580. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5581. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5582. ** before the [BLOB handle] expired are not rolled back by the
  5583. ** expiration of the handle, though of course those changes might
  5584. ** have been overwritten by the statement that expired the BLOB handle
  5585. ** or by other independent statements.
  5586. **
  5587. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5588. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5589. **
  5590. ** This routine only works on a [BLOB handle] which has been created
  5591. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5592. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5593. ** to this routine results in undefined and probably undesirable behavior.
  5594. **
  5595. ** See also: [sqlite3_blob_read()].
  5596. */
  5597. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5598. /*
  5599. ** CAPI3REF: Virtual File System Objects
  5600. **
  5601. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5602. ** that SQLite uses to interact
  5603. ** with the underlying operating system. Most SQLite builds come with a
  5604. ** single default VFS that is appropriate for the host computer.
  5605. ** New VFSes can be registered and existing VFSes can be unregistered.
  5606. ** The following interfaces are provided.
  5607. **
  5608. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5609. ** ^Names are case sensitive.
  5610. ** ^Names are zero-terminated UTF-8 strings.
  5611. ** ^If there is no match, a NULL pointer is returned.
  5612. ** ^If zVfsName is NULL then the default VFS is returned.
  5613. **
  5614. ** ^New VFSes are registered with sqlite3_vfs_register().
  5615. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5616. ** ^The same VFS can be registered multiple times without injury.
  5617. ** ^To make an existing VFS into the default VFS, register it again
  5618. ** with the makeDflt flag set. If two different VFSes with the
  5619. ** same name are registered, the behavior is undefined. If a
  5620. ** VFS is registered with a name that is NULL or an empty string,
  5621. ** then the behavior is undefined.
  5622. **
  5623. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5624. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5625. ** the default. The choice for the new VFS is arbitrary.)^
  5626. */
  5627. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5628. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5629. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5630. /*
  5631. ** CAPI3REF: Mutexes
  5632. **
  5633. ** The SQLite core uses these routines for thread
  5634. ** synchronization. Though they are intended for internal
  5635. ** use by SQLite, code that links against SQLite is
  5636. ** permitted to use any of these routines.
  5637. **
  5638. ** The SQLite source code contains multiple implementations
  5639. ** of these mutex routines. An appropriate implementation
  5640. ** is selected automatically at compile-time. ^(The following
  5641. ** implementations are available in the SQLite core:
  5642. **
  5643. ** <ul>
  5644. ** <li> SQLITE_MUTEX_PTHREADS
  5645. ** <li> SQLITE_MUTEX_W32
  5646. ** <li> SQLITE_MUTEX_NOOP
  5647. ** </ul>)^
  5648. **
  5649. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5650. ** that does no real locking and is appropriate for use in
  5651. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5652. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5653. ** and Windows.
  5654. **
  5655. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5656. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5657. ** implementation is included with the library. In this case the
  5658. ** application must supply a custom mutex implementation using the
  5659. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5660. ** before calling sqlite3_initialize() or any other public sqlite3_
  5661. ** function that calls sqlite3_initialize().)^
  5662. **
  5663. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5664. ** mutex and returns a pointer to it. ^If it returns NULL
  5665. ** that means that a mutex could not be allocated. ^SQLite
  5666. ** will unwind its stack and return an error. ^(The argument
  5667. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5668. **
  5669. ** <ul>
  5670. ** <li> SQLITE_MUTEX_FAST
  5671. ** <li> SQLITE_MUTEX_RECURSIVE
  5672. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5673. ** <li> SQLITE_MUTEX_STATIC_MEM
  5674. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5675. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5676. ** <li> SQLITE_MUTEX_STATIC_LRU
  5677. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5678. ** </ul>)^
  5679. **
  5680. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5681. ** cause sqlite3_mutex_alloc() to create
  5682. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5683. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5684. ** The mutex implementation does not need to make a distinction
  5685. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5686. ** not want to. ^SQLite will only request a recursive mutex in
  5687. ** cases where it really needs one. ^If a faster non-recursive mutex
  5688. ** implementation is available on the host platform, the mutex subsystem
  5689. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5690. **
  5691. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5692. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5693. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5694. ** used by the current version of SQLite. Future versions of SQLite
  5695. ** may add additional static mutexes. Static mutexes are for internal
  5696. ** use by SQLite only. Applications that use SQLite mutexes should
  5697. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5698. ** SQLITE_MUTEX_RECURSIVE.
  5699. **
  5700. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5701. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5702. ** returns a different mutex on every call. ^But for the static
  5703. ** mutex types, the same mutex is returned on every call that has
  5704. ** the same type number.
  5705. **
  5706. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5707. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5708. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5709. ** use when they are deallocated. Attempting to deallocate a static
  5710. ** mutex results in undefined behavior. ^SQLite never deallocates
  5711. ** a static mutex.
  5712. **
  5713. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5714. ** to enter a mutex. ^If another thread is already within the mutex,
  5715. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5716. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5717. ** upon successful entry. ^(Mutexes created using
  5718. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5719. ** In such cases the,
  5720. ** mutex must be exited an equal number of times before another thread
  5721. ** can enter.)^ ^(If the same thread tries to enter any other
  5722. ** kind of mutex more than once, the behavior is undefined.
  5723. ** SQLite will never exhibit
  5724. ** such behavior in its own use of mutexes.)^
  5725. **
  5726. ** ^(Some systems (for example, Windows 95) do not support the operation
  5727. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5728. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5729. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5730. **
  5731. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5732. ** previously entered by the same thread. ^(The behavior
  5733. ** is undefined if the mutex is not currently entered by the
  5734. ** calling thread or is not currently allocated. SQLite will
  5735. ** never do either.)^
  5736. **
  5737. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5738. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5739. ** behave as no-ops.
  5740. **
  5741. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5742. */
  5743. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5744. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5745. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5746. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5747. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5748. /*
  5749. ** CAPI3REF: Mutex Methods Object
  5750. **
  5751. ** An instance of this structure defines the low-level routines
  5752. ** used to allocate and use mutexes.
  5753. **
  5754. ** Usually, the default mutex implementations provided by SQLite are
  5755. ** sufficient, however the user has the option of substituting a custom
  5756. ** implementation for specialized deployments or systems for which SQLite
  5757. ** does not provide a suitable implementation. In this case, the user
  5758. ** creates and populates an instance of this structure to pass
  5759. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5760. ** Additionally, an instance of this structure can be used as an
  5761. ** output variable when querying the system for the current mutex
  5762. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5763. **
  5764. ** ^The xMutexInit method defined by this structure is invoked as
  5765. ** part of system initialization by the sqlite3_initialize() function.
  5766. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5767. ** effective call to [sqlite3_initialize()].
  5768. **
  5769. ** ^The xMutexEnd method defined by this structure is invoked as
  5770. ** part of system shutdown by the sqlite3_shutdown() function. The
  5771. ** implementation of this method is expected to release all outstanding
  5772. ** resources obtained by the mutex methods implementation, especially
  5773. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5774. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5775. **
  5776. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5777. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5778. ** xMutexNotheld) implement the following interfaces (respectively):
  5779. **
  5780. ** <ul>
  5781. ** <li> [sqlite3_mutex_alloc()] </li>
  5782. ** <li> [sqlite3_mutex_free()] </li>
  5783. ** <li> [sqlite3_mutex_enter()] </li>
  5784. ** <li> [sqlite3_mutex_try()] </li>
  5785. ** <li> [sqlite3_mutex_leave()] </li>
  5786. ** <li> [sqlite3_mutex_held()] </li>
  5787. ** <li> [sqlite3_mutex_notheld()] </li>
  5788. ** </ul>)^
  5789. **
  5790. ** The only difference is that the public sqlite3_XXX functions enumerated
  5791. ** above silently ignore any invocations that pass a NULL pointer instead
  5792. ** of a valid mutex handle. The implementations of the methods defined
  5793. ** by this structure are not required to handle this case, the results
  5794. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5795. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5796. ** it is passed a NULL pointer).
  5797. **
  5798. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5799. ** invoke xMutexInit() multiple times within the same process and without
  5800. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5801. ** xMutexInit() must be no-ops.
  5802. **
  5803. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5804. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5805. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5806. ** memory allocation for a fast or recursive mutex.
  5807. **
  5808. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5809. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5810. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5811. ** prior to returning.
  5812. */
  5813. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5814. struct sqlite3_mutex_methods {
  5815. int (*xMutexInit)(void);
  5816. int (*xMutexEnd)(void);
  5817. sqlite3_mutex *(*xMutexAlloc)(int);
  5818. void (*xMutexFree)(sqlite3_mutex *);
  5819. void (*xMutexEnter)(sqlite3_mutex *);
  5820. int (*xMutexTry)(sqlite3_mutex *);
  5821. void (*xMutexLeave)(sqlite3_mutex *);
  5822. int (*xMutexHeld)(sqlite3_mutex *);
  5823. int (*xMutexNotheld)(sqlite3_mutex *);
  5824. };
  5825. /*
  5826. ** CAPI3REF: Mutex Verification Routines
  5827. **
  5828. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5829. ** are intended for use inside assert() statements. ^The SQLite core
  5830. ** never uses these routines except inside an assert() and applications
  5831. ** are advised to follow the lead of the core. ^The SQLite core only
  5832. ** provides implementations for these routines when it is compiled
  5833. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5834. ** are only required to provide these routines if SQLITE_DEBUG is
  5835. ** defined and if NDEBUG is not defined.
  5836. **
  5837. ** ^These routines should return true if the mutex in their argument
  5838. ** is held or not held, respectively, by the calling thread.
  5839. **
  5840. ** ^The implementation is not required to provide versions of these
  5841. ** routines that actually work. If the implementation does not provide working
  5842. ** versions of these routines, it should at least provide stubs that always
  5843. ** return true so that one does not get spurious assertion failures.
  5844. **
  5845. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5846. ** the routine should return 1. This seems counter-intuitive since
  5847. ** clearly the mutex cannot be held if it does not exist. But
  5848. ** the reason the mutex does not exist is because the build is not
  5849. ** using mutexes. And we do not want the assert() containing the
  5850. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5851. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5852. ** interface should also return 1 when given a NULL pointer.
  5853. */
  5854. #ifndef NDEBUG
  5855. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5856. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5857. #endif
  5858. /*
  5859. ** CAPI3REF: Mutex Types
  5860. **
  5861. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5862. ** which is one of these integer constants.
  5863. **
  5864. ** The set of static mutexes may change from one SQLite release to the
  5865. ** next. Applications that override the built-in mutex logic must be
  5866. ** prepared to accommodate additional static mutexes.
  5867. */
  5868. #define SQLITE_MUTEX_FAST 0
  5869. #define SQLITE_MUTEX_RECURSIVE 1
  5870. #define SQLITE_MUTEX_STATIC_MASTER 2
  5871. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5872. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5873. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5874. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5875. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5876. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  5877. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  5878. /*
  5879. ** CAPI3REF: Retrieve the mutex for a database connection
  5880. **
  5881. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  5882. ** serializes access to the [database connection] given in the argument
  5883. ** when the [threading mode] is Serialized.
  5884. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  5885. ** routine returns a NULL pointer.
  5886. */
  5887. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5888. /*
  5889. ** CAPI3REF: Low-Level Control Of Database Files
  5890. **
  5891. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  5892. ** xFileControl method for the [sqlite3_io_methods] object associated
  5893. ** with a particular database identified by the second argument. ^The
  5894. ** name of the database is "main" for the main database or "temp" for the
  5895. ** TEMP database, or the name that appears after the AS keyword for
  5896. ** databases that are added using the [ATTACH] SQL command.
  5897. ** ^A NULL pointer can be used in place of "main" to refer to the
  5898. ** main database file.
  5899. ** ^The third and fourth parameters to this routine
  5900. ** are passed directly through to the second and third parameters of
  5901. ** the xFileControl method. ^The return value of the xFileControl
  5902. ** method becomes the return value of this routine.
  5903. **
  5904. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  5905. ** a pointer to the underlying [sqlite3_file] object to be written into
  5906. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  5907. ** case is a short-circuit path which does not actually invoke the
  5908. ** underlying sqlite3_io_methods.xFileControl method.
  5909. **
  5910. ** ^If the second parameter (zDbName) does not match the name of any
  5911. ** open database file, then SQLITE_ERROR is returned. ^This error
  5912. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5913. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  5914. ** also return SQLITE_ERROR. There is no way to distinguish between
  5915. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5916. ** xFileControl method.
  5917. **
  5918. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5919. */
  5920. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5921. /*
  5922. ** CAPI3REF: Testing Interface
  5923. **
  5924. ** ^The sqlite3_test_control() interface is used to read out internal
  5925. ** state of SQLite and to inject faults into SQLite for testing
  5926. ** purposes. ^The first parameter is an operation code that determines
  5927. ** the number, meaning, and operation of all subsequent parameters.
  5928. **
  5929. ** This interface is not for use by applications. It exists solely
  5930. ** for verifying the correct operation of the SQLite library. Depending
  5931. ** on how the SQLite library is compiled, this interface might not exist.
  5932. **
  5933. ** The details of the operation codes, their meanings, the parameters
  5934. ** they take, and what they do are all subject to change without notice.
  5935. ** Unlike most of the SQLite API, this function is not guaranteed to
  5936. ** operate consistently from one release to the next.
  5937. */
  5938. SQLITE_API int sqlite3_test_control(int op, ...);
  5939. /*
  5940. ** CAPI3REF: Testing Interface Operation Codes
  5941. **
  5942. ** These constants are the valid operation code parameters used
  5943. ** as the first argument to [sqlite3_test_control()].
  5944. **
  5945. ** These parameters and their meanings are subject to change
  5946. ** without notice. These values are for testing purposes only.
  5947. ** Applications should not use any of these parameters or the
  5948. ** [sqlite3_test_control()] interface.
  5949. */
  5950. #define SQLITE_TESTCTRL_FIRST 5
  5951. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5952. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5953. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5954. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5955. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5956. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5957. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5958. #define SQLITE_TESTCTRL_ASSERT 12
  5959. #define SQLITE_TESTCTRL_ALWAYS 13
  5960. #define SQLITE_TESTCTRL_RESERVE 14
  5961. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  5962. #define SQLITE_TESTCTRL_ISKEYWORD 16
  5963. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  5964. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  5965. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  5966. #define SQLITE_TESTCTRL_LAST 19
  5967. /*
  5968. ** CAPI3REF: SQLite Runtime Status
  5969. **
  5970. ** ^This interface is used to retrieve runtime status information
  5971. ** about the performance of SQLite, and optionally to reset various
  5972. ** highwater marks. ^The first argument is an integer code for
  5973. ** the specific parameter to measure. ^(Recognized integer codes
  5974. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  5975. ** ^The current value of the parameter is returned into *pCurrent.
  5976. ** ^The highest recorded value is returned in *pHighwater. ^If the
  5977. ** resetFlag is true, then the highest record value is reset after
  5978. ** *pHighwater is written. ^(Some parameters do not record the highest
  5979. ** value. For those parameters
  5980. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  5981. ** ^(Other parameters record only the highwater mark and not the current
  5982. ** value. For these latter parameters nothing is written into *pCurrent.)^
  5983. **
  5984. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  5985. ** non-zero [error code] on failure.
  5986. **
  5987. ** This routine is threadsafe but is not atomic. This routine can be
  5988. ** called while other threads are running the same or different SQLite
  5989. ** interfaces. However the values returned in *pCurrent and
  5990. ** *pHighwater reflect the status of SQLite at different points in time
  5991. ** and it is possible that another thread might change the parameter
  5992. ** in between the times when *pCurrent and *pHighwater are written.
  5993. **
  5994. ** See also: [sqlite3_db_status()]
  5995. */
  5996. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5997. /*
  5998. ** CAPI3REF: Status Parameters
  5999. ** KEYWORDS: {status parameters}
  6000. **
  6001. ** These integer constants designate various run-time status parameters
  6002. ** that can be returned by [sqlite3_status()].
  6003. **
  6004. ** <dl>
  6005. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6006. ** <dd>This parameter is the current amount of memory checked out
  6007. ** using [sqlite3_malloc()], either directly or indirectly. The
  6008. ** figure includes calls made to [sqlite3_malloc()] by the application
  6009. ** and internal memory usage by the SQLite library. Scratch memory
  6010. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6011. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6012. ** this parameter. The amount returned is the sum of the allocation
  6013. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6014. **
  6015. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6016. ** <dd>This parameter records the largest memory allocation request
  6017. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6018. ** internal equivalents). Only the value returned in the
  6019. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6020. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6021. **
  6022. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6023. ** <dd>This parameter records the number of separate memory allocations
  6024. ** currently checked out.</dd>)^
  6025. **
  6026. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6027. ** <dd>This parameter returns the number of pages used out of the
  6028. ** [pagecache memory allocator] that was configured using
  6029. ** [SQLITE_CONFIG_PAGECACHE]. The
  6030. ** value returned is in pages, not in bytes.</dd>)^
  6031. **
  6032. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6033. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6034. ** <dd>This parameter returns the number of bytes of page cache
  6035. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6036. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6037. ** returned value includes allocations that overflowed because they
  6038. ** where too large (they were larger than the "sz" parameter to
  6039. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6040. ** no space was left in the page cache.</dd>)^
  6041. **
  6042. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6043. ** <dd>This parameter records the largest memory allocation request
  6044. ** handed to [pagecache memory allocator]. Only the value returned in the
  6045. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6046. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6047. **
  6048. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6049. ** <dd>This parameter returns the number of allocations used out of the
  6050. ** [scratch memory allocator] configured using
  6051. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6052. ** in bytes. Since a single thread may only have one scratch allocation
  6053. ** outstanding at time, this parameter also reports the number of threads
  6054. ** using scratch memory at the same time.</dd>)^
  6055. **
  6056. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6057. ** <dd>This parameter returns the number of bytes of scratch memory
  6058. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6059. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6060. ** returned include overflows because the requested allocation was too
  6061. ** larger (that is, because the requested allocation was larger than the
  6062. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6063. ** slots were available.
  6064. ** </dd>)^
  6065. **
  6066. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6067. ** <dd>This parameter records the largest memory allocation request
  6068. ** handed to [scratch memory allocator]. Only the value returned in the
  6069. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6070. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6071. **
  6072. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6073. ** <dd>This parameter records the deepest parser stack. It is only
  6074. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6075. ** </dl>
  6076. **
  6077. ** New status parameters may be added from time to time.
  6078. */
  6079. #define SQLITE_STATUS_MEMORY_USED 0
  6080. #define SQLITE_STATUS_PAGECACHE_USED 1
  6081. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6082. #define SQLITE_STATUS_SCRATCH_USED 3
  6083. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6084. #define SQLITE_STATUS_MALLOC_SIZE 5
  6085. #define SQLITE_STATUS_PARSER_STACK 6
  6086. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6087. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6088. #define SQLITE_STATUS_MALLOC_COUNT 9
  6089. /*
  6090. ** CAPI3REF: Database Connection Status
  6091. **
  6092. ** ^This interface is used to retrieve runtime status information
  6093. ** about a single [database connection]. ^The first argument is the
  6094. ** database connection object to be interrogated. ^The second argument
  6095. ** is an integer constant, taken from the set of
  6096. ** [SQLITE_DBSTATUS options], that
  6097. ** determines the parameter to interrogate. The set of
  6098. ** [SQLITE_DBSTATUS options] is likely
  6099. ** to grow in future releases of SQLite.
  6100. **
  6101. ** ^The current value of the requested parameter is written into *pCur
  6102. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6103. ** the resetFlg is true, then the highest instantaneous value is
  6104. ** reset back down to the current value.
  6105. **
  6106. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6107. ** non-zero [error code] on failure.
  6108. **
  6109. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6110. */
  6111. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6112. /*
  6113. ** CAPI3REF: Status Parameters for database connections
  6114. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6115. **
  6116. ** These constants are the available integer "verbs" that can be passed as
  6117. ** the second argument to the [sqlite3_db_status()] interface.
  6118. **
  6119. ** New verbs may be added in future releases of SQLite. Existing verbs
  6120. ** might be discontinued. Applications should check the return code from
  6121. ** [sqlite3_db_status()] to make sure that the call worked.
  6122. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6123. ** if a discontinued or unsupported verb is invoked.
  6124. **
  6125. ** <dl>
  6126. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6127. ** <dd>This parameter returns the number of lookaside memory slots currently
  6128. ** checked out.</dd>)^
  6129. **
  6130. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6131. ** <dd>This parameter returns the number malloc attempts that were
  6132. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6133. ** the current value is always zero.)^
  6134. **
  6135. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6136. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6137. ** <dd>This parameter returns the number malloc attempts that might have
  6138. ** been satisfied using lookaside memory but failed due to the amount of
  6139. ** memory requested being larger than the lookaside slot size.
  6140. ** Only the high-water value is meaningful;
  6141. ** the current value is always zero.)^
  6142. **
  6143. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6144. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6145. ** <dd>This parameter returns the number malloc attempts that might have
  6146. ** been satisfied using lookaside memory but failed due to all lookaside
  6147. ** memory already being in use.
  6148. ** Only the high-water value is meaningful;
  6149. ** the current value is always zero.)^
  6150. **
  6151. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6152. ** <dd>This parameter returns the approximate number of of bytes of heap
  6153. ** memory used by all pager caches associated with the database connection.)^
  6154. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6155. **
  6156. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6157. ** <dd>This parameter returns the approximate number of of bytes of heap
  6158. ** memory used to store the schema for all databases associated
  6159. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6160. ** ^The full amount of memory used by the schemas is reported, even if the
  6161. ** schema memory is shared with other database connections due to
  6162. ** [shared cache mode] being enabled.
  6163. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6164. **
  6165. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6166. ** <dd>This parameter returns the approximate number of of bytes of heap
  6167. ** and lookaside memory used by all prepared statements associated with
  6168. ** the database connection.)^
  6169. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6170. ** </dd>
  6171. **
  6172. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6173. ** <dd>This parameter returns the number of pager cache hits that have
  6174. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6175. ** is always 0.
  6176. ** </dd>
  6177. **
  6178. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6179. ** <dd>This parameter returns the number of pager cache misses that have
  6180. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6181. ** is always 0.
  6182. ** </dd>
  6183. **
  6184. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6185. ** <dd>This parameter returns the number of dirty cache entries that have
  6186. ** been written to disk. Specifically, the number of pages written to the
  6187. ** wal file in wal mode databases, or the number of pages written to the
  6188. ** database file in rollback mode databases. Any pages written as part of
  6189. ** transaction rollback or database recovery operations are not included.
  6190. ** If an IO or other error occurs while writing a page to disk, the effect
  6191. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6192. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6193. ** </dd>
  6194. **
  6195. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6196. ** <dd>This parameter returns zero for the current value if and only if
  6197. ** all foreign key constraints (deferred or immediate) have been
  6198. ** resolved.)^ ^The highwater mark is always 0.
  6199. ** </dd>
  6200. ** </dl>
  6201. */
  6202. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6203. #define SQLITE_DBSTATUS_CACHE_USED 1
  6204. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6205. #define SQLITE_DBSTATUS_STMT_USED 3
  6206. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6207. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6208. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6209. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6210. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6211. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6212. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6213. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6214. /*
  6215. ** CAPI3REF: Prepared Statement Status
  6216. **
  6217. ** ^(Each prepared statement maintains various
  6218. ** [SQLITE_STMTSTATUS counters] that measure the number
  6219. ** of times it has performed specific operations.)^ These counters can
  6220. ** be used to monitor the performance characteristics of the prepared
  6221. ** statements. For example, if the number of table steps greatly exceeds
  6222. ** the number of table searches or result rows, that would tend to indicate
  6223. ** that the prepared statement is using a full table scan rather than
  6224. ** an index.
  6225. **
  6226. ** ^(This interface is used to retrieve and reset counter values from
  6227. ** a [prepared statement]. The first argument is the prepared statement
  6228. ** object to be interrogated. The second argument
  6229. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6230. ** to be interrogated.)^
  6231. ** ^The current value of the requested counter is returned.
  6232. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6233. ** interface call returns.
  6234. **
  6235. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6236. */
  6237. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6238. /*
  6239. ** CAPI3REF: Status Parameters for prepared statements
  6240. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6241. **
  6242. ** These preprocessor macros define integer codes that name counter
  6243. ** values associated with the [sqlite3_stmt_status()] interface.
  6244. ** The meanings of the various counters are as follows:
  6245. **
  6246. ** <dl>
  6247. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6248. ** <dd>^This is the number of times that SQLite has stepped forward in
  6249. ** a table as part of a full table scan. Large numbers for this counter
  6250. ** may indicate opportunities for performance improvement through
  6251. ** careful use of indices.</dd>
  6252. **
  6253. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6254. ** <dd>^This is the number of sort operations that have occurred.
  6255. ** A non-zero value in this counter may indicate an opportunity to
  6256. ** improvement performance through careful use of indices.</dd>
  6257. **
  6258. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6259. ** <dd>^This is the number of rows inserted into transient indices that
  6260. ** were created automatically in order to help joins run faster.
  6261. ** A non-zero value in this counter may indicate an opportunity to
  6262. ** improvement performance by adding permanent indices that do not
  6263. ** need to be reinitialized each time the statement is run.</dd>
  6264. **
  6265. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6266. ** <dd>^This is the number of virtual machine operations executed
  6267. ** by the prepared statement if that number is less than or equal
  6268. ** to 2147483647. The number of virtual machine operations can be
  6269. ** used as a proxy for the total work done by the prepared statement.
  6270. ** If the number of virtual machine operations exceeds 2147483647
  6271. ** then the value returned by this statement status code is undefined.
  6272. ** </dd>
  6273. ** </dl>
  6274. */
  6275. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6276. #define SQLITE_STMTSTATUS_SORT 2
  6277. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6278. #define SQLITE_STMTSTATUS_VM_STEP 4
  6279. /*
  6280. ** CAPI3REF: Custom Page Cache Object
  6281. **
  6282. ** The sqlite3_pcache type is opaque. It is implemented by
  6283. ** the pluggable module. The SQLite core has no knowledge of
  6284. ** its size or internal structure and never deals with the
  6285. ** sqlite3_pcache object except by holding and passing pointers
  6286. ** to the object.
  6287. **
  6288. ** See [sqlite3_pcache_methods2] for additional information.
  6289. */
  6290. typedef struct sqlite3_pcache sqlite3_pcache;
  6291. /*
  6292. ** CAPI3REF: Custom Page Cache Object
  6293. **
  6294. ** The sqlite3_pcache_page object represents a single page in the
  6295. ** page cache. The page cache will allocate instances of this
  6296. ** object. Various methods of the page cache use pointers to instances
  6297. ** of this object as parameters or as their return value.
  6298. **
  6299. ** See [sqlite3_pcache_methods2] for additional information.
  6300. */
  6301. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6302. struct sqlite3_pcache_page {
  6303. void *pBuf; /* The content of the page */
  6304. void *pExtra; /* Extra information associated with the page */
  6305. };
  6306. /*
  6307. ** CAPI3REF: Application Defined Page Cache.
  6308. ** KEYWORDS: {page cache}
  6309. **
  6310. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6311. ** register an alternative page cache implementation by passing in an
  6312. ** instance of the sqlite3_pcache_methods2 structure.)^
  6313. ** In many applications, most of the heap memory allocated by
  6314. ** SQLite is used for the page cache.
  6315. ** By implementing a
  6316. ** custom page cache using this API, an application can better control
  6317. ** the amount of memory consumed by SQLite, the way in which
  6318. ** that memory is allocated and released, and the policies used to
  6319. ** determine exactly which parts of a database file are cached and for
  6320. ** how long.
  6321. **
  6322. ** The alternative page cache mechanism is an
  6323. ** extreme measure that is only needed by the most demanding applications.
  6324. ** The built-in page cache is recommended for most uses.
  6325. **
  6326. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6327. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6328. ** the application may discard the parameter after the call to
  6329. ** [sqlite3_config()] returns.)^
  6330. **
  6331. ** [[the xInit() page cache method]]
  6332. ** ^(The xInit() method is called once for each effective
  6333. ** call to [sqlite3_initialize()])^
  6334. ** (usually only once during the lifetime of the process). ^(The xInit()
  6335. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6336. ** The intent of the xInit() method is to set up global data structures
  6337. ** required by the custom page cache implementation.
  6338. ** ^(If the xInit() method is NULL, then the
  6339. ** built-in default page cache is used instead of the application defined
  6340. ** page cache.)^
  6341. **
  6342. ** [[the xShutdown() page cache method]]
  6343. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6344. ** It can be used to clean up
  6345. ** any outstanding resources before process shutdown, if required.
  6346. ** ^The xShutdown() method may be NULL.
  6347. **
  6348. ** ^SQLite automatically serializes calls to the xInit method,
  6349. ** so the xInit method need not be threadsafe. ^The
  6350. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6351. ** not need to be threadsafe either. All other methods must be threadsafe
  6352. ** in multithreaded applications.
  6353. **
  6354. ** ^SQLite will never invoke xInit() more than once without an intervening
  6355. ** call to xShutdown().
  6356. **
  6357. ** [[the xCreate() page cache methods]]
  6358. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6359. ** SQLite will typically create one cache instance for each open database file,
  6360. ** though this is not guaranteed. ^The
  6361. ** first parameter, szPage, is the size in bytes of the pages that must
  6362. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6363. ** second parameter szExtra is a number of bytes of extra storage
  6364. ** associated with each page cache entry. ^The szExtra parameter will
  6365. ** a number less than 250. SQLite will use the
  6366. ** extra szExtra bytes on each page to store metadata about the underlying
  6367. ** database page on disk. The value passed into szExtra depends
  6368. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6369. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6370. ** created will be used to cache database pages of a file stored on disk, or
  6371. ** false if it is used for an in-memory database. The cache implementation
  6372. ** does not have to do anything special based with the value of bPurgeable;
  6373. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6374. ** never invoke xUnpin() except to deliberately delete a page.
  6375. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6376. ** false will always have the "discard" flag set to true.
  6377. ** ^Hence, a cache created with bPurgeable false will
  6378. ** never contain any unpinned pages.
  6379. **
  6380. ** [[the xCachesize() page cache method]]
  6381. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6382. ** suggested maximum cache-size (number of pages stored by) the cache
  6383. ** instance passed as the first argument. This is the value configured using
  6384. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6385. ** parameter, the implementation is not required to do anything with this
  6386. ** value; it is advisory only.
  6387. **
  6388. ** [[the xPagecount() page cache methods]]
  6389. ** The xPagecount() method must return the number of pages currently
  6390. ** stored in the cache, both pinned and unpinned.
  6391. **
  6392. ** [[the xFetch() page cache methods]]
  6393. ** The xFetch() method locates a page in the cache and returns a pointer to
  6394. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6395. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6396. ** pointer to a buffer of szPage bytes used to store the content of a
  6397. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6398. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6399. ** for each entry in the page cache.
  6400. **
  6401. ** The page to be fetched is determined by the key. ^The minimum key value
  6402. ** is 1. After it has been retrieved using xFetch, the page is considered
  6403. ** to be "pinned".
  6404. **
  6405. ** If the requested page is already in the page cache, then the page cache
  6406. ** implementation must return a pointer to the page buffer with its content
  6407. ** intact. If the requested page is not already in the cache, then the
  6408. ** cache implementation should use the value of the createFlag
  6409. ** parameter to help it determined what action to take:
  6410. **
  6411. ** <table border=1 width=85% align=center>
  6412. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6413. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6414. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6415. ** Otherwise return NULL.
  6416. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6417. ** NULL if allocating a new page is effectively impossible.
  6418. ** </table>
  6419. **
  6420. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6421. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6422. ** failed.)^ In between the to xFetch() calls, SQLite may
  6423. ** attempt to unpin one or more cache pages by spilling the content of
  6424. ** pinned pages to disk and synching the operating system disk cache.
  6425. **
  6426. ** [[the xUnpin() page cache method]]
  6427. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6428. ** as its second argument. If the third parameter, discard, is non-zero,
  6429. ** then the page must be evicted from the cache.
  6430. ** ^If the discard parameter is
  6431. ** zero, then the page may be discarded or retained at the discretion of
  6432. ** page cache implementation. ^The page cache implementation
  6433. ** may choose to evict unpinned pages at any time.
  6434. **
  6435. ** The cache must not perform any reference counting. A single
  6436. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6437. ** to xFetch().
  6438. **
  6439. ** [[the xRekey() page cache methods]]
  6440. ** The xRekey() method is used to change the key value associated with the
  6441. ** page passed as the second argument. If the cache
  6442. ** previously contains an entry associated with newKey, it must be
  6443. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6444. ** to be pinned.
  6445. **
  6446. ** When SQLite calls the xTruncate() method, the cache must discard all
  6447. ** existing cache entries with page numbers (keys) greater than or equal
  6448. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6449. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6450. ** they can be safely discarded.
  6451. **
  6452. ** [[the xDestroy() page cache method]]
  6453. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6454. ** All resources associated with the specified cache should be freed. ^After
  6455. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6456. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6457. ** functions.
  6458. **
  6459. ** [[the xShrink() page cache method]]
  6460. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6461. ** free up as much of heap memory as possible. The page cache implementation
  6462. ** is not obligated to free any memory, but well-behaved implementations should
  6463. ** do their best.
  6464. */
  6465. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6466. struct sqlite3_pcache_methods2 {
  6467. int iVersion;
  6468. void *pArg;
  6469. int (*xInit)(void*);
  6470. void (*xShutdown)(void*);
  6471. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6472. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6473. int (*xPagecount)(sqlite3_pcache*);
  6474. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6475. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6476. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6477. unsigned oldKey, unsigned newKey);
  6478. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6479. void (*xDestroy)(sqlite3_pcache*);
  6480. void (*xShrink)(sqlite3_pcache*);
  6481. };
  6482. /*
  6483. ** This is the obsolete pcache_methods object that has now been replaced
  6484. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6485. ** retained in the header file for backwards compatibility only.
  6486. */
  6487. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6488. struct sqlite3_pcache_methods {
  6489. void *pArg;
  6490. int (*xInit)(void*);
  6491. void (*xShutdown)(void*);
  6492. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6493. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6494. int (*xPagecount)(sqlite3_pcache*);
  6495. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6496. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6497. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6498. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6499. void (*xDestroy)(sqlite3_pcache*);
  6500. };
  6501. /*
  6502. ** CAPI3REF: Online Backup Object
  6503. **
  6504. ** The sqlite3_backup object records state information about an ongoing
  6505. ** online backup operation. ^The sqlite3_backup object is created by
  6506. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6507. ** [sqlite3_backup_finish()].
  6508. **
  6509. ** See Also: [Using the SQLite Online Backup API]
  6510. */
  6511. typedef struct sqlite3_backup sqlite3_backup;
  6512. /*
  6513. ** CAPI3REF: Online Backup API.
  6514. **
  6515. ** The backup API copies the content of one database into another.
  6516. ** It is useful either for creating backups of databases or
  6517. ** for copying in-memory databases to or from persistent files.
  6518. **
  6519. ** See Also: [Using the SQLite Online Backup API]
  6520. **
  6521. ** ^SQLite holds a write transaction open on the destination database file
  6522. ** for the duration of the backup operation.
  6523. ** ^The source database is read-locked only while it is being read;
  6524. ** it is not locked continuously for the entire backup operation.
  6525. ** ^Thus, the backup may be performed on a live source database without
  6526. ** preventing other database connections from
  6527. ** reading or writing to the source database while the backup is underway.
  6528. **
  6529. ** ^(To perform a backup operation:
  6530. ** <ol>
  6531. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6532. ** backup,
  6533. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6534. ** the data between the two databases, and finally
  6535. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6536. ** associated with the backup operation.
  6537. ** </ol>)^
  6538. ** There should be exactly one call to sqlite3_backup_finish() for each
  6539. ** successful call to sqlite3_backup_init().
  6540. **
  6541. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6542. **
  6543. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6544. ** [database connection] associated with the destination database
  6545. ** and the database name, respectively.
  6546. ** ^The database name is "main" for the main database, "temp" for the
  6547. ** temporary database, or the name specified after the AS keyword in
  6548. ** an [ATTACH] statement for an attached database.
  6549. ** ^The S and M arguments passed to
  6550. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6551. ** and database name of the source database, respectively.
  6552. ** ^The source and destination [database connections] (parameters S and D)
  6553. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6554. ** an error.
  6555. **
  6556. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6557. ** returned and an error code and error message are stored in the
  6558. ** destination [database connection] D.
  6559. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6560. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6561. ** [sqlite3_errmsg16()] functions.
  6562. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6563. ** [sqlite3_backup] object.
  6564. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6565. ** sqlite3_backup_finish() functions to perform the specified backup
  6566. ** operation.
  6567. **
  6568. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6569. **
  6570. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6571. ** the source and destination databases specified by [sqlite3_backup] object B.
  6572. ** ^If N is negative, all remaining source pages are copied.
  6573. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6574. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6575. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6576. ** from source to destination, then it returns [SQLITE_DONE].
  6577. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6578. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6579. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6580. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6581. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6582. **
  6583. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6584. ** <ol>
  6585. ** <li> the destination database was opened read-only, or
  6586. ** <li> the destination database is using write-ahead-log journaling
  6587. ** and the destination and source page sizes differ, or
  6588. ** <li> the destination database is an in-memory database and the
  6589. ** destination and source page sizes differ.
  6590. ** </ol>)^
  6591. **
  6592. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6593. ** the [sqlite3_busy_handler | busy-handler function]
  6594. ** is invoked (if one is specified). ^If the
  6595. ** busy-handler returns non-zero before the lock is available, then
  6596. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6597. ** sqlite3_backup_step() can be retried later. ^If the source
  6598. ** [database connection]
  6599. ** is being used to write to the source database when sqlite3_backup_step()
  6600. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6601. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6602. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6603. ** [SQLITE_READONLY] is returned, then
  6604. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6605. ** errors are considered fatal.)^ The application must accept
  6606. ** that the backup operation has failed and pass the backup operation handle
  6607. ** to the sqlite3_backup_finish() to release associated resources.
  6608. **
  6609. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6610. ** on the destination file. ^The exclusive lock is not released until either
  6611. ** sqlite3_backup_finish() is called or the backup operation is complete
  6612. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6613. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6614. ** lasts for the duration of the sqlite3_backup_step() call.
  6615. ** ^Because the source database is not locked between calls to
  6616. ** sqlite3_backup_step(), the source database may be modified mid-way
  6617. ** through the backup process. ^If the source database is modified by an
  6618. ** external process or via a database connection other than the one being
  6619. ** used by the backup operation, then the backup will be automatically
  6620. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6621. ** database is modified by the using the same database connection as is used
  6622. ** by the backup operation, then the backup database is automatically
  6623. ** updated at the same time.
  6624. **
  6625. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6626. **
  6627. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6628. ** application wishes to abandon the backup operation, the application
  6629. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6630. ** ^The sqlite3_backup_finish() interfaces releases all
  6631. ** resources associated with the [sqlite3_backup] object.
  6632. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6633. ** active write-transaction on the destination database is rolled back.
  6634. ** The [sqlite3_backup] object is invalid
  6635. ** and may not be used following a call to sqlite3_backup_finish().
  6636. **
  6637. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6638. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6639. ** sqlite3_backup_step() completed.
  6640. ** ^If an out-of-memory condition or IO error occurred during any prior
  6641. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6642. ** sqlite3_backup_finish() returns the corresponding [error code].
  6643. **
  6644. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6645. ** is not a permanent error and does not affect the return value of
  6646. ** sqlite3_backup_finish().
  6647. **
  6648. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6649. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6650. **
  6651. ** ^Each call to sqlite3_backup_step() sets two values inside
  6652. ** the [sqlite3_backup] object: the number of pages still to be backed
  6653. ** up and the total number of pages in the source database file.
  6654. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6655. ** retrieve these two values, respectively.
  6656. **
  6657. ** ^The values returned by these functions are only updated by
  6658. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6659. ** operation, then the values are not updated to account for any extra
  6660. ** pages that need to be updated or the size of the source database file
  6661. ** changing.
  6662. **
  6663. ** <b>Concurrent Usage of Database Handles</b>
  6664. **
  6665. ** ^The source [database connection] may be used by the application for other
  6666. ** purposes while a backup operation is underway or being initialized.
  6667. ** ^If SQLite is compiled and configured to support threadsafe database
  6668. ** connections, then the source database connection may be used concurrently
  6669. ** from within other threads.
  6670. **
  6671. ** However, the application must guarantee that the destination
  6672. ** [database connection] is not passed to any other API (by any thread) after
  6673. ** sqlite3_backup_init() is called and before the corresponding call to
  6674. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6675. ** if the application incorrectly accesses the destination [database connection]
  6676. ** and so no error code is reported, but the operations may malfunction
  6677. ** nevertheless. Use of the destination database connection while a
  6678. ** backup is in progress might also also cause a mutex deadlock.
  6679. **
  6680. ** If running in [shared cache mode], the application must
  6681. ** guarantee that the shared cache used by the destination database
  6682. ** is not accessed while the backup is running. In practice this means
  6683. ** that the application must guarantee that the disk file being
  6684. ** backed up to is not accessed by any connection within the process,
  6685. ** not just the specific connection that was passed to sqlite3_backup_init().
  6686. **
  6687. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6688. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6689. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6690. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6691. ** same time as another thread is invoking sqlite3_backup_step() it is
  6692. ** possible that they return invalid values.
  6693. */
  6694. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6695. sqlite3 *pDest, /* Destination database handle */
  6696. const char *zDestName, /* Destination database name */
  6697. sqlite3 *pSource, /* Source database handle */
  6698. const char *zSourceName /* Source database name */
  6699. );
  6700. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6701. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6702. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6703. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6704. /*
  6705. ** CAPI3REF: Unlock Notification
  6706. **
  6707. ** ^When running in shared-cache mode, a database operation may fail with
  6708. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6709. ** individual tables within the shared-cache cannot be obtained. See
  6710. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6711. ** ^This API may be used to register a callback that SQLite will invoke
  6712. ** when the connection currently holding the required lock relinquishes it.
  6713. ** ^This API is only available if the library was compiled with the
  6714. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6715. **
  6716. ** See Also: [Using the SQLite Unlock Notification Feature].
  6717. **
  6718. ** ^Shared-cache locks are released when a database connection concludes
  6719. ** its current transaction, either by committing it or rolling it back.
  6720. **
  6721. ** ^When a connection (known as the blocked connection) fails to obtain a
  6722. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6723. ** identity of the database connection (the blocking connection) that
  6724. ** has locked the required resource is stored internally. ^After an
  6725. ** application receives an SQLITE_LOCKED error, it may call the
  6726. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6727. ** the first argument to register for a callback that will be invoked
  6728. ** when the blocking connections current transaction is concluded. ^The
  6729. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6730. ** call that concludes the blocking connections transaction.
  6731. **
  6732. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6733. ** there is a chance that the blocking connection will have already
  6734. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6735. ** If this happens, then the specified callback is invoked immediately,
  6736. ** from within the call to sqlite3_unlock_notify().)^
  6737. **
  6738. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6739. ** shared-cache table, and more than one other connection currently holds
  6740. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6741. ** the other connections to use as the blocking connection.
  6742. **
  6743. ** ^(There may be at most one unlock-notify callback registered by a
  6744. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6745. ** blocked connection already has a registered unlock-notify callback,
  6746. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6747. ** called with a NULL pointer as its second argument, then any existing
  6748. ** unlock-notify callback is canceled. ^The blocked connections
  6749. ** unlock-notify callback may also be canceled by closing the blocked
  6750. ** connection using [sqlite3_close()].
  6751. **
  6752. ** The unlock-notify callback is not reentrant. If an application invokes
  6753. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6754. ** crash or deadlock may be the result.
  6755. **
  6756. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6757. ** returns SQLITE_OK.
  6758. **
  6759. ** <b>Callback Invocation Details</b>
  6760. **
  6761. ** When an unlock-notify callback is registered, the application provides a
  6762. ** single void* pointer that is passed to the callback when it is invoked.
  6763. ** However, the signature of the callback function allows SQLite to pass
  6764. ** it an array of void* context pointers. The first argument passed to
  6765. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6766. ** and the second is the number of entries in the array.
  6767. **
  6768. ** When a blocking connections transaction is concluded, there may be
  6769. ** more than one blocked connection that has registered for an unlock-notify
  6770. ** callback. ^If two or more such blocked connections have specified the
  6771. ** same callback function, then instead of invoking the callback function
  6772. ** multiple times, it is invoked once with the set of void* context pointers
  6773. ** specified by the blocked connections bundled together into an array.
  6774. ** This gives the application an opportunity to prioritize any actions
  6775. ** related to the set of unblocked database connections.
  6776. **
  6777. ** <b>Deadlock Detection</b>
  6778. **
  6779. ** Assuming that after registering for an unlock-notify callback a
  6780. ** database waits for the callback to be issued before taking any further
  6781. ** action (a reasonable assumption), then using this API may cause the
  6782. ** application to deadlock. For example, if connection X is waiting for
  6783. ** connection Y's transaction to be concluded, and similarly connection
  6784. ** Y is waiting on connection X's transaction, then neither connection
  6785. ** will proceed and the system may remain deadlocked indefinitely.
  6786. **
  6787. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6788. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6789. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6790. ** unlock-notify callback is registered. The system is said to be in
  6791. ** a deadlocked state if connection A has registered for an unlock-notify
  6792. ** callback on the conclusion of connection B's transaction, and connection
  6793. ** B has itself registered for an unlock-notify callback when connection
  6794. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6795. ** the system is also considered to be deadlocked if connection B has
  6796. ** registered for an unlock-notify callback on the conclusion of connection
  6797. ** C's transaction, where connection C is waiting on connection A. ^Any
  6798. ** number of levels of indirection are allowed.
  6799. **
  6800. ** <b>The "DROP TABLE" Exception</b>
  6801. **
  6802. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6803. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6804. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6805. ** SQLite checks if there are any currently executing SELECT statements
  6806. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6807. ** returned. In this case there is no "blocking connection", so invoking
  6808. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6809. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6810. ** or "DROP INDEX" query, an infinite loop might be the result.
  6811. **
  6812. ** One way around this problem is to check the extended error code returned
  6813. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6814. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6815. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6816. ** SQLITE_LOCKED.)^
  6817. */
  6818. SQLITE_API int sqlite3_unlock_notify(
  6819. sqlite3 *pBlocked, /* Waiting connection */
  6820. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6821. void *pNotifyArg /* Argument to pass to xNotify */
  6822. );
  6823. /*
  6824. ** CAPI3REF: String Comparison
  6825. **
  6826. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  6827. ** and extensions to compare the contents of two buffers containing UTF-8
  6828. ** strings in a case-independent fashion, using the same definition of "case
  6829. ** independence" that SQLite uses internally when comparing identifiers.
  6830. */
  6831. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  6832. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6833. /*
  6834. ** CAPI3REF: String Globbing
  6835. *
  6836. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  6837. ** the glob pattern P, and it returns non-zero if string X does not match
  6838. ** the glob pattern P. ^The definition of glob pattern matching used in
  6839. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  6840. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  6841. ** sensitive.
  6842. **
  6843. ** Note that this routine returns zero on a match and non-zero if the strings
  6844. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  6845. */
  6846. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  6847. /*
  6848. ** CAPI3REF: Error Logging Interface
  6849. **
  6850. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  6851. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6852. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6853. ** used with [sqlite3_snprintf()] to generate the final output string.
  6854. **
  6855. ** The sqlite3_log() interface is intended for use by extensions such as
  6856. ** virtual tables, collating functions, and SQL functions. While there is
  6857. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6858. ** is considered bad form.
  6859. **
  6860. ** The zFormat string must not be NULL.
  6861. **
  6862. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6863. ** will not use dynamically allocated memory. The log message is stored in
  6864. ** a fixed-length buffer on the stack. If the log message is longer than
  6865. ** a few hundred characters, it will be truncated to the length of the
  6866. ** buffer.
  6867. */
  6868. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6869. /*
  6870. ** CAPI3REF: Write-Ahead Log Commit Hook
  6871. **
  6872. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6873. ** will be invoked each time a database connection commits data to a
  6874. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6875. ** [journal_mode | journal_mode=WAL mode]).
  6876. **
  6877. ** ^The callback is invoked by SQLite after the commit has taken place and
  6878. ** the associated write-lock on the database released, so the implementation
  6879. ** may read, write or [checkpoint] the database as required.
  6880. **
  6881. ** ^The first parameter passed to the callback function when it is invoked
  6882. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6883. ** registering the callback. ^The second is a copy of the database handle.
  6884. ** ^The third parameter is the name of the database that was written to -
  6885. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6886. ** is the number of pages currently in the write-ahead log file,
  6887. ** including those that were just committed.
  6888. **
  6889. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6890. ** code is returned, that error will propagate back up through the
  6891. ** SQLite code base to cause the statement that provoked the callback
  6892. ** to report an error, though the commit will have still occurred. If the
  6893. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6894. ** that does not correspond to any valid SQLite error code, the results
  6895. ** are undefined.
  6896. **
  6897. ** A single database handle may have at most a single write-ahead log callback
  6898. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6899. ** previously registered write-ahead log callback. ^Note that the
  6900. ** [sqlite3_wal_autocheckpoint()] interface and the
  6901. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6902. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6903. */
  6904. SQLITE_API void *sqlite3_wal_hook(
  6905. sqlite3*,
  6906. int(*)(void *,sqlite3*,const char*,int),
  6907. void*
  6908. );
  6909. /*
  6910. ** CAPI3REF: Configure an auto-checkpoint
  6911. **
  6912. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6913. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  6914. ** to automatically [checkpoint]
  6915. ** after committing a transaction if there are N or
  6916. ** more frames in the [write-ahead log] file. ^Passing zero or
  6917. ** a negative value as the nFrame parameter disables automatic
  6918. ** checkpoints entirely.
  6919. **
  6920. ** ^The callback registered by this function replaces any existing callback
  6921. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  6922. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  6923. ** configured by this function.
  6924. **
  6925. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  6926. ** from SQL.
  6927. **
  6928. ** ^Every new [database connection] defaults to having the auto-checkpoint
  6929. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  6930. ** pages. The use of this interface
  6931. ** is only necessary if the default setting is found to be suboptimal
  6932. ** for a particular application.
  6933. */
  6934. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  6935. /*
  6936. ** CAPI3REF: Checkpoint a database
  6937. **
  6938. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  6939. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  6940. ** empty string, then a checkpoint is run on all databases of
  6941. ** connection D. ^If the database connection D is not in
  6942. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  6943. **
  6944. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  6945. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  6946. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  6947. ** run whenever the WAL reaches a certain size threshold.
  6948. **
  6949. ** See also: [sqlite3_wal_checkpoint_v2()]
  6950. */
  6951. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  6952. /*
  6953. ** CAPI3REF: Checkpoint a database
  6954. **
  6955. ** Run a checkpoint operation on WAL database zDb attached to database
  6956. ** handle db. The specific operation is determined by the value of the
  6957. ** eMode parameter:
  6958. **
  6959. ** <dl>
  6960. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  6961. ** Checkpoint as many frames as possible without waiting for any database
  6962. ** readers or writers to finish. Sync the db file if all frames in the log
  6963. ** are checkpointed. This mode is the same as calling
  6964. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  6965. **
  6966. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  6967. ** This mode blocks (calls the busy-handler callback) until there is no
  6968. ** database writer and all readers are reading from the most recent database
  6969. ** snapshot. It then checkpoints all frames in the log file and syncs the
  6970. ** database file. This call blocks database writers while it is running,
  6971. ** but not database readers.
  6972. **
  6973. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  6974. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  6975. ** checkpointing the log file it blocks (calls the busy-handler callback)
  6976. ** until all readers are reading from the database file only. This ensures
  6977. ** that the next client to write to the database file restarts the log file
  6978. ** from the beginning. This call blocks database writers while it is running,
  6979. ** but not database readers.
  6980. ** </dl>
  6981. **
  6982. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  6983. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  6984. ** the total number of checkpointed frames (including any that were already
  6985. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  6986. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  6987. ** If no values are available because of an error, they are both set to -1
  6988. ** before returning to communicate this to the caller.
  6989. **
  6990. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  6991. ** any other process is running a checkpoint operation at the same time, the
  6992. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  6993. ** busy-handler configured, it will not be invoked in this case.
  6994. **
  6995. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  6996. ** "writer" lock on the database file. If the writer lock cannot be obtained
  6997. ** immediately, and a busy-handler is configured, it is invoked and the writer
  6998. ** lock retried until either the busy-handler returns 0 or the lock is
  6999. ** successfully obtained. The busy-handler is also invoked while waiting for
  7000. ** database readers as described above. If the busy-handler returns 0 before
  7001. ** the writer lock is obtained or while waiting for database readers, the
  7002. ** checkpoint operation proceeds from that point in the same way as
  7003. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7004. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7005. **
  7006. ** If parameter zDb is NULL or points to a zero length string, then the
  7007. ** specified operation is attempted on all WAL databases. In this case the
  7008. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7009. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7010. ** attached WAL databases, the operation is still attempted on any remaining
  7011. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7012. ** error occurs while processing an attached database, processing is abandoned
  7013. ** and the error code returned to the caller immediately. If no error
  7014. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7015. ** databases, SQLITE_OK is returned.
  7016. **
  7017. ** If database zDb is the name of an attached database that is not in WAL
  7018. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7019. ** zDb is not NULL (or a zero length string) and is not the name of any
  7020. ** attached database, SQLITE_ERROR is returned to the caller.
  7021. */
  7022. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7023. sqlite3 *db, /* Database handle */
  7024. const char *zDb, /* Name of attached database (or NULL) */
  7025. int eMode, /* SQLITE_CHECKPOINT_* value */
  7026. int *pnLog, /* OUT: Size of WAL log in frames */
  7027. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7028. );
  7029. /*
  7030. ** CAPI3REF: Checkpoint operation parameters
  7031. **
  7032. ** These constants can be used as the 3rd parameter to
  7033. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7034. ** documentation for additional information about the meaning and use of
  7035. ** each of these values.
  7036. */
  7037. #define SQLITE_CHECKPOINT_PASSIVE 0
  7038. #define SQLITE_CHECKPOINT_FULL 1
  7039. #define SQLITE_CHECKPOINT_RESTART 2
  7040. /*
  7041. ** CAPI3REF: Virtual Table Interface Configuration
  7042. **
  7043. ** This function may be called by either the [xConnect] or [xCreate] method
  7044. ** of a [virtual table] implementation to configure
  7045. ** various facets of the virtual table interface.
  7046. **
  7047. ** If this interface is invoked outside the context of an xConnect or
  7048. ** xCreate virtual table method then the behavior is undefined.
  7049. **
  7050. ** At present, there is only one option that may be configured using
  7051. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7052. ** may be added in the future.
  7053. */
  7054. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7055. /*
  7056. ** CAPI3REF: Virtual Table Configuration Options
  7057. **
  7058. ** These macros define the various options to the
  7059. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7060. ** can use to customize and optimize their behavior.
  7061. **
  7062. ** <dl>
  7063. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7064. ** <dd>Calls of the form
  7065. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7066. ** where X is an integer. If X is zero, then the [virtual table] whose
  7067. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7068. ** support constraints. In this configuration (which is the default) if
  7069. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7070. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7071. ** specified as part of the users SQL statement, regardless of the actual
  7072. ** ON CONFLICT mode specified.
  7073. **
  7074. ** If X is non-zero, then the virtual table implementation guarantees
  7075. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7076. ** any modifications to internal or persistent data structures have been made.
  7077. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7078. ** is able to roll back a statement or database transaction, and abandon
  7079. ** or continue processing the current SQL statement as appropriate.
  7080. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7081. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7082. ** had been ABORT.
  7083. **
  7084. ** Virtual table implementations that are required to handle OR REPLACE
  7085. ** must do so within the [xUpdate] method. If a call to the
  7086. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7087. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7088. ** silently replace the appropriate rows within the xUpdate callback and
  7089. ** return SQLITE_OK. Or, if this is not possible, it may return
  7090. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7091. ** constraint handling.
  7092. ** </dl>
  7093. */
  7094. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7095. /*
  7096. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7097. **
  7098. ** This function may only be called from within a call to the [xUpdate] method
  7099. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7100. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7101. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7102. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7103. ** [virtual table].
  7104. */
  7105. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7106. /*
  7107. ** CAPI3REF: Conflict resolution modes
  7108. **
  7109. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7110. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7111. ** is for the SQL statement being evaluated.
  7112. **
  7113. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7114. ** return value from the [sqlite3_set_authorizer()] callback and that
  7115. ** [SQLITE_ABORT] is also a [result code].
  7116. */
  7117. #define SQLITE_ROLLBACK 1
  7118. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7119. #define SQLITE_FAIL 3
  7120. /* #define SQLITE_ABORT 4 // Also an error code */
  7121. #define SQLITE_REPLACE 5
  7122. /*
  7123. ** Undo the hack that converts floating point types to integer for
  7124. ** builds on processors without floating point support.
  7125. */
  7126. #ifdef SQLITE_OMIT_FLOATING_POINT
  7127. # undef double
  7128. #endif
  7129. #if 0
  7130. } /* End of the 'extern "C"' block */
  7131. #endif
  7132. #endif /* _SQLITE3_H_ */
  7133. /*
  7134. ** 2010 August 30
  7135. **
  7136. ** The author disclaims copyright to this source code. In place of
  7137. ** a legal notice, here is a blessing:
  7138. **
  7139. ** May you do good and not evil.
  7140. ** May you find forgiveness for yourself and forgive others.
  7141. ** May you share freely, never taking more than you give.
  7142. **
  7143. *************************************************************************
  7144. */
  7145. #ifndef _SQLITE3RTREE_H_
  7146. #define _SQLITE3RTREE_H_
  7147. #if 0
  7148. extern "C" {
  7149. #endif
  7150. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7151. /*
  7152. ** Register a geometry callback named zGeom that can be used as part of an
  7153. ** R-Tree geometry query as follows:
  7154. **
  7155. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7156. */
  7157. SQLITE_API int sqlite3_rtree_geometry_callback(
  7158. sqlite3 *db,
  7159. const char *zGeom,
  7160. #ifdef SQLITE_RTREE_INT_ONLY
  7161. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7162. #else
  7163. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7164. #endif
  7165. void *pContext
  7166. );
  7167. /*
  7168. ** A pointer to a structure of the following type is passed as the first
  7169. ** argument to callbacks registered using rtree_geometry_callback().
  7170. */
  7171. struct sqlite3_rtree_geometry {
  7172. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7173. int nParam; /* Size of array aParam[] */
  7174. double *aParam; /* Parameters passed to SQL geom function */
  7175. void *pUser; /* Callback implementation user data */
  7176. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7177. };
  7178. #if 0
  7179. } /* end of the 'extern "C"' block */
  7180. #endif
  7181. #endif /* ifndef _SQLITE3RTREE_H_ */
  7182. /************** End of sqlite3.h *********************************************/
  7183. /************** Begin file sqliteInt.h ***************************************/
  7184. /*
  7185. ** 2001 September 15
  7186. **
  7187. ** The author disclaims copyright to this source code. In place of
  7188. ** a legal notice, here is a blessing:
  7189. **
  7190. ** May you do good and not evil.
  7191. ** May you find forgiveness for yourself and forgive others.
  7192. ** May you share freely, never taking more than you give.
  7193. **
  7194. *************************************************************************
  7195. ** Internal interface definitions for SQLite.
  7196. **
  7197. */
  7198. #ifndef _SQLITEINT_H_
  7199. #define _SQLITEINT_H_
  7200. /*
  7201. ** These #defines should enable >2GB file support on POSIX if the
  7202. ** underlying operating system supports it. If the OS lacks
  7203. ** large file support, or if the OS is windows, these should be no-ops.
  7204. **
  7205. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  7206. ** system #includes. Hence, this block of code must be the very first
  7207. ** code in all source files.
  7208. **
  7209. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  7210. ** on the compiler command line. This is necessary if you are compiling
  7211. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  7212. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  7213. ** without this option, LFS is enable. But LFS does not exist in the kernel
  7214. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  7215. ** portability you should omit LFS.
  7216. **
  7217. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  7218. */
  7219. #ifndef SQLITE_DISABLE_LFS
  7220. # define _LARGE_FILE 1
  7221. # ifndef _FILE_OFFSET_BITS
  7222. # define _FILE_OFFSET_BITS 64
  7223. # endif
  7224. # define _LARGEFILE_SOURCE 1
  7225. #endif
  7226. /*
  7227. ** Include the configuration header output by 'configure' if we're using the
  7228. ** autoconf-based build
  7229. */
  7230. #ifdef _HAVE_SQLITE_CONFIG_H
  7231. #include "config.h"
  7232. #endif
  7233. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7234. /************** Begin file sqliteLimit.h *************************************/
  7235. /*
  7236. ** 2007 May 7
  7237. **
  7238. ** The author disclaims copyright to this source code. In place of
  7239. ** a legal notice, here is a blessing:
  7240. **
  7241. ** May you do good and not evil.
  7242. ** May you find forgiveness for yourself and forgive others.
  7243. ** May you share freely, never taking more than you give.
  7244. **
  7245. *************************************************************************
  7246. **
  7247. ** This file defines various limits of what SQLite can process.
  7248. */
  7249. /*
  7250. ** The maximum length of a TEXT or BLOB in bytes. This also
  7251. ** limits the size of a row in a table or index.
  7252. **
  7253. ** The hard limit is the ability of a 32-bit signed integer
  7254. ** to count the size: 2^31-1 or 2147483647.
  7255. */
  7256. #ifndef SQLITE_MAX_LENGTH
  7257. # define SQLITE_MAX_LENGTH 1000000000
  7258. #endif
  7259. /*
  7260. ** This is the maximum number of
  7261. **
  7262. ** * Columns in a table
  7263. ** * Columns in an index
  7264. ** * Columns in a view
  7265. ** * Terms in the SET clause of an UPDATE statement
  7266. ** * Terms in the result set of a SELECT statement
  7267. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7268. ** * Terms in the VALUES clause of an INSERT statement
  7269. **
  7270. ** The hard upper limit here is 32676. Most database people will
  7271. ** tell you that in a well-normalized database, you usually should
  7272. ** not have more than a dozen or so columns in any table. And if
  7273. ** that is the case, there is no point in having more than a few
  7274. ** dozen values in any of the other situations described above.
  7275. */
  7276. #ifndef SQLITE_MAX_COLUMN
  7277. # define SQLITE_MAX_COLUMN 2000
  7278. #endif
  7279. /*
  7280. ** The maximum length of a single SQL statement in bytes.
  7281. **
  7282. ** It used to be the case that setting this value to zero would
  7283. ** turn the limit off. That is no longer true. It is not possible
  7284. ** to turn this limit off.
  7285. */
  7286. #ifndef SQLITE_MAX_SQL_LENGTH
  7287. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7288. #endif
  7289. /*
  7290. ** The maximum depth of an expression tree. This is limited to
  7291. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7292. ** want to place more severe limits on the complexity of an
  7293. ** expression.
  7294. **
  7295. ** A value of 0 used to mean that the limit was not enforced.
  7296. ** But that is no longer true. The limit is now strictly enforced
  7297. ** at all times.
  7298. */
  7299. #ifndef SQLITE_MAX_EXPR_DEPTH
  7300. # define SQLITE_MAX_EXPR_DEPTH 1000
  7301. #endif
  7302. /*
  7303. ** The maximum number of terms in a compound SELECT statement.
  7304. ** The code generator for compound SELECT statements does one
  7305. ** level of recursion for each term. A stack overflow can result
  7306. ** if the number of terms is too large. In practice, most SQL
  7307. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7308. ** any limit on the number of terms in a compount SELECT.
  7309. */
  7310. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7311. # define SQLITE_MAX_COMPOUND_SELECT 500
  7312. #endif
  7313. /*
  7314. ** The maximum number of opcodes in a VDBE program.
  7315. ** Not currently enforced.
  7316. */
  7317. #ifndef SQLITE_MAX_VDBE_OP
  7318. # define SQLITE_MAX_VDBE_OP 25000
  7319. #endif
  7320. /*
  7321. ** The maximum number of arguments to an SQL function.
  7322. */
  7323. #ifndef SQLITE_MAX_FUNCTION_ARG
  7324. # define SQLITE_MAX_FUNCTION_ARG 127
  7325. #endif
  7326. /*
  7327. ** The maximum number of in-memory pages to use for the main database
  7328. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7329. */
  7330. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7331. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7332. #endif
  7333. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7334. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7335. #endif
  7336. /*
  7337. ** The default number of frames to accumulate in the log file before
  7338. ** checkpointing the database in WAL mode.
  7339. */
  7340. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7341. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7342. #endif
  7343. /*
  7344. ** The maximum number of attached databases. This must be between 0
  7345. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7346. ** is used internally to track attached databases.
  7347. */
  7348. #ifndef SQLITE_MAX_ATTACHED
  7349. # define SQLITE_MAX_ATTACHED 10
  7350. #endif
  7351. /*
  7352. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7353. */
  7354. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7355. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7356. #endif
  7357. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7358. ** imposed by the use of 16-bit offsets within each page.
  7359. **
  7360. ** Earlier versions of SQLite allowed the user to change this value at
  7361. ** compile time. This is no longer permitted, on the grounds that it creates
  7362. ** a library that is technically incompatible with an SQLite library
  7363. ** compiled with a different limit. If a process operating on a database
  7364. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7365. ** compiled with the default page-size limit will not be able to rollback
  7366. ** the aborted transaction. This could lead to database corruption.
  7367. */
  7368. #ifdef SQLITE_MAX_PAGE_SIZE
  7369. # undef SQLITE_MAX_PAGE_SIZE
  7370. #endif
  7371. #define SQLITE_MAX_PAGE_SIZE 65536
  7372. /*
  7373. ** The default size of a database page.
  7374. */
  7375. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7376. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7377. #endif
  7378. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7379. # undef SQLITE_DEFAULT_PAGE_SIZE
  7380. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7381. #endif
  7382. /*
  7383. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7384. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7385. ** device characteristics (sector-size and atomic write() support),
  7386. ** SQLite may choose a larger value. This constant is the maximum value
  7387. ** SQLite will choose on its own.
  7388. */
  7389. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7390. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7391. #endif
  7392. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7393. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7394. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7395. #endif
  7396. /*
  7397. ** Maximum number of pages in one database file.
  7398. **
  7399. ** This is really just the default value for the max_page_count pragma.
  7400. ** This value can be lowered (or raised) at run-time using that the
  7401. ** max_page_count macro.
  7402. */
  7403. #ifndef SQLITE_MAX_PAGE_COUNT
  7404. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7405. #endif
  7406. /*
  7407. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7408. ** operator.
  7409. */
  7410. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7411. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7412. #endif
  7413. /*
  7414. ** Maximum depth of recursion for triggers.
  7415. **
  7416. ** A value of 1 means that a trigger program will not be able to itself
  7417. ** fire any triggers. A value of 0 means that no trigger programs at all
  7418. ** may be executed.
  7419. */
  7420. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7421. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7422. #endif
  7423. /************** End of sqliteLimit.h *****************************************/
  7424. /************** Continuing where we left off in sqliteInt.h ******************/
  7425. /* Disable nuisance warnings on Borland compilers */
  7426. #if defined(__BORLANDC__)
  7427. #pragma warn -rch /* unreachable code */
  7428. #pragma warn -ccc /* Condition is always true or false */
  7429. #pragma warn -aus /* Assigned value is never used */
  7430. #pragma warn -csu /* Comparing signed and unsigned */
  7431. #pragma warn -spa /* Suspicious pointer arithmetic */
  7432. #endif
  7433. /* Needed for various definitions... */
  7434. #ifndef _GNU_SOURCE
  7435. # define _GNU_SOURCE
  7436. #endif
  7437. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  7438. # define _BSD_SOURCE
  7439. #endif
  7440. /*
  7441. ** Include standard header files as necessary
  7442. */
  7443. #ifdef HAVE_STDINT_H
  7444. #include <stdint.h>
  7445. #endif
  7446. #ifdef HAVE_INTTYPES_H
  7447. #include <inttypes.h>
  7448. #endif
  7449. /*
  7450. ** The following macros are used to cast pointers to integers and
  7451. ** integers to pointers. The way you do this varies from one compiler
  7452. ** to the next, so we have developed the following set of #if statements
  7453. ** to generate appropriate macros for a wide range of compilers.
  7454. **
  7455. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7456. ** Unfortunately, that typedef is not available on all compilers, or
  7457. ** if it is available, it requires an #include of specific headers
  7458. ** that vary from one machine to the next.
  7459. **
  7460. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7461. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7462. ** So we have to define the macros in different ways depending on the
  7463. ** compiler.
  7464. */
  7465. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7466. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7467. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7468. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7469. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7470. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7471. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7472. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7473. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7474. #else /* Generates a warning - but it always works */
  7475. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7476. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7477. #endif
  7478. /*
  7479. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7480. ** 0 means mutexes are permanently disable and the library is never
  7481. ** threadsafe. 1 means the library is serialized which is the highest
  7482. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7483. ** threads can use SQLite as long as no two threads try to use the same
  7484. ** database connection at the same time.
  7485. **
  7486. ** Older versions of SQLite used an optional THREADSAFE macro.
  7487. ** We support that for legacy.
  7488. */
  7489. #if !defined(SQLITE_THREADSAFE)
  7490. # if defined(THREADSAFE)
  7491. # define SQLITE_THREADSAFE THREADSAFE
  7492. # else
  7493. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7494. # endif
  7495. #endif
  7496. /*
  7497. ** Powersafe overwrite is on by default. But can be turned off using
  7498. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7499. */
  7500. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7501. # define SQLITE_POWERSAFE_OVERWRITE 1
  7502. #endif
  7503. /*
  7504. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7505. ** It determines whether or not the features related to
  7506. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7507. ** be overridden at runtime using the sqlite3_config() API.
  7508. */
  7509. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7510. # define SQLITE_DEFAULT_MEMSTATUS 1
  7511. #endif
  7512. /*
  7513. ** Exactly one of the following macros must be defined in order to
  7514. ** specify which memory allocation subsystem to use.
  7515. **
  7516. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7517. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7518. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7519. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7520. **
  7521. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7522. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7523. ** will cause HeapValidate to be called. If heap validation should fail, an
  7524. ** assertion will be triggered.
  7525. **
  7526. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7527. ** the default.
  7528. */
  7529. #if defined(SQLITE_SYSTEM_MALLOC) \
  7530. + defined(SQLITE_WIN32_MALLOC) \
  7531. + defined(SQLITE_ZERO_MALLOC) \
  7532. + defined(SQLITE_MEMDEBUG)>1
  7533. # error "Two or more of the following compile-time configuration options\
  7534. are defined but at most one is allowed:\
  7535. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7536. SQLITE_ZERO_MALLOC"
  7537. #endif
  7538. #if defined(SQLITE_SYSTEM_MALLOC) \
  7539. + defined(SQLITE_WIN32_MALLOC) \
  7540. + defined(SQLITE_ZERO_MALLOC) \
  7541. + defined(SQLITE_MEMDEBUG)==0
  7542. # define SQLITE_SYSTEM_MALLOC 1
  7543. #endif
  7544. /*
  7545. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7546. ** sizes of memory allocations below this value where possible.
  7547. */
  7548. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7549. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7550. #endif
  7551. /*
  7552. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7553. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7554. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7555. ** it.
  7556. */
  7557. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7558. # define _XOPEN_SOURCE 600
  7559. #endif
  7560. /*
  7561. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7562. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7563. ** make it true by defining or undefining NDEBUG.
  7564. **
  7565. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7566. ** assert() statements in the code. So we want the default action
  7567. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7568. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7569. ** feature.
  7570. */
  7571. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7572. # define NDEBUG 1
  7573. #endif
  7574. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7575. # undef NDEBUG
  7576. #endif
  7577. /*
  7578. ** The testcase() macro is used to aid in coverage testing. When
  7579. ** doing coverage testing, the condition inside the argument to
  7580. ** testcase() must be evaluated both true and false in order to
  7581. ** get full branch coverage. The testcase() macro is inserted
  7582. ** to help ensure adequate test coverage in places where simple
  7583. ** condition/decision coverage is inadequate. For example, testcase()
  7584. ** can be used to make sure boundary values are tested. For
  7585. ** bitmask tests, testcase() can be used to make sure each bit
  7586. ** is significant and used at least once. On switch statements
  7587. ** where multiple cases go to the same block of code, testcase()
  7588. ** can insure that all cases are evaluated.
  7589. **
  7590. */
  7591. #ifdef SQLITE_COVERAGE_TEST
  7592. SQLITE_PRIVATE void sqlite3Coverage(int);
  7593. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7594. #else
  7595. # define testcase(X)
  7596. #endif
  7597. /*
  7598. ** The TESTONLY macro is used to enclose variable declarations or
  7599. ** other bits of code that are needed to support the arguments
  7600. ** within testcase() and assert() macros.
  7601. */
  7602. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7603. # define TESTONLY(X) X
  7604. #else
  7605. # define TESTONLY(X)
  7606. #endif
  7607. /*
  7608. ** Sometimes we need a small amount of code such as a variable initialization
  7609. ** to setup for a later assert() statement. We do not want this code to
  7610. ** appear when assert() is disabled. The following macro is therefore
  7611. ** used to contain that setup code. The "VVA" acronym stands for
  7612. ** "Verification, Validation, and Accreditation". In other words, the
  7613. ** code within VVA_ONLY() will only run during verification processes.
  7614. */
  7615. #ifndef NDEBUG
  7616. # define VVA_ONLY(X) X
  7617. #else
  7618. # define VVA_ONLY(X)
  7619. #endif
  7620. /*
  7621. ** The ALWAYS and NEVER macros surround boolean expressions which
  7622. ** are intended to always be true or false, respectively. Such
  7623. ** expressions could be omitted from the code completely. But they
  7624. ** are included in a few cases in order to enhance the resilience
  7625. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7626. ** or "ductile" rather than being "brittle" and crashing at the first
  7627. ** hint of unplanned behavior.
  7628. **
  7629. ** In other words, ALWAYS and NEVER are added for defensive code.
  7630. **
  7631. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7632. ** be true and false so that the unreachable code they specify will
  7633. ** not be counted as untested code.
  7634. */
  7635. #if defined(SQLITE_COVERAGE_TEST)
  7636. # define ALWAYS(X) (1)
  7637. # define NEVER(X) (0)
  7638. #elif !defined(NDEBUG)
  7639. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7640. # define NEVER(X) ((X)?(assert(0),1):0)
  7641. #else
  7642. # define ALWAYS(X) (X)
  7643. # define NEVER(X) (X)
  7644. #endif
  7645. /*
  7646. ** Return true (non-zero) if the input is a integer that is too large
  7647. ** to fit in 32-bits. This macro is used inside of various testcase()
  7648. ** macros to verify that we have tested SQLite for large-file support.
  7649. */
  7650. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7651. /*
  7652. ** The macro unlikely() is a hint that surrounds a boolean
  7653. ** expression that is usually false. Macro likely() surrounds
  7654. ** a boolean expression that is usually true. These hints could,
  7655. ** in theory, be used by the compiler to generate better code, but
  7656. ** currently they are just comments for human readers.
  7657. */
  7658. #define likely(X) (X)
  7659. #define unlikely(X) (X)
  7660. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7661. /************** Begin file hash.h ********************************************/
  7662. /*
  7663. ** 2001 September 22
  7664. **
  7665. ** The author disclaims copyright to this source code. In place of
  7666. ** a legal notice, here is a blessing:
  7667. **
  7668. ** May you do good and not evil.
  7669. ** May you find forgiveness for yourself and forgive others.
  7670. ** May you share freely, never taking more than you give.
  7671. **
  7672. *************************************************************************
  7673. ** This is the header file for the generic hash-table implementation
  7674. ** used in SQLite.
  7675. */
  7676. #ifndef _SQLITE_HASH_H_
  7677. #define _SQLITE_HASH_H_
  7678. /* Forward declarations of structures. */
  7679. typedef struct Hash Hash;
  7680. typedef struct HashElem HashElem;
  7681. /* A complete hash table is an instance of the following structure.
  7682. ** The internals of this structure are intended to be opaque -- client
  7683. ** code should not attempt to access or modify the fields of this structure
  7684. ** directly. Change this structure only by using the routines below.
  7685. ** However, some of the "procedures" and "functions" for modifying and
  7686. ** accessing this structure are really macros, so we can't really make
  7687. ** this structure opaque.
  7688. **
  7689. ** All elements of the hash table are on a single doubly-linked list.
  7690. ** Hash.first points to the head of this list.
  7691. **
  7692. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7693. ** the global doubly-linked list. The contents of the bucket are the
  7694. ** element pointed to plus the next _ht.count-1 elements in the list.
  7695. **
  7696. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7697. ** by a linear search of the global list. For small tables, the
  7698. ** Hash.ht table is never allocated because if there are few elements
  7699. ** in the table, it is faster to do a linear search than to manage
  7700. ** the hash table.
  7701. */
  7702. struct Hash {
  7703. unsigned int htsize; /* Number of buckets in the hash table */
  7704. unsigned int count; /* Number of entries in this table */
  7705. HashElem *first; /* The first element of the array */
  7706. struct _ht { /* the hash table */
  7707. int count; /* Number of entries with this hash */
  7708. HashElem *chain; /* Pointer to first entry with this hash */
  7709. } *ht;
  7710. };
  7711. /* Each element in the hash table is an instance of the following
  7712. ** structure. All elements are stored on a single doubly-linked list.
  7713. **
  7714. ** Again, this structure is intended to be opaque, but it can't really
  7715. ** be opaque because it is used by macros.
  7716. */
  7717. struct HashElem {
  7718. HashElem *next, *prev; /* Next and previous elements in the table */
  7719. void *data; /* Data associated with this element */
  7720. const char *pKey; int nKey; /* Key associated with this element */
  7721. };
  7722. /*
  7723. ** Access routines. To delete, insert a NULL pointer.
  7724. */
  7725. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7726. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7727. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7728. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7729. /*
  7730. ** Macros for looping over all elements of a hash table. The idiom is
  7731. ** like this:
  7732. **
  7733. ** Hash h;
  7734. ** HashElem *p;
  7735. ** ...
  7736. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7737. ** SomeStructure *pData = sqliteHashData(p);
  7738. ** // do something with pData
  7739. ** }
  7740. */
  7741. #define sqliteHashFirst(H) ((H)->first)
  7742. #define sqliteHashNext(E) ((E)->next)
  7743. #define sqliteHashData(E) ((E)->data)
  7744. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7745. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7746. /*
  7747. ** Number of entries in a hash table
  7748. */
  7749. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7750. #endif /* _SQLITE_HASH_H_ */
  7751. /************** End of hash.h ************************************************/
  7752. /************** Continuing where we left off in sqliteInt.h ******************/
  7753. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7754. /************** Begin file parse.h *******************************************/
  7755. #define TK_SEMI 1
  7756. #define TK_EXPLAIN 2
  7757. #define TK_QUERY 3
  7758. #define TK_PLAN 4
  7759. #define TK_BEGIN 5
  7760. #define TK_TRANSACTION 6
  7761. #define TK_DEFERRED 7
  7762. #define TK_IMMEDIATE 8
  7763. #define TK_EXCLUSIVE 9
  7764. #define TK_COMMIT 10
  7765. #define TK_END 11
  7766. #define TK_ROLLBACK 12
  7767. #define TK_SAVEPOINT 13
  7768. #define TK_RELEASE 14
  7769. #define TK_TO 15
  7770. #define TK_TABLE 16
  7771. #define TK_CREATE 17
  7772. #define TK_IF 18
  7773. #define TK_NOT 19
  7774. #define TK_EXISTS 20
  7775. #define TK_TEMP 21
  7776. #define TK_LP 22
  7777. #define TK_RP 23
  7778. #define TK_AS 24
  7779. #define TK_COMMA 25
  7780. #define TK_ID 26
  7781. #define TK_INDEXED 27
  7782. #define TK_ABORT 28
  7783. #define TK_ACTION 29
  7784. #define TK_AFTER 30
  7785. #define TK_ANALYZE 31
  7786. #define TK_ASC 32
  7787. #define TK_ATTACH 33
  7788. #define TK_BEFORE 34
  7789. #define TK_BY 35
  7790. #define TK_CASCADE 36
  7791. #define TK_CAST 37
  7792. #define TK_COLUMNKW 38
  7793. #define TK_CONFLICT 39
  7794. #define TK_DATABASE 40
  7795. #define TK_DESC 41
  7796. #define TK_DETACH 42
  7797. #define TK_EACH 43
  7798. #define TK_FAIL 44
  7799. #define TK_FOR 45
  7800. #define TK_IGNORE 46
  7801. #define TK_INITIALLY 47
  7802. #define TK_INSTEAD 48
  7803. #define TK_LIKE_KW 49
  7804. #define TK_MATCH 50
  7805. #define TK_NO 51
  7806. #define TK_KEY 52
  7807. #define TK_OF 53
  7808. #define TK_OFFSET 54
  7809. #define TK_PRAGMA 55
  7810. #define TK_RAISE 56
  7811. #define TK_REPLACE 57
  7812. #define TK_RESTRICT 58
  7813. #define TK_ROW 59
  7814. #define TK_TRIGGER 60
  7815. #define TK_VACUUM 61
  7816. #define TK_VIEW 62
  7817. #define TK_VIRTUAL 63
  7818. #define TK_REINDEX 64
  7819. #define TK_RENAME 65
  7820. #define TK_CTIME_KW 66
  7821. #define TK_ANY 67
  7822. #define TK_OR 68
  7823. #define TK_AND 69
  7824. #define TK_IS 70
  7825. #define TK_BETWEEN 71
  7826. #define TK_IN 72
  7827. #define TK_ISNULL 73
  7828. #define TK_NOTNULL 74
  7829. #define TK_NE 75
  7830. #define TK_EQ 76
  7831. #define TK_GT 77
  7832. #define TK_LE 78
  7833. #define TK_LT 79
  7834. #define TK_GE 80
  7835. #define TK_ESCAPE 81
  7836. #define TK_BITAND 82
  7837. #define TK_BITOR 83
  7838. #define TK_LSHIFT 84
  7839. #define TK_RSHIFT 85
  7840. #define TK_PLUS 86
  7841. #define TK_MINUS 87
  7842. #define TK_STAR 88
  7843. #define TK_SLASH 89
  7844. #define TK_REM 90
  7845. #define TK_CONCAT 91
  7846. #define TK_COLLATE 92
  7847. #define TK_BITNOT 93
  7848. #define TK_STRING 94
  7849. #define TK_JOIN_KW 95
  7850. #define TK_CONSTRAINT 96
  7851. #define TK_DEFAULT 97
  7852. #define TK_NULL 98
  7853. #define TK_PRIMARY 99
  7854. #define TK_UNIQUE 100
  7855. #define TK_CHECK 101
  7856. #define TK_REFERENCES 102
  7857. #define TK_AUTOINCR 103
  7858. #define TK_ON 104
  7859. #define TK_INSERT 105
  7860. #define TK_DELETE 106
  7861. #define TK_UPDATE 107
  7862. #define TK_SET 108
  7863. #define TK_DEFERRABLE 109
  7864. #define TK_FOREIGN 110
  7865. #define TK_DROP 111
  7866. #define TK_UNION 112
  7867. #define TK_ALL 113
  7868. #define TK_EXCEPT 114
  7869. #define TK_INTERSECT 115
  7870. #define TK_SELECT 116
  7871. #define TK_DISTINCT 117
  7872. #define TK_DOT 118
  7873. #define TK_FROM 119
  7874. #define TK_JOIN 120
  7875. #define TK_USING 121
  7876. #define TK_ORDER 122
  7877. #define TK_GROUP 123
  7878. #define TK_HAVING 124
  7879. #define TK_LIMIT 125
  7880. #define TK_WHERE 126
  7881. #define TK_INTO 127
  7882. #define TK_VALUES 128
  7883. #define TK_INTEGER 129
  7884. #define TK_FLOAT 130
  7885. #define TK_BLOB 131
  7886. #define TK_REGISTER 132
  7887. #define TK_VARIABLE 133
  7888. #define TK_CASE 134
  7889. #define TK_WHEN 135
  7890. #define TK_THEN 136
  7891. #define TK_ELSE 137
  7892. #define TK_INDEX 138
  7893. #define TK_ALTER 139
  7894. #define TK_ADD 140
  7895. #define TK_TO_TEXT 141
  7896. #define TK_TO_BLOB 142
  7897. #define TK_TO_NUMERIC 143
  7898. #define TK_TO_INT 144
  7899. #define TK_TO_REAL 145
  7900. #define TK_ISNOT 146
  7901. #define TK_END_OF_FILE 147
  7902. #define TK_ILLEGAL 148
  7903. #define TK_SPACE 149
  7904. #define TK_UNCLOSED_STRING 150
  7905. #define TK_FUNCTION 151
  7906. #define TK_COLUMN 152
  7907. #define TK_AGG_FUNCTION 153
  7908. #define TK_AGG_COLUMN 154
  7909. #define TK_CONST_FUNC 155
  7910. #define TK_UMINUS 156
  7911. #define TK_UPLUS 157
  7912. /************** End of parse.h ***********************************************/
  7913. /************** Continuing where we left off in sqliteInt.h ******************/
  7914. #include <stdio.h>
  7915. #include <stdlib.h>
  7916. #include <string.h>
  7917. #include <assert.h>
  7918. #include <stddef.h>
  7919. /*
  7920. ** If compiling for a processor that lacks floating point support,
  7921. ** substitute integer for floating-point
  7922. */
  7923. #ifdef SQLITE_OMIT_FLOATING_POINT
  7924. # define double sqlite_int64
  7925. # define float sqlite_int64
  7926. # define LONGDOUBLE_TYPE sqlite_int64
  7927. # ifndef SQLITE_BIG_DBL
  7928. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7929. # endif
  7930. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7931. # define SQLITE_OMIT_TRACE 1
  7932. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7933. # undef SQLITE_HAVE_ISNAN
  7934. #endif
  7935. #ifndef SQLITE_BIG_DBL
  7936. # define SQLITE_BIG_DBL (1e99)
  7937. #endif
  7938. /*
  7939. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7940. ** afterward. Having this macro allows us to cause the C compiler
  7941. ** to omit code used by TEMP tables without messy #ifndef statements.
  7942. */
  7943. #ifdef SQLITE_OMIT_TEMPDB
  7944. #define OMIT_TEMPDB 1
  7945. #else
  7946. #define OMIT_TEMPDB 0
  7947. #endif
  7948. /*
  7949. ** The "file format" number is an integer that is incremented whenever
  7950. ** the VDBE-level file format changes. The following macros define the
  7951. ** the default file format for new databases and the maximum file format
  7952. ** that the library can read.
  7953. */
  7954. #define SQLITE_MAX_FILE_FORMAT 4
  7955. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7956. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7957. #endif
  7958. /*
  7959. ** Determine whether triggers are recursive by default. This can be
  7960. ** changed at run-time using a pragma.
  7961. */
  7962. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7963. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7964. #endif
  7965. /*
  7966. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7967. ** on the command-line
  7968. */
  7969. #ifndef SQLITE_TEMP_STORE
  7970. # define SQLITE_TEMP_STORE 1
  7971. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  7972. #endif
  7973. /*
  7974. ** GCC does not define the offsetof() macro so we'll have to do it
  7975. ** ourselves.
  7976. */
  7977. #ifndef offsetof
  7978. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7979. #endif
  7980. /*
  7981. ** Macros to compute minimum and maximum of two numbers.
  7982. */
  7983. #define MIN(A,B) ((A)<(B)?(A):(B))
  7984. #define MAX(A,B) ((A)>(B)?(A):(B))
  7985. /*
  7986. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7987. ** not, there are still machines out there that use EBCDIC.)
  7988. */
  7989. #if 'A' == '\301'
  7990. # define SQLITE_EBCDIC 1
  7991. #else
  7992. # define SQLITE_ASCII 1
  7993. #endif
  7994. /*
  7995. ** Integers of known sizes. These typedefs might change for architectures
  7996. ** where the sizes very. Preprocessor macros are available so that the
  7997. ** types can be conveniently redefined at compile-type. Like this:
  7998. **
  7999. ** cc '-DUINTPTR_TYPE=long long int' ...
  8000. */
  8001. #ifndef UINT32_TYPE
  8002. # ifdef HAVE_UINT32_T
  8003. # define UINT32_TYPE uint32_t
  8004. # else
  8005. # define UINT32_TYPE unsigned int
  8006. # endif
  8007. #endif
  8008. #ifndef UINT16_TYPE
  8009. # ifdef HAVE_UINT16_T
  8010. # define UINT16_TYPE uint16_t
  8011. # else
  8012. # define UINT16_TYPE unsigned short int
  8013. # endif
  8014. #endif
  8015. #ifndef INT16_TYPE
  8016. # ifdef HAVE_INT16_T
  8017. # define INT16_TYPE int16_t
  8018. # else
  8019. # define INT16_TYPE short int
  8020. # endif
  8021. #endif
  8022. #ifndef UINT8_TYPE
  8023. # ifdef HAVE_UINT8_T
  8024. # define UINT8_TYPE uint8_t
  8025. # else
  8026. # define UINT8_TYPE unsigned char
  8027. # endif
  8028. #endif
  8029. #ifndef INT8_TYPE
  8030. # ifdef HAVE_INT8_T
  8031. # define INT8_TYPE int8_t
  8032. # else
  8033. # define INT8_TYPE signed char
  8034. # endif
  8035. #endif
  8036. #ifndef LONGDOUBLE_TYPE
  8037. # define LONGDOUBLE_TYPE long double
  8038. #endif
  8039. typedef sqlite_int64 i64; /* 8-byte signed integer */
  8040. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  8041. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  8042. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  8043. typedef INT16_TYPE i16; /* 2-byte signed integer */
  8044. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  8045. typedef INT8_TYPE i8; /* 1-byte signed integer */
  8046. /*
  8047. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  8048. ** that can be stored in a u32 without loss of data. The value
  8049. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8050. ** have to specify the value in the less intuitive manner shown:
  8051. */
  8052. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8053. /*
  8054. ** The datatype used to store estimates of the number of rows in a
  8055. ** table or index. This is an unsigned integer type. For 99.9% of
  8056. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8057. ** can be used at compile-time if desired.
  8058. */
  8059. #ifdef SQLITE_64BIT_STATS
  8060. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8061. #else
  8062. typedef u32 tRowcnt; /* 32-bit is the default */
  8063. #endif
  8064. /*
  8065. ** Estimated quantities used for query planning are stored as 16-bit
  8066. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8067. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8068. ** But the allowed values are "grainy". Not every value is representable.
  8069. ** For example, quantities 16 and 17 are both represented by a LogEst
  8070. ** of 40. However, since LogEst quantatites are suppose to be estimates,
  8071. ** not exact values, this imprecision is not a problem.
  8072. **
  8073. ** "LogEst" is short for "Logarithimic Estimate".
  8074. **
  8075. ** Examples:
  8076. ** 1 -> 0 20 -> 43 10000 -> 132
  8077. ** 2 -> 10 25 -> 46 25000 -> 146
  8078. ** 3 -> 16 100 -> 66 1000000 -> 199
  8079. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8080. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8081. **
  8082. ** The LogEst can be negative to indicate fractional values.
  8083. ** Examples:
  8084. **
  8085. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8086. */
  8087. typedef INT16_TYPE LogEst;
  8088. /*
  8089. ** Macros to determine whether the machine is big or little endian,
  8090. ** evaluated at runtime.
  8091. */
  8092. #ifdef SQLITE_AMALGAMATION
  8093. SQLITE_PRIVATE const int sqlite3one = 1;
  8094. #else
  8095. SQLITE_PRIVATE const int sqlite3one;
  8096. #endif
  8097. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  8098. || defined(__x86_64) || defined(__x86_64__)
  8099. # define SQLITE_BIGENDIAN 0
  8100. # define SQLITE_LITTLEENDIAN 1
  8101. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8102. #else
  8103. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8104. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8105. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8106. #endif
  8107. /*
  8108. ** Constants for the largest and smallest possible 64-bit signed integers.
  8109. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8110. ** compilers.
  8111. */
  8112. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8113. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8114. /*
  8115. ** Round up a number to the next larger multiple of 8. This is used
  8116. ** to force 8-byte alignment on 64-bit architectures.
  8117. */
  8118. #define ROUND8(x) (((x)+7)&~7)
  8119. /*
  8120. ** Round down to the nearest multiple of 8
  8121. */
  8122. #define ROUNDDOWN8(x) ((x)&~7)
  8123. /*
  8124. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8125. ** macro is used only within assert() to verify that the code gets
  8126. ** all alignment restrictions correct.
  8127. **
  8128. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8129. ** underlying malloc() implemention might return us 4-byte aligned
  8130. ** pointers. In that case, only verify 4-byte alignment.
  8131. */
  8132. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8133. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8134. #else
  8135. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8136. #endif
  8137. /*
  8138. ** Disable MMAP on platforms where it is known to not work
  8139. */
  8140. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8141. # undef SQLITE_MAX_MMAP_SIZE
  8142. # define SQLITE_MAX_MMAP_SIZE 0
  8143. #endif
  8144. /*
  8145. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8146. */
  8147. #ifdef __APPLE__
  8148. # include <TargetConditionals.h>
  8149. # if TARGET_OS_IPHONE
  8150. # undef SQLITE_MAX_MMAP_SIZE
  8151. # define SQLITE_MAX_MMAP_SIZE 0
  8152. # endif
  8153. #endif
  8154. #ifndef SQLITE_MAX_MMAP_SIZE
  8155. # if defined(SQLITE_OS_RTTHREAD)
  8156. # define SQLITE_MAX_MMAP_SIZE 0
  8157. # elif defined(__linux__) \
  8158. || defined(_WIN32) \
  8159. || (defined(__APPLE__) && defined(__MACH__)) \
  8160. || defined(__sun)
  8161. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8162. # else
  8163. # define SQLITE_MAX_MMAP_SIZE 0
  8164. # endif
  8165. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8166. #endif
  8167. /*
  8168. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8169. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8170. ** not exceed the maximum mmap size.
  8171. */
  8172. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8173. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8174. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8175. #endif
  8176. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8177. # undef SQLITE_DEFAULT_MMAP_SIZE
  8178. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8179. #endif
  8180. /*
  8181. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8182. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8183. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8184. */
  8185. #ifdef SQLITE_ENABLE_STAT4
  8186. # undef SQLITE_ENABLE_STAT3
  8187. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8188. #elif SQLITE_ENABLE_STAT3
  8189. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8190. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8191. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8192. #endif
  8193. /*
  8194. ** An instance of the following structure is used to store the busy-handler
  8195. ** callback for a given sqlite handle.
  8196. **
  8197. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8198. ** callback for the database handle. Each pager opened via the sqlite
  8199. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8200. ** callback is currently invoked only from within pager.c.
  8201. */
  8202. typedef struct BusyHandler BusyHandler;
  8203. struct BusyHandler {
  8204. int (*xFunc)(void *,int); /* The busy callback */
  8205. void *pArg; /* First arg to busy callback */
  8206. int nBusy; /* Incremented with each busy call */
  8207. };
  8208. /*
  8209. ** Name of the master database table. The master database table
  8210. ** is a special table that holds the names and attributes of all
  8211. ** user tables and indices.
  8212. */
  8213. #define MASTER_NAME "sqlite_master"
  8214. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8215. /*
  8216. ** The root-page of the master database table.
  8217. */
  8218. #define MASTER_ROOT 1
  8219. /*
  8220. ** The name of the schema table.
  8221. */
  8222. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8223. /*
  8224. ** A convenience macro that returns the number of elements in
  8225. ** an array.
  8226. */
  8227. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8228. /*
  8229. ** Determine if the argument is a power of two
  8230. */
  8231. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8232. /*
  8233. ** The following value as a destructor means to use sqlite3DbFree().
  8234. ** The sqlite3DbFree() routine requires two parameters instead of the
  8235. ** one parameter that destructors normally want. So we have to introduce
  8236. ** this magic value that the code knows to handle differently. Any
  8237. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8238. ** and SQLITE_TRANSIENT.
  8239. */
  8240. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8241. /*
  8242. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8243. ** not support Writable Static Data (WSD) such as global and static variables.
  8244. ** All variables must either be on the stack or dynamically allocated from
  8245. ** the heap. When WSD is unsupported, the variable declarations scattered
  8246. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8247. ** macro is used for this purpose. And instead of referencing the variable
  8248. ** directly, we use its constant as a key to lookup the run-time allocated
  8249. ** buffer that holds real variable. The constant is also the initializer
  8250. ** for the run-time allocated buffer.
  8251. **
  8252. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8253. ** macros become no-ops and have zero performance impact.
  8254. */
  8255. #ifdef SQLITE_OMIT_WSD
  8256. #define SQLITE_WSD const
  8257. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8258. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8259. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8260. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8261. #else
  8262. #define SQLITE_WSD
  8263. #define GLOBAL(t,v) v
  8264. #define sqlite3GlobalConfig sqlite3Config
  8265. #endif
  8266. /*
  8267. ** The following macros are used to suppress compiler warnings and to
  8268. ** make it clear to human readers when a function parameter is deliberately
  8269. ** left unused within the body of a function. This usually happens when
  8270. ** a function is called via a function pointer. For example the
  8271. ** implementation of an SQL aggregate step callback may not use the
  8272. ** parameter indicating the number of arguments passed to the aggregate,
  8273. ** if it knows that this is enforced elsewhere.
  8274. **
  8275. ** When a function parameter is not used at all within the body of a function,
  8276. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8277. ** However, these macros may also be used to suppress warnings related to
  8278. ** parameters that may or may not be used depending on compilation options.
  8279. ** For example those parameters only used in assert() statements. In these
  8280. ** cases the parameters are named as per the usual conventions.
  8281. */
  8282. #define UNUSED_PARAMETER(x) (void)(x)
  8283. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8284. /*
  8285. ** Forward references to structures
  8286. */
  8287. typedef struct AggInfo AggInfo;
  8288. typedef struct AuthContext AuthContext;
  8289. typedef struct AutoincInfo AutoincInfo;
  8290. typedef struct Bitvec Bitvec;
  8291. typedef struct CollSeq CollSeq;
  8292. typedef struct Column Column;
  8293. typedef struct Db Db;
  8294. typedef struct Schema Schema;
  8295. typedef struct Expr Expr;
  8296. typedef struct ExprList ExprList;
  8297. typedef struct ExprSpan ExprSpan;
  8298. typedef struct FKey FKey;
  8299. typedef struct FuncDestructor FuncDestructor;
  8300. typedef struct FuncDef FuncDef;
  8301. typedef struct FuncDefHash FuncDefHash;
  8302. typedef struct IdList IdList;
  8303. typedef struct Index Index;
  8304. typedef struct IndexSample IndexSample;
  8305. typedef struct KeyClass KeyClass;
  8306. typedef struct KeyInfo KeyInfo;
  8307. typedef struct Lookaside Lookaside;
  8308. typedef struct LookasideSlot LookasideSlot;
  8309. typedef struct Module Module;
  8310. typedef struct NameContext NameContext;
  8311. typedef struct Parse Parse;
  8312. typedef struct RowSet RowSet;
  8313. typedef struct Savepoint Savepoint;
  8314. typedef struct Select Select;
  8315. typedef struct SelectDest SelectDest;
  8316. typedef struct SrcList SrcList;
  8317. typedef struct StrAccum StrAccum;
  8318. typedef struct Table Table;
  8319. typedef struct TableLock TableLock;
  8320. typedef struct Token Token;
  8321. typedef struct Trigger Trigger;
  8322. typedef struct TriggerPrg TriggerPrg;
  8323. typedef struct TriggerStep TriggerStep;
  8324. typedef struct UnpackedRecord UnpackedRecord;
  8325. typedef struct VTable VTable;
  8326. typedef struct VtabCtx VtabCtx;
  8327. typedef struct Walker Walker;
  8328. typedef struct WhereInfo WhereInfo;
  8329. /*
  8330. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8331. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8332. ** pointer types (i.e. FuncDef) defined above.
  8333. */
  8334. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8335. /************** Begin file btree.h *******************************************/
  8336. /*
  8337. ** 2001 September 15
  8338. **
  8339. ** The author disclaims copyright to this source code. In place of
  8340. ** a legal notice, here is a blessing:
  8341. **
  8342. ** May you do good and not evil.
  8343. ** May you find forgiveness for yourself and forgive others.
  8344. ** May you share freely, never taking more than you give.
  8345. **
  8346. *************************************************************************
  8347. ** This header file defines the interface that the sqlite B-Tree file
  8348. ** subsystem. See comments in the source code for a detailed description
  8349. ** of what each interface routine does.
  8350. */
  8351. #ifndef _BTREE_H_
  8352. #define _BTREE_H_
  8353. /* TODO: This definition is just included so other modules compile. It
  8354. ** needs to be revisited.
  8355. */
  8356. #define SQLITE_N_BTREE_META 10
  8357. /*
  8358. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8359. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8360. */
  8361. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8362. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8363. #endif
  8364. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8365. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8366. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8367. /*
  8368. ** Forward declarations of structure
  8369. */
  8370. typedef struct Btree Btree;
  8371. typedef struct BtCursor BtCursor;
  8372. typedef struct BtShared BtShared;
  8373. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8374. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8375. const char *zFilename, /* Name of database file to open */
  8376. sqlite3 *db, /* Associated database connection */
  8377. Btree **ppBtree, /* Return open Btree* here */
  8378. int flags, /* Flags */
  8379. int vfsFlags /* Flags passed through to VFS open */
  8380. );
  8381. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8382. ** following values.
  8383. **
  8384. ** NOTE: These values must match the corresponding PAGER_ values in
  8385. ** pager.h.
  8386. */
  8387. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8388. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8389. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8390. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8391. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8392. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8393. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8394. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8395. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8396. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8397. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8398. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8399. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8400. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8401. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8402. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8403. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8404. #endif
  8405. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8406. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8407. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8408. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8409. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8410. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8411. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8412. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8413. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8414. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8415. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8416. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8417. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8418. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8419. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8420. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8421. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8422. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8423. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8424. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8425. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8426. ** of the flags shown below.
  8427. **
  8428. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8429. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8430. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8431. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8432. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8433. ** indices.)
  8434. */
  8435. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8436. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8437. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8438. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8439. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8440. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8441. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8442. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8443. /*
  8444. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8445. ** should be one of the following values. The integer values are assigned
  8446. ** to constants so that the offset of the corresponding field in an
  8447. ** SQLite database header may be found using the following formula:
  8448. **
  8449. ** offset = 36 + (idx * 4)
  8450. **
  8451. ** For example, the free-page-count field is located at byte offset 36 of
  8452. ** the database file header. The incr-vacuum-flag field is located at
  8453. ** byte offset 64 (== 36+4*7).
  8454. */
  8455. #define BTREE_FREE_PAGE_COUNT 0
  8456. #define BTREE_SCHEMA_VERSION 1
  8457. #define BTREE_FILE_FORMAT 2
  8458. #define BTREE_DEFAULT_CACHE_SIZE 3
  8459. #define BTREE_LARGEST_ROOT_PAGE 4
  8460. #define BTREE_TEXT_ENCODING 5
  8461. #define BTREE_USER_VERSION 6
  8462. #define BTREE_INCR_VACUUM 7
  8463. #define BTREE_APPLICATION_ID 8
  8464. /*
  8465. ** Values that may be OR'd together to form the second argument of an
  8466. ** sqlite3BtreeCursorHints() call.
  8467. */
  8468. #define BTREE_BULKLOAD 0x00000001
  8469. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8470. Btree*, /* BTree containing table to open */
  8471. int iTable, /* Index of root page */
  8472. int wrFlag, /* 1 for writing. 0 for read-only */
  8473. struct KeyInfo*, /* First argument to compare function */
  8474. BtCursor *pCursor /* Space to write cursor structure */
  8475. );
  8476. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8477. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8478. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8479. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8480. BtCursor*,
  8481. UnpackedRecord *pUnKey,
  8482. i64 intKey,
  8483. int bias,
  8484. int *pRes
  8485. );
  8486. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8487. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8488. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8489. const void *pData, int nData,
  8490. int nZero, int bias, int seekResult);
  8491. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8492. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8493. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8494. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8495. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8496. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8497. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8498. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8499. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8500. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8501. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8502. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8503. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8504. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8505. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8506. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8507. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8508. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8509. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8510. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8511. #ifndef NDEBUG
  8512. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8513. #endif
  8514. #ifndef SQLITE_OMIT_BTREECOUNT
  8515. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8516. #endif
  8517. #ifdef SQLITE_TEST
  8518. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8519. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8520. #endif
  8521. #ifndef SQLITE_OMIT_WAL
  8522. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8523. #endif
  8524. /*
  8525. ** If we are not using shared cache, then there is no need to
  8526. ** use mutexes to access the BtShared structures. So make the
  8527. ** Enter and Leave procedures no-ops.
  8528. */
  8529. #ifndef SQLITE_OMIT_SHARED_CACHE
  8530. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8531. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8532. #else
  8533. # define sqlite3BtreeEnter(X)
  8534. # define sqlite3BtreeEnterAll(X)
  8535. #endif
  8536. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8537. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8538. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8539. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8540. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8541. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8542. #ifndef NDEBUG
  8543. /* These routines are used inside assert() statements only. */
  8544. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8545. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8546. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8547. #endif
  8548. #else
  8549. # define sqlite3BtreeSharable(X) 0
  8550. # define sqlite3BtreeLeave(X)
  8551. # define sqlite3BtreeEnterCursor(X)
  8552. # define sqlite3BtreeLeaveCursor(X)
  8553. # define sqlite3BtreeLeaveAll(X)
  8554. # define sqlite3BtreeHoldsMutex(X) 1
  8555. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8556. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8557. #endif
  8558. #endif /* _BTREE_H_ */
  8559. /************** End of btree.h ***********************************************/
  8560. /************** Continuing where we left off in sqliteInt.h ******************/
  8561. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8562. /************** Begin file vdbe.h ********************************************/
  8563. /*
  8564. ** 2001 September 15
  8565. **
  8566. ** The author disclaims copyright to this source code. In place of
  8567. ** a legal notice, here is a blessing:
  8568. **
  8569. ** May you do good and not evil.
  8570. ** May you find forgiveness for yourself and forgive others.
  8571. ** May you share freely, never taking more than you give.
  8572. **
  8573. *************************************************************************
  8574. ** Header file for the Virtual DataBase Engine (VDBE)
  8575. **
  8576. ** This header defines the interface to the virtual database engine
  8577. ** or VDBE. The VDBE implements an abstract machine that runs a
  8578. ** simple program to access and modify the underlying database.
  8579. */
  8580. #ifndef _SQLITE_VDBE_H_
  8581. #define _SQLITE_VDBE_H_
  8582. /* #include <stdio.h> */
  8583. /*
  8584. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8585. ** in the source file sqliteVdbe.c are allowed to see the insides
  8586. ** of this structure.
  8587. */
  8588. typedef struct Vdbe Vdbe;
  8589. /*
  8590. ** The names of the following types declared in vdbeInt.h are required
  8591. ** for the VdbeOp definition.
  8592. */
  8593. typedef struct Mem Mem;
  8594. typedef struct SubProgram SubProgram;
  8595. /*
  8596. ** A single instruction of the virtual machine has an opcode
  8597. ** and as many as three operands. The instruction is recorded
  8598. ** as an instance of the following structure:
  8599. */
  8600. struct VdbeOp {
  8601. u8 opcode; /* What operation to perform */
  8602. signed char p4type; /* One of the P4_xxx constants for p4 */
  8603. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8604. u8 p5; /* Fifth parameter is an unsigned character */
  8605. int p1; /* First operand */
  8606. int p2; /* Second parameter (often the jump destination) */
  8607. int p3; /* The third parameter */
  8608. union { /* fourth parameter */
  8609. int i; /* Integer value if p4type==P4_INT32 */
  8610. void *p; /* Generic pointer */
  8611. char *z; /* Pointer to data for string (char array) types */
  8612. i64 *pI64; /* Used when p4type is P4_INT64 */
  8613. double *pReal; /* Used when p4type is P4_REAL */
  8614. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8615. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8616. Mem *pMem; /* Used when p4type is P4_MEM */
  8617. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8618. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8619. int *ai; /* Used when p4type is P4_INTARRAY */
  8620. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8621. int (*xAdvance)(BtCursor *, int *);
  8622. } p4;
  8623. #ifdef SQLITE_DEBUG
  8624. char *zComment; /* Comment to improve readability */
  8625. #endif
  8626. #ifdef VDBE_PROFILE
  8627. int cnt; /* Number of times this instruction was executed */
  8628. u64 cycles; /* Total time spent executing this instruction */
  8629. #endif
  8630. };
  8631. typedef struct VdbeOp VdbeOp;
  8632. /*
  8633. ** A sub-routine used to implement a trigger program.
  8634. */
  8635. struct SubProgram {
  8636. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8637. int nOp; /* Elements in aOp[] */
  8638. int nMem; /* Number of memory cells required */
  8639. int nCsr; /* Number of cursors required */
  8640. int nOnce; /* Number of OP_Once instructions */
  8641. void *token; /* id that may be used to recursive triggers */
  8642. SubProgram *pNext; /* Next sub-program already visited */
  8643. };
  8644. /*
  8645. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8646. ** it takes up less space.
  8647. */
  8648. struct VdbeOpList {
  8649. u8 opcode; /* What operation to perform */
  8650. signed char p1; /* First operand */
  8651. signed char p2; /* Second parameter (often the jump destination) */
  8652. signed char p3; /* Third parameter */
  8653. };
  8654. typedef struct VdbeOpList VdbeOpList;
  8655. /*
  8656. ** Allowed values of VdbeOp.p4type
  8657. */
  8658. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8659. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8660. #define P4_STATIC (-2) /* Pointer to a static string */
  8661. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8662. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8663. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8664. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8665. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8666. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8667. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8668. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8669. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8670. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8671. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8672. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8673. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8674. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8675. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8676. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8677. ** gets freed when the Vdbe is finalized so it still should be obtained
  8678. ** from a single sqliteMalloc(). But no copy is made and the calling
  8679. ** function should *not* try to free the KeyInfo.
  8680. */
  8681. #define P4_KEYINFO_HANDOFF (-16)
  8682. #define P4_KEYINFO_STATIC (-17)
  8683. /*
  8684. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8685. ** number of columns of data returned by the statement.
  8686. */
  8687. #define COLNAME_NAME 0
  8688. #define COLNAME_DECLTYPE 1
  8689. #define COLNAME_DATABASE 2
  8690. #define COLNAME_TABLE 3
  8691. #define COLNAME_COLUMN 4
  8692. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8693. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8694. #else
  8695. # ifdef SQLITE_OMIT_DECLTYPE
  8696. # define COLNAME_N 1 /* Store only the name */
  8697. # else
  8698. # define COLNAME_N 2 /* Store the name and decltype */
  8699. # endif
  8700. #endif
  8701. /*
  8702. ** The following macro converts a relative address in the p2 field
  8703. ** of a VdbeOp structure into a negative number so that
  8704. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8705. ** the macro again restores the address.
  8706. */
  8707. #define ADDR(X) (-1-(X))
  8708. /*
  8709. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8710. ** header file that defines a number for each opcode used by the VDBE.
  8711. */
  8712. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8713. /************** Begin file opcodes.h *****************************************/
  8714. /* Automatically generated. Do not edit */
  8715. /* See the mkopcodeh.awk script for details */
  8716. #define OP_Function 1
  8717. #define OP_Savepoint 2
  8718. #define OP_AutoCommit 3
  8719. #define OP_Transaction 4
  8720. #define OP_SorterNext 5
  8721. #define OP_Prev 6
  8722. #define OP_Next 7
  8723. #define OP_AggStep 8
  8724. #define OP_Checkpoint 9
  8725. #define OP_JournalMode 10
  8726. #define OP_Vacuum 11
  8727. #define OP_VFilter 12
  8728. #define OP_VUpdate 13
  8729. #define OP_Goto 14
  8730. #define OP_Gosub 15
  8731. #define OP_Return 16
  8732. #define OP_Yield 17
  8733. #define OP_HaltIfNull 18
  8734. #define OP_Not 19 /* same as TK_NOT */
  8735. #define OP_Halt 20
  8736. #define OP_Integer 21
  8737. #define OP_Int64 22
  8738. #define OP_String 23
  8739. #define OP_Null 24
  8740. #define OP_Blob 25
  8741. #define OP_Variable 26
  8742. #define OP_Move 27
  8743. #define OP_Copy 28
  8744. #define OP_SCopy 29
  8745. #define OP_ResultRow 30
  8746. #define OP_CollSeq 31
  8747. #define OP_AddImm 32
  8748. #define OP_MustBeInt 33
  8749. #define OP_RealAffinity 34
  8750. #define OP_Permutation 35
  8751. #define OP_Compare 36
  8752. #define OP_Jump 37
  8753. #define OP_Once 38
  8754. #define OP_If 39
  8755. #define OP_IfNot 40
  8756. #define OP_Column 41
  8757. #define OP_Affinity 42
  8758. #define OP_MakeRecord 43
  8759. #define OP_Count 44
  8760. #define OP_ReadCookie 45
  8761. #define OP_SetCookie 46
  8762. #define OP_VerifyCookie 47
  8763. #define OP_OpenRead 48
  8764. #define OP_OpenWrite 49
  8765. #define OP_OpenAutoindex 50
  8766. #define OP_OpenEphemeral 51
  8767. #define OP_SorterOpen 52
  8768. #define OP_OpenPseudo 53
  8769. #define OP_Close 54
  8770. #define OP_SeekLt 55
  8771. #define OP_SeekLe 56
  8772. #define OP_SeekGe 57
  8773. #define OP_SeekGt 58
  8774. #define OP_Seek 59
  8775. #define OP_NotFound 60
  8776. #define OP_Found 61
  8777. #define OP_IsUnique 62
  8778. #define OP_NotExists 63
  8779. #define OP_Sequence 64
  8780. #define OP_NewRowid 65
  8781. #define OP_Insert 66
  8782. #define OP_InsertInt 67
  8783. #define OP_Or 68 /* same as TK_OR */
  8784. #define OP_And 69 /* same as TK_AND */
  8785. #define OP_Delete 70
  8786. #define OP_ResetCount 71
  8787. #define OP_SorterCompare 72
  8788. #define OP_IsNull 73 /* same as TK_ISNULL */
  8789. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8790. #define OP_Ne 75 /* same as TK_NE */
  8791. #define OP_Eq 76 /* same as TK_EQ */
  8792. #define OP_Gt 77 /* same as TK_GT */
  8793. #define OP_Le 78 /* same as TK_LE */
  8794. #define OP_Lt 79 /* same as TK_LT */
  8795. #define OP_Ge 80 /* same as TK_GE */
  8796. #define OP_SorterData 81
  8797. #define OP_BitAnd 82 /* same as TK_BITAND */
  8798. #define OP_BitOr 83 /* same as TK_BITOR */
  8799. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8800. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8801. #define OP_Add 86 /* same as TK_PLUS */
  8802. #define OP_Subtract 87 /* same as TK_MINUS */
  8803. #define OP_Multiply 88 /* same as TK_STAR */
  8804. #define OP_Divide 89 /* same as TK_SLASH */
  8805. #define OP_Remainder 90 /* same as TK_REM */
  8806. #define OP_Concat 91 /* same as TK_CONCAT */
  8807. #define OP_RowKey 92
  8808. #define OP_BitNot 93 /* same as TK_BITNOT */
  8809. #define OP_String8 94 /* same as TK_STRING */
  8810. #define OP_RowData 95
  8811. #define OP_Rowid 96
  8812. #define OP_NullRow 97
  8813. #define OP_Last 98
  8814. #define OP_SorterSort 99
  8815. #define OP_Sort 100
  8816. #define OP_Rewind 101
  8817. #define OP_SorterInsert 102
  8818. #define OP_IdxInsert 103
  8819. #define OP_IdxDelete 104
  8820. #define OP_IdxRowid 105
  8821. #define OP_IdxLT 106
  8822. #define OP_IdxGE 107
  8823. #define OP_Destroy 108
  8824. #define OP_Clear 109
  8825. #define OP_CreateIndex 110
  8826. #define OP_CreateTable 111
  8827. #define OP_ParseSchema 112
  8828. #define OP_LoadAnalysis 113
  8829. #define OP_DropTable 114
  8830. #define OP_DropIndex 115
  8831. #define OP_DropTrigger 116
  8832. #define OP_IntegrityCk 117
  8833. #define OP_RowSetAdd 118
  8834. #define OP_RowSetRead 119
  8835. #define OP_RowSetTest 120
  8836. #define OP_Program 121
  8837. #define OP_Param 122
  8838. #define OP_FkCounter 123
  8839. #define OP_FkIfZero 124
  8840. #define OP_MemMax 125
  8841. #define OP_IfPos 126
  8842. #define OP_IfNeg 127
  8843. #define OP_IfZero 128
  8844. #define OP_AggFinal 129
  8845. #define OP_Real 130 /* same as TK_FLOAT */
  8846. #define OP_IncrVacuum 131
  8847. #define OP_Expire 132
  8848. #define OP_TableLock 133
  8849. #define OP_VBegin 134
  8850. #define OP_VCreate 135
  8851. #define OP_VDestroy 136
  8852. #define OP_VOpen 137
  8853. #define OP_VColumn 138
  8854. #define OP_VNext 139
  8855. #define OP_VRename 140
  8856. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8857. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8858. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8859. #define OP_ToInt 144 /* same as TK_TO_INT */
  8860. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8861. #define OP_Pagecount 146
  8862. #define OP_MaxPgcnt 147
  8863. #define OP_Trace 148
  8864. #define OP_Noop 149
  8865. #define OP_Explain 150
  8866. /* Properties such as "out2" or "jump" that are specified in
  8867. ** comments following the "case" for each opcode in the vdbe.c
  8868. ** are encoded into bitvectors as follows:
  8869. */
  8870. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8871. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8872. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8873. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8874. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8875. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8876. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8877. #define OPFLG_INITIALIZER {\
  8878. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  8879. /* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\
  8880. /* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\
  8881. /* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\
  8882. /* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\
  8883. /* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\
  8884. /* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\
  8885. /* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\
  8886. /* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\
  8887. /* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8888. /* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8889. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\
  8890. /* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\
  8891. /* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\
  8892. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
  8893. /* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\
  8894. /* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\
  8895. /* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\
  8896. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8897. /************** End of opcodes.h *********************************************/
  8898. /************** Continuing where we left off in vdbe.h ***********************/
  8899. /*
  8900. ** Prototypes for the VDBE interface. See comments on the implementation
  8901. ** for a description of what each of these routines does.
  8902. */
  8903. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8904. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8905. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8906. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8907. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8908. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8909. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8910. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8911. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8912. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8913. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8914. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8915. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8916. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8917. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8918. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8919. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8920. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8921. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8922. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8923. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8924. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8925. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8926. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8927. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8928. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8929. #ifdef SQLITE_DEBUG
  8930. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8931. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8932. #endif
  8933. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8934. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8935. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8936. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8937. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8938. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8939. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8940. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8941. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8942. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8943. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  8944. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8945. #ifndef SQLITE_OMIT_TRACE
  8946. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8947. #endif
  8948. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8949. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8950. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8951. #ifndef SQLITE_OMIT_TRIGGER
  8952. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8953. #endif
  8954. #ifndef NDEBUG
  8955. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8956. # define VdbeComment(X) sqlite3VdbeComment X
  8957. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8958. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8959. #else
  8960. # define VdbeComment(X)
  8961. # define VdbeNoopComment(X)
  8962. #endif
  8963. #endif
  8964. /************** End of vdbe.h ************************************************/
  8965. /************** Continuing where we left off in sqliteInt.h ******************/
  8966. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8967. /************** Begin file pager.h *******************************************/
  8968. /*
  8969. ** 2001 September 15
  8970. **
  8971. ** The author disclaims copyright to this source code. In place of
  8972. ** a legal notice, here is a blessing:
  8973. **
  8974. ** May you do good and not evil.
  8975. ** May you find forgiveness for yourself and forgive others.
  8976. ** May you share freely, never taking more than you give.
  8977. **
  8978. *************************************************************************
  8979. ** This header file defines the interface that the sqlite page cache
  8980. ** subsystem. The page cache subsystem reads and writes a file a page
  8981. ** at a time and provides a journal for rollback.
  8982. */
  8983. #ifndef _PAGER_H_
  8984. #define _PAGER_H_
  8985. /*
  8986. ** Default maximum size for persistent journal files. A negative
  8987. ** value means no limit. This value may be overridden using the
  8988. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8989. */
  8990. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8991. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8992. #endif
  8993. /*
  8994. ** The type used to represent a page number. The first page in a file
  8995. ** is called page 1. 0 is used to represent "not a page".
  8996. */
  8997. typedef u32 Pgno;
  8998. /*
  8999. ** Each open file is managed by a separate instance of the "Pager" structure.
  9000. */
  9001. typedef struct Pager Pager;
  9002. /*
  9003. ** Handle type for pages.
  9004. */
  9005. typedef struct PgHdr DbPage;
  9006. /*
  9007. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  9008. ** reserved for working around a windows/posix incompatibility). It is
  9009. ** used in the journal to signify that the remainder of the journal file
  9010. ** is devoted to storing a master journal name - there are no more pages to
  9011. ** roll back. See comments for function writeMasterJournal() in pager.c
  9012. ** for details.
  9013. */
  9014. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  9015. /*
  9016. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  9017. **
  9018. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  9019. */
  9020. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  9021. #define PAGER_MEMORY 0x0002 /* In-memory database */
  9022. /*
  9023. ** Valid values for the second argument to sqlite3PagerLockingMode().
  9024. */
  9025. #define PAGER_LOCKINGMODE_QUERY -1
  9026. #define PAGER_LOCKINGMODE_NORMAL 0
  9027. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  9028. /*
  9029. ** Numeric constants that encode the journalmode.
  9030. */
  9031. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  9032. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  9033. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  9034. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  9035. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  9036. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  9037. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  9038. /*
  9039. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  9040. */
  9041. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  9042. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  9043. /*
  9044. ** Flags for sqlite3PagerSetFlags()
  9045. */
  9046. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  9047. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  9048. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  9049. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9050. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9051. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9052. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9053. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9054. /*
  9055. ** The remainder of this file contains the declarations of the functions
  9056. ** that make up the Pager sub-system API. See source code comments for
  9057. ** a detailed description of each routine.
  9058. */
  9059. /* Open and close a Pager connection. */
  9060. SQLITE_PRIVATE int sqlite3PagerOpen(
  9061. sqlite3_vfs*,
  9062. Pager **ppPager,
  9063. const char*,
  9064. int,
  9065. int,
  9066. int,
  9067. void(*)(DbPage*)
  9068. );
  9069. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9070. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9071. /* Functions used to configure a Pager object. */
  9072. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9073. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9074. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9075. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9076. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9077. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9078. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9079. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9080. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9081. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9082. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9083. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9084. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9085. /* Functions used to obtain and release page references. */
  9086. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9087. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9088. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9089. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9090. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9091. /* Operations on page references. */
  9092. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9093. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9094. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9095. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9096. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9097. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9098. /* Functions used to manage pager transactions and savepoints. */
  9099. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9100. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9101. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9102. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9103. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  9104. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9105. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9106. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9107. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9108. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9109. #ifndef SQLITE_OMIT_WAL
  9110. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9111. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9112. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9113. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9114. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9115. #endif
  9116. #ifdef SQLITE_ENABLE_ZIPVFS
  9117. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9118. #endif
  9119. /* Functions used to query pager state and configuration. */
  9120. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9121. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9122. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9123. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9124. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9125. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9126. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9127. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9128. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9129. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9130. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9131. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9132. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9133. /* Functions used to truncate the database file. */
  9134. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9135. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9136. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9137. #endif
  9138. /* Functions to support testing and debugging. */
  9139. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9140. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9141. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9142. #endif
  9143. #ifdef SQLITE_TEST
  9144. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9145. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9146. void disable_simulated_io_errors(void);
  9147. void enable_simulated_io_errors(void);
  9148. #else
  9149. # define disable_simulated_io_errors()
  9150. # define enable_simulated_io_errors()
  9151. #endif
  9152. #endif /* _PAGER_H_ */
  9153. /************** End of pager.h ***********************************************/
  9154. /************** Continuing where we left off in sqliteInt.h ******************/
  9155. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9156. /************** Begin file pcache.h ******************************************/
  9157. /*
  9158. ** 2008 August 05
  9159. **
  9160. ** The author disclaims copyright to this source code. In place of
  9161. ** a legal notice, here is a blessing:
  9162. **
  9163. ** May you do good and not evil.
  9164. ** May you find forgiveness for yourself and forgive others.
  9165. ** May you share freely, never taking more than you give.
  9166. **
  9167. *************************************************************************
  9168. ** This header file defines the interface that the sqlite page cache
  9169. ** subsystem.
  9170. */
  9171. #ifndef _PCACHE_H_
  9172. typedef struct PgHdr PgHdr;
  9173. typedef struct PCache PCache;
  9174. /*
  9175. ** Every page in the cache is controlled by an instance of the following
  9176. ** structure.
  9177. */
  9178. struct PgHdr {
  9179. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9180. void *pData; /* Page data */
  9181. void *pExtra; /* Extra content */
  9182. PgHdr *pDirty; /* Transient list of dirty pages */
  9183. Pager *pPager; /* The pager this page is part of */
  9184. Pgno pgno; /* Page number for this page */
  9185. #ifdef SQLITE_CHECK_PAGES
  9186. u32 pageHash; /* Hash of page content */
  9187. #endif
  9188. u16 flags; /* PGHDR flags defined below */
  9189. /**********************************************************************
  9190. ** Elements above are public. All that follows is private to pcache.c
  9191. ** and should not be accessed by other modules.
  9192. */
  9193. i16 nRef; /* Number of users of this page */
  9194. PCache *pCache; /* Cache that owns this page */
  9195. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9196. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9197. };
  9198. /* Bit values for PgHdr.flags */
  9199. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9200. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9201. ** writing this page to the database */
  9202. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9203. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9204. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9205. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9206. /* Initialize and shutdown the page cache subsystem */
  9207. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9208. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9209. /* Page cache buffer management:
  9210. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9211. */
  9212. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9213. /* Create a new pager cache.
  9214. ** Under memory stress, invoke xStress to try to make pages clean.
  9215. ** Only clean and unpinned pages can be reclaimed.
  9216. */
  9217. SQLITE_PRIVATE void sqlite3PcacheOpen(
  9218. int szPage, /* Size of every page */
  9219. int szExtra, /* Extra space associated with each page */
  9220. int bPurgeable, /* True if pages are on backing store */
  9221. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9222. void *pStress, /* Argument to xStress */
  9223. PCache *pToInit /* Preallocated space for the PCache */
  9224. );
  9225. /* Modify the page-size after the cache has been created. */
  9226. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  9227. /* Return the size in bytes of a PCache object. Used to preallocate
  9228. ** storage space.
  9229. */
  9230. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9231. /* One release per successful fetch. Page is pinned until released.
  9232. ** Reference counted.
  9233. */
  9234. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  9235. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9236. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9237. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9238. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9239. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9240. /* Change a page number. Used by incr-vacuum. */
  9241. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9242. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9243. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9244. /* Get a list of all dirty pages in the cache, sorted by page number */
  9245. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9246. /* Reset and close the cache object */
  9247. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9248. /* Clear flags from pages of the page cache */
  9249. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9250. /* Discard the contents of the cache */
  9251. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9252. /* Return the total number of outstanding page references */
  9253. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9254. /* Increment the reference count of an existing page */
  9255. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9256. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9257. /* Return the total number of pages stored in the cache */
  9258. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9259. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9260. /* Iterate through all dirty pages currently stored in the cache. This
  9261. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9262. ** library is built.
  9263. */
  9264. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9265. #endif
  9266. /* Set and get the suggested cache-size for the specified pager-cache.
  9267. **
  9268. ** If no global maximum is configured, then the system attempts to limit
  9269. ** the total number of pages cached by purgeable pager-caches to the sum
  9270. ** of the suggested cache-sizes.
  9271. */
  9272. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9273. #ifdef SQLITE_TEST
  9274. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9275. #endif
  9276. /* Free up as much memory as possible from the page cache */
  9277. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9278. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9279. /* Try to return memory used by the pcache module to the main memory heap */
  9280. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9281. #endif
  9282. #ifdef SQLITE_TEST
  9283. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9284. #endif
  9285. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9286. #endif /* _PCACHE_H_ */
  9287. /************** End of pcache.h **********************************************/
  9288. /************** Continuing where we left off in sqliteInt.h ******************/
  9289. /************** Include os.h in the middle of sqliteInt.h ********************/
  9290. /************** Begin file os.h **********************************************/
  9291. /*
  9292. ** 2001 September 16
  9293. **
  9294. ** The author disclaims copyright to this source code. In place of
  9295. ** a legal notice, here is a blessing:
  9296. **
  9297. ** May you do good and not evil.
  9298. ** May you find forgiveness for yourself and forgive others.
  9299. ** May you share freely, never taking more than you give.
  9300. **
  9301. ******************************************************************************
  9302. **
  9303. ** This header file (together with is companion C source-code file
  9304. ** "os.c") attempt to abstract the underlying operating system so that
  9305. ** the SQLite library will work on both POSIX and windows systems.
  9306. **
  9307. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9308. ** being included by every source file.
  9309. */
  9310. #ifndef _SQLITE_OS_H_
  9311. #define _SQLITE_OS_H_
  9312. /*
  9313. ** Figure out if we are dealing with Unix, Windows, or some other
  9314. ** operating system. After the following block of preprocess macros,
  9315. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9316. ** will defined to either 1 or 0. One of the four will be 1. The other
  9317. ** three will be 0.
  9318. */
  9319. #if defined(SQLITE_OS_OTHER)
  9320. # if SQLITE_OS_OTHER==1
  9321. # undef SQLITE_OS_UNIX
  9322. # define SQLITE_OS_UNIX 0
  9323. # undef SQLITE_OS_WIN
  9324. # define SQLITE_OS_WIN 0
  9325. # undef SQLITE_OS_RTTHREAD
  9326. # define SQLITE_OS_RTTHREAD 1
  9327. # else
  9328. # undef SQLITE_OS_OTHER
  9329. # endif
  9330. #endif
  9331. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9332. # define SQLITE_OS_OTHER 0
  9333. # ifndef SQLITE_OS_WIN
  9334. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9335. # define SQLITE_OS_WIN 1
  9336. # define SQLITE_OS_UNIX 0
  9337. # else
  9338. # define SQLITE_OS_WIN 0
  9339. # define SQLITE_OS_UNIX 1
  9340. # endif
  9341. # else
  9342. # define SQLITE_OS_UNIX 0
  9343. # endif
  9344. #else
  9345. # ifndef SQLITE_OS_WIN
  9346. # define SQLITE_OS_WIN 0
  9347. # endif
  9348. #endif
  9349. #if SQLITE_OS_WIN
  9350. # include <windows.h>
  9351. #endif
  9352. /*
  9353. ** Determine if we are dealing with Windows NT.
  9354. **
  9355. ** We ought to be able to determine if we are compiling for win98 or winNT
  9356. ** using the _WIN32_WINNT macro as follows:
  9357. **
  9358. ** #if defined(_WIN32_WINNT)
  9359. ** # define SQLITE_OS_WINNT 1
  9360. ** #else
  9361. ** # define SQLITE_OS_WINNT 0
  9362. ** #endif
  9363. **
  9364. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9365. ** so the above test does not work. We'll just assume that everything is
  9366. ** winNT unless the programmer explicitly says otherwise by setting
  9367. ** SQLITE_OS_WINNT to 0.
  9368. */
  9369. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9370. # define SQLITE_OS_WINNT 1
  9371. #endif
  9372. /*
  9373. ** Determine if we are dealing with WindowsCE - which has a much
  9374. ** reduced API.
  9375. */
  9376. #if defined(_WIN32_WCE)
  9377. # define SQLITE_OS_WINCE 1
  9378. #else
  9379. # define SQLITE_OS_WINCE 0
  9380. #endif
  9381. /*
  9382. ** Determine if we are dealing with WinRT, which provides only a subset of
  9383. ** the full Win32 API.
  9384. */
  9385. #if !defined(SQLITE_OS_WINRT)
  9386. # define SQLITE_OS_WINRT 0
  9387. #endif
  9388. /* If the SET_FULLSYNC macro is not defined above, then make it
  9389. ** a no-op
  9390. */
  9391. #ifndef SET_FULLSYNC
  9392. # define SET_FULLSYNC(x,y)
  9393. #endif
  9394. /*
  9395. ** The default size of a disk sector
  9396. */
  9397. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9398. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9399. #endif
  9400. /*
  9401. ** Temporary files are named starting with this prefix followed by 16 random
  9402. ** alphanumeric characters, and no file extension. They are stored in the
  9403. ** OS's standard temporary file directory, and are deleted prior to exit.
  9404. ** If sqlite is being embedded in another program, you may wish to change the
  9405. ** prefix to reflect your program's name, so that if your program exits
  9406. ** prematurely, old temporary files can be easily identified. This can be done
  9407. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9408. **
  9409. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9410. ** Mcafee started using SQLite in their anti-virus product and it
  9411. ** started putting files with the "sqlite" name in the c:/temp folder.
  9412. ** This annoyed many windows users. Those users would then do a
  9413. ** Google search for "sqlite", find the telephone numbers of the
  9414. ** developers and call to wake them up at night and complain.
  9415. ** For this reason, the default name prefix is changed to be "sqlite"
  9416. ** spelled backwards. So the temp files are still identified, but
  9417. ** anybody smart enough to figure out the code is also likely smart
  9418. ** enough to know that calling the developer will not help get rid
  9419. ** of the file.
  9420. */
  9421. #ifndef SQLITE_TEMP_FILE_PREFIX
  9422. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9423. #endif
  9424. /*
  9425. ** The following values may be passed as the second argument to
  9426. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9427. **
  9428. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9429. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9430. ** any time. Other processes may hold and obtain new SHARED locks.
  9431. ** PENDING: A single process may hold a PENDING lock on a file at
  9432. ** any one time. Existing SHARED locks may persist, but no new
  9433. ** SHARED locks may be obtained by other processes.
  9434. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9435. **
  9436. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9437. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9438. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9439. ** sqlite3OsLock().
  9440. */
  9441. #define NO_LOCK 0
  9442. #define SHARED_LOCK 1
  9443. #define RESERVED_LOCK 2
  9444. #define PENDING_LOCK 3
  9445. #define EXCLUSIVE_LOCK 4
  9446. /*
  9447. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9448. **
  9449. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9450. ** those functions are not available. So we use only LockFile() and
  9451. ** UnlockFile().
  9452. **
  9453. ** LockFile() prevents not just writing but also reading by other processes.
  9454. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9455. ** byte out of a specific range of bytes. The lock byte is obtained at
  9456. ** random so two separate readers can probably access the file at the
  9457. ** same time, unless they are unlucky and choose the same lock byte.
  9458. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9459. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9460. ** a single byte of the file that is designated as the reserved lock byte.
  9461. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9462. ** the RESERVED_LOCK byte.
  9463. **
  9464. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9465. ** which means we can use reader/writer locks. When reader/writer locks
  9466. ** are used, the lock is placed on the same range of bytes that is used
  9467. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9468. ** will support two or more Win95 readers or two or more WinNT readers.
  9469. ** But a single Win95 reader will lock out all WinNT readers and a single
  9470. ** WinNT reader will lock out all other Win95 readers.
  9471. **
  9472. ** The following #defines specify the range of bytes used for locking.
  9473. ** SHARED_SIZE is the number of bytes available in the pool from which
  9474. ** a random byte is selected for a shared lock. The pool of bytes for
  9475. ** shared locks begins at SHARED_FIRST.
  9476. **
  9477. ** The same locking strategy and
  9478. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9479. ** clients on win95, winNT, and unix all talking to the same shared file
  9480. ** and all locking correctly. To do so would require that samba (or whatever
  9481. ** tool is being used for file sharing) implements locks correctly between
  9482. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9483. ** using the same locking range we are at least open to the possibility.
  9484. **
  9485. ** Locking in windows is manditory. For this reason, we cannot store
  9486. ** actual data in the bytes used for locking. The pager never allocates
  9487. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9488. ** that all locks will fit on a single page even at the minimum page size.
  9489. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9490. ** is set high so that we don't have to allocate an unused page except
  9491. ** for very large databases. But one should test the page skipping logic
  9492. ** by setting PENDING_BYTE low and running the entire regression suite.
  9493. **
  9494. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9495. ** file format. Depending on how it is changed, you might not notice
  9496. ** the incompatibility right away, even running a full regression test.
  9497. ** The default location of PENDING_BYTE is the first byte past the
  9498. ** 1GB boundary.
  9499. **
  9500. */
  9501. #ifdef SQLITE_OMIT_WSD
  9502. # define PENDING_BYTE (0x40000000)
  9503. #else
  9504. # define PENDING_BYTE sqlite3PendingByte
  9505. #endif
  9506. #define RESERVED_BYTE (PENDING_BYTE+1)
  9507. #define SHARED_FIRST (PENDING_BYTE+2)
  9508. #define SHARED_SIZE 510
  9509. /*
  9510. ** Wrapper around OS specific sqlite3_os_init() function.
  9511. */
  9512. SQLITE_PRIVATE int sqlite3OsInit(void);
  9513. /*
  9514. ** Functions for accessing sqlite3_file methods
  9515. */
  9516. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9517. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9518. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9519. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9520. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9521. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9522. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9523. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9524. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9525. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9526. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9527. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9528. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9529. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9530. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9531. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9532. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9533. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9534. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9535. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9536. /*
  9537. ** Functions for accessing sqlite3_vfs methods
  9538. */
  9539. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9540. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9541. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9542. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9543. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9544. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9545. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9546. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9547. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9548. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9549. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9550. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9551. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9552. /*
  9553. ** Convenience functions for opening and closing files using
  9554. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9555. */
  9556. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9557. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9558. #endif /* _SQLITE_OS_H_ */
  9559. /************** End of os.h **************************************************/
  9560. /************** Continuing where we left off in sqliteInt.h ******************/
  9561. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9562. /************** Begin file mutex.h *******************************************/
  9563. /*
  9564. ** 2007 August 28
  9565. **
  9566. ** The author disclaims copyright to this source code. In place of
  9567. ** a legal notice, here is a blessing:
  9568. **
  9569. ** May you do good and not evil.
  9570. ** May you find forgiveness for yourself and forgive others.
  9571. ** May you share freely, never taking more than you give.
  9572. **
  9573. *************************************************************************
  9574. **
  9575. ** This file contains the common header for all mutex implementations.
  9576. ** The sqliteInt.h header #includes this file so that it is available
  9577. ** to all source files. We break it out in an effort to keep the code
  9578. ** better organized.
  9579. **
  9580. ** NOTE: source files should *not* #include this header file directly.
  9581. ** Source files should #include the sqliteInt.h file and let that file
  9582. ** include this one indirectly.
  9583. */
  9584. /*
  9585. ** Figure out what version of the code to use. The choices are
  9586. **
  9587. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9588. ** mutexes implemention cannot be overridden
  9589. ** at start-time.
  9590. **
  9591. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9592. ** mutual exclusion is provided. But this
  9593. ** implementation can be overridden at
  9594. ** start-time.
  9595. **
  9596. ** SQLITE_MUTEX_RTTHREAD For multi-threaded applications on rt-thread.
  9597. **
  9598. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9599. **
  9600. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9601. */
  9602. #if !SQLITE_THREADSAFE
  9603. # define SQLITE_MUTEX_OMIT
  9604. #endif
  9605. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9606. # if SQLITE_OS_UNIX
  9607. # define SQLITE_MUTEX_PTHREADS
  9608. # elif SQLITE_OS_WIN
  9609. # define SQLITE_MUTEX_W32
  9610. # elif SQLITE_OS_RTTHREAD
  9611. # define SQLITE_MUTEX_RTTHREAD
  9612. # else
  9613. # define SQLITE_MUTEX_NOOP
  9614. # endif
  9615. #endif
  9616. #ifdef SQLITE_MUTEX_OMIT
  9617. /*
  9618. ** If this is a no-op implementation, implement everything as macros.
  9619. */
  9620. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9621. #define sqlite3_mutex_free(X)
  9622. #define sqlite3_mutex_enter(X)
  9623. #define sqlite3_mutex_try(X) SQLITE_OK
  9624. #define sqlite3_mutex_leave(X)
  9625. #define sqlite3_mutex_held(X) ((void)(X),1)
  9626. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9627. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9628. #define sqlite3MutexInit() SQLITE_OK
  9629. #define sqlite3MutexEnd()
  9630. #define MUTEX_LOGIC(X)
  9631. #else
  9632. #define MUTEX_LOGIC(X) X
  9633. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9634. /************** End of mutex.h ***********************************************/
  9635. /************** Continuing where we left off in sqliteInt.h ******************/
  9636. /*
  9637. ** Each database file to be accessed by the system is an instance
  9638. ** of the following structure. There are normally two of these structures
  9639. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9640. ** aDb[1] is the database file used to hold temporary tables. Additional
  9641. ** databases may be attached.
  9642. */
  9643. struct Db {
  9644. char *zName; /* Name of this database */
  9645. Btree *pBt; /* The B*Tree structure for this database file */
  9646. u8 safety_level; /* How aggressive at syncing data to disk */
  9647. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9648. };
  9649. /*
  9650. ** An instance of the following structure stores a database schema.
  9651. **
  9652. ** Most Schema objects are associated with a Btree. The exception is
  9653. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9654. ** In shared cache mode, a single Schema object can be shared by multiple
  9655. ** Btrees that refer to the same underlying BtShared object.
  9656. **
  9657. ** Schema objects are automatically deallocated when the last Btree that
  9658. ** references them is destroyed. The TEMP Schema is manually freed by
  9659. ** sqlite3_close().
  9660. *
  9661. ** A thread must be holding a mutex on the corresponding Btree in order
  9662. ** to access Schema content. This implies that the thread must also be
  9663. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9664. ** For a TEMP Schema, only the connection mutex is required.
  9665. */
  9666. struct Schema {
  9667. int schema_cookie; /* Database schema version number for this file */
  9668. int iGeneration; /* Generation counter. Incremented with each change */
  9669. Hash tblHash; /* All tables indexed by name */
  9670. Hash idxHash; /* All (named) indices indexed by name */
  9671. Hash trigHash; /* All triggers indexed by name */
  9672. Hash fkeyHash; /* All foreign keys by referenced table name */
  9673. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9674. u8 file_format; /* Schema format version for this file */
  9675. u8 enc; /* Text encoding used by this database */
  9676. u16 flags; /* Flags associated with this schema */
  9677. int cache_size; /* Number of pages to use in the cache */
  9678. };
  9679. /*
  9680. ** These macros can be used to test, set, or clear bits in the
  9681. ** Db.pSchema->flags field.
  9682. */
  9683. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9684. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9685. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9686. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9687. /*
  9688. ** Allowed values for the DB.pSchema->flags field.
  9689. **
  9690. ** The DB_SchemaLoaded flag is set after the database schema has been
  9691. ** read into internal hash tables.
  9692. **
  9693. ** DB_UnresetViews means that one or more views have column names that
  9694. ** have been filled out. If the schema changes, these column names might
  9695. ** changes and so the view will need to be reset.
  9696. */
  9697. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9698. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9699. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9700. /*
  9701. ** The number of different kinds of things that can be limited
  9702. ** using the sqlite3_limit() interface.
  9703. */
  9704. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9705. /*
  9706. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9707. ** to satisfy small transient memory allocation requests for objects
  9708. ** associated with a particular database connection. The use of
  9709. ** lookaside malloc provides a significant performance enhancement
  9710. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9711. ** SQL statements.
  9712. **
  9713. ** The Lookaside structure holds configuration information about the
  9714. ** lookaside malloc subsystem. Each available memory allocation in
  9715. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9716. ** objects.
  9717. **
  9718. ** Lookaside allocations are only allowed for objects that are associated
  9719. ** with a particular database connection. Hence, schema information cannot
  9720. ** be stored in lookaside because in shared cache mode the schema information
  9721. ** is shared by multiple database connections. Therefore, while parsing
  9722. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9723. ** lookaside allocations are not used to construct the schema objects.
  9724. */
  9725. struct Lookaside {
  9726. u16 sz; /* Size of each buffer in bytes */
  9727. u8 bEnabled; /* False to disable new lookaside allocations */
  9728. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9729. int nOut; /* Number of buffers currently checked out */
  9730. int mxOut; /* Highwater mark for nOut */
  9731. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9732. LookasideSlot *pFree; /* List of available buffers */
  9733. void *pStart; /* First byte of available memory space */
  9734. void *pEnd; /* First byte past end of available space */
  9735. };
  9736. struct LookasideSlot {
  9737. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9738. };
  9739. /*
  9740. ** A hash table for function definitions.
  9741. **
  9742. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9743. ** Collisions are on the FuncDef.pHash chain.
  9744. */
  9745. struct FuncDefHash {
  9746. FuncDef *a[23]; /* Hash table for functions */
  9747. };
  9748. /*
  9749. ** Each database connection is an instance of the following structure.
  9750. */
  9751. struct sqlite3 {
  9752. sqlite3_vfs *pVfs; /* OS Interface */
  9753. struct Vdbe *pVdbe; /* List of active virtual machines */
  9754. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9755. sqlite3_mutex *mutex; /* Connection mutex */
  9756. Db *aDb; /* All backends */
  9757. int nDb; /* Number of backends currently in use */
  9758. int flags; /* Miscellaneous flags. See below */
  9759. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9760. i64 szMmap; /* Default mmap_size setting */
  9761. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9762. int errCode; /* Most recent error code (SQLITE_*) */
  9763. int errMask; /* & result codes with this before returning */
  9764. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9765. u8 autoCommit; /* The auto-commit flag. */
  9766. u8 temp_store; /* 1: file 2: memory 0: default */
  9767. u8 mallocFailed; /* True if we have seen a malloc failure */
  9768. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9769. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9770. u8 suppressErr; /* Do not issue error messages if true */
  9771. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9772. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9773. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9774. u32 magic; /* Magic number for detect library misuse */
  9775. int nChange; /* Value returned by sqlite3_changes() */
  9776. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9777. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9778. struct sqlite3InitInfo { /* Information used during initialization */
  9779. int newTnum; /* Rootpage of table being initialized */
  9780. u8 iDb; /* Which db file is being initialized */
  9781. u8 busy; /* TRUE if currently initializing */
  9782. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9783. } init;
  9784. int nVdbeActive; /* Number of VDBEs currently running */
  9785. int nVdbeRead; /* Number of active VDBEs that read or write */
  9786. int nVdbeWrite; /* Number of active VDBEs that read and write */
  9787. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  9788. int nExtension; /* Number of loaded extensions */
  9789. void **aExtension; /* Array of shared library handles */
  9790. void (*xTrace)(void*,const char*); /* Trace function */
  9791. void *pTraceArg; /* Argument to the trace function */
  9792. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9793. void *pProfileArg; /* Argument to profile function */
  9794. void *pCommitArg; /* Argument to xCommitCallback() */
  9795. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9796. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9797. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9798. void *pUpdateArg;
  9799. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9800. #ifndef SQLITE_OMIT_WAL
  9801. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9802. void *pWalArg;
  9803. #endif
  9804. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9805. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9806. void *pCollNeededArg;
  9807. sqlite3_value *pErr; /* Most recent error message */
  9808. union {
  9809. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9810. double notUsed1; /* Spacer */
  9811. } u1;
  9812. Lookaside lookaside; /* Lookaside malloc configuration */
  9813. #ifndef SQLITE_OMIT_AUTHORIZATION
  9814. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9815. /* Access authorization function */
  9816. void *pAuthArg; /* 1st argument to the access auth function */
  9817. #endif
  9818. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9819. int (*xProgress)(void *); /* The progress callback */
  9820. void *pProgressArg; /* Argument to the progress callback */
  9821. unsigned nProgressOps; /* Number of opcodes for progress callback */
  9822. #endif
  9823. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9824. int nVTrans; /* Allocated size of aVTrans */
  9825. Hash aModule; /* populated by sqlite3_create_module() */
  9826. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9827. VTable **aVTrans; /* Virtual tables with open transactions */
  9828. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9829. #endif
  9830. FuncDefHash aFunc; /* Hash table of connection functions */
  9831. Hash aCollSeq; /* All collating sequences */
  9832. BusyHandler busyHandler; /* Busy callback */
  9833. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9834. Savepoint *pSavepoint; /* List of active savepoints */
  9835. int busyTimeout; /* Busy handler timeout, in msec */
  9836. int nSavepoint; /* Number of non-transaction savepoints */
  9837. int nStatement; /* Number of nested statement-transactions */
  9838. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9839. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  9840. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9841. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9842. /* The following variables are all protected by the STATIC_MASTER
  9843. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9844. **
  9845. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9846. ** unlock so that it can proceed.
  9847. **
  9848. ** When X.pBlockingConnection==Y, that means that something that X tried
  9849. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9850. ** held by Y.
  9851. */
  9852. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9853. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9854. void *pUnlockArg; /* Argument to xUnlockNotify */
  9855. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9856. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9857. #endif
  9858. };
  9859. /*
  9860. ** A macro to discover the encoding of a database.
  9861. */
  9862. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9863. /*
  9864. ** Possible values for the sqlite3.flags.
  9865. */
  9866. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9867. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9868. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  9869. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  9870. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  9871. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  9872. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  9873. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  9874. /* DELETE, or UPDATE and return */
  9875. /* the count using a callback. */
  9876. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  9877. /* result set is empty */
  9878. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  9879. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  9880. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  9881. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  9882. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  9883. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  9884. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  9885. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  9886. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  9887. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  9888. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  9889. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  9890. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  9891. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  9892. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  9893. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  9894. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  9895. /*
  9896. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9897. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9898. ** selectively disable various optimizations.
  9899. */
  9900. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9901. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9902. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9903. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9904. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9905. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9906. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9907. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9908. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9909. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  9910. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  9911. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  9912. #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
  9913. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9914. /*
  9915. ** Macros for testing whether or not optimizations are enabled or disabled.
  9916. */
  9917. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9918. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9919. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9920. #else
  9921. #define OptimizationDisabled(db, mask) 0
  9922. #define OptimizationEnabled(db, mask) 1
  9923. #endif
  9924. /*
  9925. ** Possible values for the sqlite.magic field.
  9926. ** The numbers are obtained at random and have no special meaning, other
  9927. ** than being distinct from one another.
  9928. */
  9929. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9930. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9931. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9932. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9933. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9934. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9935. /*
  9936. ** Each SQL function is defined by an instance of the following
  9937. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9938. ** hash table. When multiple functions have the same name, the hash table
  9939. ** points to a linked list of these structures.
  9940. */
  9941. struct FuncDef {
  9942. i16 nArg; /* Number of arguments. -1 means unlimited */
  9943. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  9944. void *pUserData; /* User data parameter */
  9945. FuncDef *pNext; /* Next function with same name */
  9946. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9947. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9948. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9949. char *zName; /* SQL name of the function. */
  9950. FuncDef *pHash; /* Next with a different name but the same hash */
  9951. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9952. };
  9953. /*
  9954. ** This structure encapsulates a user-function destructor callback (as
  9955. ** configured using create_function_v2()) and a reference counter. When
  9956. ** create_function_v2() is called to create a function with a destructor,
  9957. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9958. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9959. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9960. ** member of each of the new FuncDef objects is set to point to the allocated
  9961. ** FuncDestructor.
  9962. **
  9963. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9964. ** count on this object is decremented. When it reaches 0, the destructor
  9965. ** is invoked and the FuncDestructor structure freed.
  9966. */
  9967. struct FuncDestructor {
  9968. int nRef;
  9969. void (*xDestroy)(void *);
  9970. void *pUserData;
  9971. };
  9972. /*
  9973. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9974. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9975. ** are assert() statements in the code to verify this.
  9976. */
  9977. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  9978. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  9979. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  9980. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  9981. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  9982. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  9983. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  9984. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  9985. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  9986. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  9987. /*
  9988. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9989. ** used to create the initializers for the FuncDef structures.
  9990. **
  9991. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9992. ** Used to create a scalar function definition of a function zName
  9993. ** implemented by C function xFunc that accepts nArg arguments. The
  9994. ** value passed as iArg is cast to a (void*) and made available
  9995. ** as the user-data (sqlite3_user_data()) for the function. If
  9996. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9997. **
  9998. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9999. ** Used to create an aggregate function definition implemented by
  10000. ** the C functions xStep and xFinal. The first four parameters
  10001. ** are interpreted in the same way as the first 4 parameters to
  10002. ** FUNCTION().
  10003. **
  10004. ** LIKEFUNC(zName, nArg, pArg, flags)
  10005. ** Used to create a scalar function definition of a function zName
  10006. ** that accepts nArg arguments and is implemented by a call to C
  10007. ** function likeFunc. Argument pArg is cast to a (void *) and made
  10008. ** available as the function user-data (sqlite3_user_data()). The
  10009. ** FuncDef.flags variable is set to the value passed as the flags
  10010. ** parameter.
  10011. */
  10012. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10013. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10014. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10015. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  10016. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  10017. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10018. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  10019. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10020. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  10021. #define LIKEFUNC(zName, nArg, arg, flags) \
  10022. {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  10023. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  10024. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  10025. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10026. /*
  10027. ** All current savepoints are stored in a linked list starting at
  10028. ** sqlite3.pSavepoint. The first element in the list is the most recently
  10029. ** opened savepoint. Savepoints are added to the list by the vdbe
  10030. ** OP_Savepoint instruction.
  10031. */
  10032. struct Savepoint {
  10033. char *zName; /* Savepoint name (nul-terminated) */
  10034. i64 nDeferredCons; /* Number of deferred fk violations */
  10035. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  10036. Savepoint *pNext; /* Parent savepoint (if any) */
  10037. };
  10038. /*
  10039. ** The following are used as the second parameter to sqlite3Savepoint(),
  10040. ** and as the P1 argument to the OP_Savepoint instruction.
  10041. */
  10042. #define SAVEPOINT_BEGIN 0
  10043. #define SAVEPOINT_RELEASE 1
  10044. #define SAVEPOINT_ROLLBACK 2
  10045. /*
  10046. ** Each SQLite module (virtual table definition) is defined by an
  10047. ** instance of the following structure, stored in the sqlite3.aModule
  10048. ** hash table.
  10049. */
  10050. struct Module {
  10051. const sqlite3_module *pModule; /* Callback pointers */
  10052. const char *zName; /* Name passed to create_module() */
  10053. void *pAux; /* pAux passed to create_module() */
  10054. void (*xDestroy)(void *); /* Module destructor function */
  10055. };
  10056. /*
  10057. ** information about each column of an SQL table is held in an instance
  10058. ** of this structure.
  10059. */
  10060. struct Column {
  10061. char *zName; /* Name of this column */
  10062. Expr *pDflt; /* Default value of this column */
  10063. char *zDflt; /* Original text of the default value */
  10064. char *zType; /* Data type for this column */
  10065. char *zColl; /* Collating sequence. If NULL, use the default */
  10066. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10067. char affinity; /* One of the SQLITE_AFF_... values */
  10068. u8 szEst; /* Estimated size of this column. INT==1 */
  10069. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10070. };
  10071. /* Allowed values for Column.colFlags:
  10072. */
  10073. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10074. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10075. /*
  10076. ** A "Collating Sequence" is defined by an instance of the following
  10077. ** structure. Conceptually, a collating sequence consists of a name and
  10078. ** a comparison routine that defines the order of that sequence.
  10079. **
  10080. ** If CollSeq.xCmp is NULL, it means that the
  10081. ** collating sequence is undefined. Indices built on an undefined
  10082. ** collating sequence may not be read or written.
  10083. */
  10084. struct CollSeq {
  10085. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10086. u8 enc; /* Text encoding handled by xCmp() */
  10087. void *pUser; /* First argument to xCmp() */
  10088. int (*xCmp)(void*,int, const void*, int, const void*);
  10089. void (*xDel)(void*); /* Destructor for pUser */
  10090. };
  10091. /*
  10092. ** A sort order can be either ASC or DESC.
  10093. */
  10094. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10095. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10096. /*
  10097. ** Column affinity types.
  10098. **
  10099. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10100. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10101. ** the speed a little by numbering the values consecutively.
  10102. **
  10103. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  10104. ** when multiple affinity types are concatenated into a string and
  10105. ** used as the P4 operand, they will be more readable.
  10106. **
  10107. ** Note also that the numeric types are grouped together so that testing
  10108. ** for a numeric type is a single comparison.
  10109. */
  10110. #define SQLITE_AFF_TEXT 'a'
  10111. #define SQLITE_AFF_NONE 'b'
  10112. #define SQLITE_AFF_NUMERIC 'c'
  10113. #define SQLITE_AFF_INTEGER 'd'
  10114. #define SQLITE_AFF_REAL 'e'
  10115. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10116. /*
  10117. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10118. ** affinity value.
  10119. */
  10120. #define SQLITE_AFF_MASK 0x67
  10121. /*
  10122. ** Additional bit values that can be ORed with an affinity without
  10123. ** changing the affinity.
  10124. */
  10125. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  10126. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  10127. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10128. /*
  10129. ** An object of this type is created for each virtual table present in
  10130. ** the database schema.
  10131. **
  10132. ** If the database schema is shared, then there is one instance of this
  10133. ** structure for each database connection (sqlite3*) that uses the shared
  10134. ** schema. This is because each database connection requires its own unique
  10135. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10136. ** implementation. sqlite3_vtab* handles can not be shared between
  10137. ** database connections, even when the rest of the in-memory database
  10138. ** schema is shared, as the implementation often stores the database
  10139. ** connection handle passed to it via the xConnect() or xCreate() method
  10140. ** during initialization internally. This database connection handle may
  10141. ** then be used by the virtual table implementation to access real tables
  10142. ** within the database. So that they appear as part of the callers
  10143. ** transaction, these accesses need to be made via the same database
  10144. ** connection as that used to execute SQL operations on the virtual table.
  10145. **
  10146. ** All VTable objects that correspond to a single table in a shared
  10147. ** database schema are initially stored in a linked-list pointed to by
  10148. ** the Table.pVTable member variable of the corresponding Table object.
  10149. ** When an sqlite3_prepare() operation is required to access the virtual
  10150. ** table, it searches the list for the VTable that corresponds to the
  10151. ** database connection doing the preparing so as to use the correct
  10152. ** sqlite3_vtab* handle in the compiled query.
  10153. **
  10154. ** When an in-memory Table object is deleted (for example when the
  10155. ** schema is being reloaded for some reason), the VTable objects are not
  10156. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10157. ** immediately. Instead, they are moved from the Table.pVTable list to
  10158. ** another linked list headed by the sqlite3.pDisconnect member of the
  10159. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10160. ** next time a statement is prepared using said sqlite3*. This is done
  10161. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10162. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10163. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10164. ** list without holding the corresponding sqlite3.mutex mutex.
  10165. **
  10166. ** The memory for objects of this type is always allocated by
  10167. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10168. ** the first argument.
  10169. */
  10170. struct VTable {
  10171. sqlite3 *db; /* Database connection associated with this table */
  10172. Module *pMod; /* Pointer to module implementation */
  10173. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10174. int nRef; /* Number of pointers to this structure */
  10175. u8 bConstraint; /* True if constraints are supported */
  10176. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10177. VTable *pNext; /* Next in linked list (see above) */
  10178. };
  10179. /*
  10180. ** Each SQL table is represented in memory by an instance of the
  10181. ** following structure.
  10182. **
  10183. ** Table.zName is the name of the table. The case of the original
  10184. ** CREATE TABLE statement is stored, but case is not significant for
  10185. ** comparisons.
  10186. **
  10187. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10188. ** pointer to an array of Column structures, one for each column.
  10189. **
  10190. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10191. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10192. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10193. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10194. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10195. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10196. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10197. **
  10198. ** Table.tnum is the page number for the root BTree page of the table in the
  10199. ** database file. If Table.iDb is the index of the database table backend
  10200. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10201. ** holds temporary tables and indices. If TF_Ephemeral is set
  10202. ** then the table is stored in a file that is automatically deleted
  10203. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10204. ** refers VDBE cursor number that holds the table open, not to the root
  10205. ** page number. Transient tables are used to hold the results of a
  10206. ** sub-query that appears instead of a real table name in the FROM clause
  10207. ** of a SELECT statement.
  10208. */
  10209. struct Table {
  10210. char *zName; /* Name of the table or view */
  10211. Column *aCol; /* Information about each column */
  10212. Index *pIndex; /* List of SQL indexes on this table. */
  10213. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10214. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10215. char *zColAff; /* String defining the affinity of each column */
  10216. #ifndef SQLITE_OMIT_CHECK
  10217. ExprList *pCheck; /* All CHECK constraints */
  10218. #endif
  10219. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  10220. int tnum; /* Root BTree node for this table (see note above) */
  10221. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10222. i16 nCol; /* Number of columns in this table */
  10223. u16 nRef; /* Number of pointers to this Table */
  10224. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10225. u8 tabFlags; /* Mask of TF_* values */
  10226. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10227. #ifndef SQLITE_OMIT_ALTERTABLE
  10228. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10229. #endif
  10230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10231. int nModuleArg; /* Number of arguments to the module */
  10232. char **azModuleArg; /* Text of all module args. [0] is module name */
  10233. VTable *pVTable; /* List of VTable objects. */
  10234. #endif
  10235. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10236. Schema *pSchema; /* Schema that contains this table */
  10237. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10238. };
  10239. /*
  10240. ** Allowed values for Tabe.tabFlags.
  10241. */
  10242. #define TF_Readonly 0x01 /* Read-only system table */
  10243. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10244. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10245. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10246. #define TF_Virtual 0x10 /* Is a virtual table */
  10247. /*
  10248. ** Test to see whether or not a table is a virtual table. This is
  10249. ** done as a macro so that it will be optimized out when virtual
  10250. ** table support is omitted from the build.
  10251. */
  10252. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10253. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10254. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10255. #else
  10256. # define IsVirtual(X) 0
  10257. # define IsHiddenColumn(X) 0
  10258. #endif
  10259. /*
  10260. ** Each foreign key constraint is an instance of the following structure.
  10261. **
  10262. ** A foreign key is associated with two tables. The "from" table is
  10263. ** the table that contains the REFERENCES clause that creates the foreign
  10264. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10265. ** Consider this example:
  10266. **
  10267. ** CREATE TABLE ex1(
  10268. ** a INTEGER PRIMARY KEY,
  10269. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10270. ** );
  10271. **
  10272. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10273. **
  10274. ** Each REFERENCES clause generates an instance of the following structure
  10275. ** which is attached to the from-table. The to-table need not exist when
  10276. ** the from-table is created. The existence of the to-table is not checked.
  10277. */
  10278. struct FKey {
  10279. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10280. FKey *pNextFrom; /* Next foreign key in pFrom */
  10281. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10282. FKey *pNextTo; /* Next foreign key on table named zTo */
  10283. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  10284. int nCol; /* Number of columns in this key */
  10285. /* EV: R-30323-21917 */
  10286. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10287. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10288. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10289. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10290. int iFrom; /* Index of column in pFrom */
  10291. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10292. } aCol[1]; /* One entry for each of nCol column s */
  10293. };
  10294. /*
  10295. ** SQLite supports many different ways to resolve a constraint
  10296. ** error. ROLLBACK processing means that a constraint violation
  10297. ** causes the operation in process to fail and for the current transaction
  10298. ** to be rolled back. ABORT processing means the operation in process
  10299. ** fails and any prior changes from that one operation are backed out,
  10300. ** but the transaction is not rolled back. FAIL processing means that
  10301. ** the operation in progress stops and returns an error code. But prior
  10302. ** changes due to the same operation are not backed out and no rollback
  10303. ** occurs. IGNORE means that the particular row that caused the constraint
  10304. ** error is not inserted or updated. Processing continues and no error
  10305. ** is returned. REPLACE means that preexisting database rows that caused
  10306. ** a UNIQUE constraint violation are removed so that the new insert or
  10307. ** update can proceed. Processing continues and no error is reported.
  10308. **
  10309. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10310. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10311. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10312. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10313. ** referenced table row is propagated into the row that holds the
  10314. ** foreign key.
  10315. **
  10316. ** The following symbolic values are used to record which type
  10317. ** of action to take.
  10318. */
  10319. #define OE_None 0 /* There is no constraint to check */
  10320. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10321. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10322. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10323. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10324. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10325. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10326. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10327. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10328. #define OE_Cascade 9 /* Cascade the changes */
  10329. #define OE_Default 10 /* Do whatever the default action is */
  10330. /*
  10331. ** An instance of the following structure is passed as the first
  10332. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10333. ** comparison of the two index keys.
  10334. **
  10335. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10336. ** are nField slots for the columns of an index then one extra slot
  10337. ** for the rowid at the end.
  10338. */
  10339. struct KeyInfo {
  10340. sqlite3 *db; /* The database connection */
  10341. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10342. u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
  10343. u8 *aSortOrder; /* Sort order for each column. */
  10344. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10345. };
  10346. /*
  10347. ** An instance of the following structure holds information about a
  10348. ** single index record that has already been parsed out into individual
  10349. ** values.
  10350. **
  10351. ** A record is an object that contains one or more fields of data.
  10352. ** Records are used to store the content of a table row and to store
  10353. ** the key of an index. A blob encoding of a record is created by
  10354. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10355. ** OP_Column opcode.
  10356. **
  10357. ** This structure holds a record that has already been disassembled
  10358. ** into its constituent fields.
  10359. */
  10360. struct UnpackedRecord {
  10361. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10362. u16 nField; /* Number of entries in apMem[] */
  10363. u8 flags; /* Boolean settings. UNPACKED_... below */
  10364. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10365. Mem *aMem; /* Values */
  10366. };
  10367. /*
  10368. ** Allowed values of UnpackedRecord.flags
  10369. */
  10370. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10371. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10372. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10373. /*
  10374. ** Each SQL index is represented in memory by an
  10375. ** instance of the following structure.
  10376. **
  10377. ** The columns of the table that are to be indexed are described
  10378. ** by the aiColumn[] field of this structure. For example, suppose
  10379. ** we have the following table and index:
  10380. **
  10381. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10382. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10383. **
  10384. ** In the Table structure describing Ex1, nCol==3 because there are
  10385. ** three columns in the table. In the Index structure describing
  10386. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10387. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10388. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10389. ** The second column to be indexed (c1) has an index of 0 in
  10390. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10391. **
  10392. ** The Index.onError field determines whether or not the indexed columns
  10393. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10394. ** it means this is not a unique index. Otherwise it is a unique index
  10395. ** and the value of Index.onError indicate the which conflict resolution
  10396. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10397. ** element.
  10398. */
  10399. struct Index {
  10400. char *zName; /* Name of this index */
  10401. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10402. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  10403. Table *pTable; /* The SQL table being indexed */
  10404. char *zColAff; /* String defining the affinity of each column */
  10405. Index *pNext; /* The next index associated with the same table */
  10406. Schema *pSchema; /* Schema containing this index */
  10407. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10408. char **azColl; /* Array of collation sequence names for index */
  10409. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10410. int tnum; /* DB Page containing root of this index */
  10411. LogEst szIdxRow; /* Estimated average row size in bytes */
  10412. u16 nColumn; /* Number of columns in table used by this index */
  10413. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10414. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10415. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10416. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10417. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10418. int nSample; /* Number of elements in aSample[] */
  10419. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10420. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10421. IndexSample *aSample; /* Samples of the left-most key */
  10422. #endif
  10423. };
  10424. /*
  10425. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10426. ** using a structure of this type. See documentation at the top of the
  10427. ** analyze.c source file for additional information.
  10428. */
  10429. struct IndexSample {
  10430. void *p; /* Pointer to sampled record */
  10431. int n; /* Size of record in bytes */
  10432. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10433. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10434. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10435. };
  10436. /*
  10437. ** Each token coming out of the lexer is an instance of
  10438. ** this structure. Tokens are also used as part of an expression.
  10439. **
  10440. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10441. ** may contain random values. Do not make any assumptions about Token.dyn
  10442. ** and Token.n when Token.z==0.
  10443. */
  10444. struct Token {
  10445. const char *z; /* Text of the token. Not NULL-terminated! */
  10446. unsigned int n; /* Number of characters in this token */
  10447. };
  10448. /*
  10449. ** An instance of this structure contains information needed to generate
  10450. ** code for a SELECT that contains aggregate functions.
  10451. **
  10452. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10453. ** pointer to this structure. The Expr.iColumn field is the index in
  10454. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10455. ** code for that node.
  10456. **
  10457. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10458. ** original Select structure that describes the SELECT statement. These
  10459. ** fields do not need to be freed when deallocating the AggInfo structure.
  10460. */
  10461. struct AggInfo {
  10462. u8 directMode; /* Direct rendering mode means take data directly
  10463. ** from source tables rather than from accumulators */
  10464. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10465. ** than the source table */
  10466. int sortingIdx; /* Cursor number of the sorting index */
  10467. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10468. int nSortingColumn; /* Number of columns in the sorting index */
  10469. ExprList *pGroupBy; /* The group by clause */
  10470. struct AggInfo_col { /* For each column used in source tables */
  10471. Table *pTab; /* Source table */
  10472. int iTable; /* Cursor number of the source table */
  10473. int iColumn; /* Column number within the source table */
  10474. int iSorterColumn; /* Column number in the sorting index */
  10475. int iMem; /* Memory location that acts as accumulator */
  10476. Expr *pExpr; /* The original expression */
  10477. } *aCol;
  10478. int nColumn; /* Number of used entries in aCol[] */
  10479. int nAccumulator; /* Number of columns that show through to the output.
  10480. ** Additional columns are used only as parameters to
  10481. ** aggregate functions */
  10482. struct AggInfo_func { /* For each aggregate function */
  10483. Expr *pExpr; /* Expression encoding the function */
  10484. FuncDef *pFunc; /* The aggregate function implementation */
  10485. int iMem; /* Memory location that acts as accumulator */
  10486. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10487. } *aFunc;
  10488. int nFunc; /* Number of entries in aFunc[] */
  10489. };
  10490. /*
  10491. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10492. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10493. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10494. ** it uses less memory in the Expr object, which is a big memory user
  10495. ** in systems with lots of prepared statements. And few applications
  10496. ** need more than about 10 or 20 variables. But some extreme users want
  10497. ** to have prepared statements with over 32767 variables, and for them
  10498. ** the option is available (at compile-time).
  10499. */
  10500. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10501. typedef i16 ynVar;
  10502. #else
  10503. typedef int ynVar;
  10504. #endif
  10505. /*
  10506. ** Each node of an expression in the parse tree is an instance
  10507. ** of this structure.
  10508. **
  10509. ** Expr.op is the opcode. The integer parser token codes are reused
  10510. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10511. ** code representing the ">=" operator. This same integer code is reused
  10512. ** to represent the greater-than-or-equal-to operator in the expression
  10513. ** tree.
  10514. **
  10515. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10516. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10517. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10518. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10519. ** then Expr.token contains the name of the function.
  10520. **
  10521. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10522. ** binary operator. Either or both may be NULL.
  10523. **
  10524. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10525. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10526. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10527. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10528. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10529. ** valid.
  10530. **
  10531. ** An expression of the form ID or ID.ID refers to a column in a table.
  10532. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10533. ** the integer cursor number of a VDBE cursor pointing to that table and
  10534. ** Expr.iColumn is the column number for the specific column. If the
  10535. ** expression is used as a result in an aggregate SELECT, then the
  10536. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10537. ** it can be accessed after all aggregates are computed.
  10538. **
  10539. ** If the expression is an unbound variable marker (a question mark
  10540. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10541. ** number for that variable.
  10542. **
  10543. ** If the expression is a subquery then Expr.iColumn holds an integer
  10544. ** register number containing the result of the subquery. If the
  10545. ** subquery gives a constant result, then iTable is -1. If the subquery
  10546. ** gives a different answer at different times during statement processing
  10547. ** then iTable is the address of a subroutine that computes the subquery.
  10548. **
  10549. ** If the Expr is of type OP_Column, and the table it is selecting from
  10550. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10551. ** corresponding table definition.
  10552. **
  10553. ** ALLOCATION NOTES:
  10554. **
  10555. ** Expr objects can use a lot of memory space in database schema. To
  10556. ** help reduce memory requirements, sometimes an Expr object will be
  10557. ** truncated. And to reduce the number of memory allocations, sometimes
  10558. ** two or more Expr objects will be stored in a single memory allocation,
  10559. ** together with Expr.zToken strings.
  10560. **
  10561. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10562. ** an Expr object is truncated. When EP_Reduced is set, then all
  10563. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10564. ** are contained within the same memory allocation. Note, however, that
  10565. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10566. ** allocated, regardless of whether or not EP_Reduced is set.
  10567. */
  10568. struct Expr {
  10569. u8 op; /* Operation performed by this node */
  10570. char affinity; /* The affinity of the column or 0 if not a column */
  10571. u32 flags; /* Various flags. EP_* See below */
  10572. union {
  10573. char *zToken; /* Token value. Zero terminated and dequoted */
  10574. int iValue; /* Non-negative integer value if EP_IntValue */
  10575. } u;
  10576. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10577. ** space is allocated for the fields below this point. An attempt to
  10578. ** access them will result in a segfault or malfunction.
  10579. *********************************************************************/
  10580. Expr *pLeft; /* Left subnode */
  10581. Expr *pRight; /* Right subnode */
  10582. union {
  10583. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  10584. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  10585. } x;
  10586. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10587. ** space is allocated for the fields below this point. An attempt to
  10588. ** access them will result in a segfault or malfunction.
  10589. *********************************************************************/
  10590. #if SQLITE_MAX_EXPR_DEPTH>0
  10591. int nHeight; /* Height of the tree headed by this node */
  10592. #endif
  10593. int iTable; /* TK_COLUMN: cursor number of table holding column
  10594. ** TK_REGISTER: register number
  10595. ** TK_TRIGGER: 1 -> new, 0 -> old
  10596. ** EP_Unlikely: 1000 times likelihood */
  10597. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10598. ** TK_VARIABLE: variable number (always >= 1). */
  10599. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10600. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10601. u8 op2; /* TK_REGISTER: original value of Expr.op
  10602. ** TK_COLUMN: the value of p5 for OP_Column
  10603. ** TK_AGG_FUNCTION: nesting depth */
  10604. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10605. Table *pTab; /* Table for TK_COLUMN expressions. */
  10606. };
  10607. /*
  10608. ** The following are the meanings of bits in the Expr.flags field.
  10609. */
  10610. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  10611. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  10612. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  10613. #define EP_Error 0x000008 /* Expression contains one or more errors */
  10614. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  10615. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  10616. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  10617. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  10618. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
  10619. #define EP_FixedDest 0x000200 /* Result needed in a specific register */
  10620. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  10621. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  10622. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  10623. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  10624. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  10625. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  10626. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  10627. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  10628. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  10629. /*
  10630. ** These macros can be used to test, set, or clear bits in the
  10631. ** Expr.flags field.
  10632. */
  10633. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  10634. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  10635. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10636. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10637. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  10638. ** and Accreditation only. It works like ExprSetProperty() during VVA
  10639. ** processes but is a no-op for delivery.
  10640. */
  10641. #ifdef SQLITE_DEBUG
  10642. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  10643. #else
  10644. # define ExprSetVVAProperty(E,P)
  10645. #endif
  10646. /*
  10647. ** Macros to determine the number of bytes required by a normal Expr
  10648. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10649. ** and an Expr struct with the EP_TokenOnly flag set.
  10650. */
  10651. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10652. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10653. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10654. /*
  10655. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10656. ** above sqlite3ExprDup() for details.
  10657. */
  10658. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10659. /*
  10660. ** A list of expressions. Each expression may optionally have a
  10661. ** name. An expr/name combination can be used in several ways, such
  10662. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10663. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10664. ** also be used as the argument to a function, in which case the a.zName
  10665. ** field is not used.
  10666. **
  10667. ** By default the Expr.zSpan field holds a human-readable description of
  10668. ** the expression that is used in the generation of error messages and
  10669. ** column labels. In this case, Expr.zSpan is typically the text of a
  10670. ** column expression as it exists in a SELECT statement. However, if
  10671. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  10672. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  10673. ** form is used for name resolution with nested FROM clauses.
  10674. */
  10675. struct ExprList {
  10676. int nExpr; /* Number of expressions on the list */
  10677. int iECursor; /* VDBE Cursor associated with this ExprList */
  10678. struct ExprList_item { /* For each expression in the list */
  10679. Expr *pExpr; /* The list of expressions */
  10680. char *zName; /* Token associated with this expression */
  10681. char *zSpan; /* Original text of the expression */
  10682. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10683. unsigned done :1; /* A flag to indicate when processing is finished */
  10684. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  10685. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10686. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10687. } *a; /* Alloc a power of two greater or equal to nExpr */
  10688. };
  10689. /*
  10690. ** An instance of this structure is used by the parser to record both
  10691. ** the parse tree for an expression and the span of input text for an
  10692. ** expression.
  10693. */
  10694. struct ExprSpan {
  10695. Expr *pExpr; /* The expression parse tree */
  10696. const char *zStart; /* First character of input text */
  10697. const char *zEnd; /* One character past the end of input text */
  10698. };
  10699. /*
  10700. ** An instance of this structure can hold a simple list of identifiers,
  10701. ** such as the list "a,b,c" in the following statements:
  10702. **
  10703. ** INSERT INTO t(a,b,c) VALUES ...;
  10704. ** CREATE INDEX idx ON t(a,b,c);
  10705. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10706. **
  10707. ** The IdList.a.idx field is used when the IdList represents the list of
  10708. ** column names after a table name in an INSERT statement. In the statement
  10709. **
  10710. ** INSERT INTO t(a,b,c) ...
  10711. **
  10712. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10713. */
  10714. struct IdList {
  10715. struct IdList_item {
  10716. char *zName; /* Name of the identifier */
  10717. int idx; /* Index in some Table.aCol[] of a column named zName */
  10718. } *a;
  10719. int nId; /* Number of identifiers on the list */
  10720. };
  10721. /*
  10722. ** The bitmask datatype defined below is used for various optimizations.
  10723. **
  10724. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10725. ** tables in a join to 32 instead of 64. But it also reduces the size
  10726. ** of the library by 738 bytes on ix86.
  10727. */
  10728. typedef u64 Bitmask;
  10729. /*
  10730. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10731. */
  10732. #define BMS ((int)(sizeof(Bitmask)*8))
  10733. /*
  10734. ** A bit in a Bitmask
  10735. */
  10736. #define MASKBIT(n) (((Bitmask)1)<<(n))
  10737. /*
  10738. ** The following structure describes the FROM clause of a SELECT statement.
  10739. ** Each table or subquery in the FROM clause is a separate element of
  10740. ** the SrcList.a[] array.
  10741. **
  10742. ** With the addition of multiple database support, the following structure
  10743. ** can also be used to describe a particular table such as the table that
  10744. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10745. ** such a table must be a simple name: ID. But in SQLite, the table can
  10746. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10747. **
  10748. ** The jointype starts out showing the join type between the current table
  10749. ** and the next table on the list. The parser builds the list this way.
  10750. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10751. ** jointype expresses the join between the table and the previous table.
  10752. **
  10753. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10754. ** contains more than 63 columns and the 64-th or later column is used.
  10755. */
  10756. struct SrcList {
  10757. u8 nSrc; /* Number of tables or subqueries in the FROM clause */
  10758. u8 nAlloc; /* Number of entries allocated in a[] below */
  10759. struct SrcList_item {
  10760. Schema *pSchema; /* Schema to which this item is fixed */
  10761. char *zDatabase; /* Name of database holding this table */
  10762. char *zName; /* Name of the table */
  10763. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10764. Table *pTab; /* An SQL table corresponding to zName */
  10765. Select *pSelect; /* A SELECT statement used in place of a table name */
  10766. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10767. int regReturn; /* Register holding return address of addrFillSub */
  10768. u8 jointype; /* Type of join between this able and the previous */
  10769. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10770. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10771. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10772. #ifndef SQLITE_OMIT_EXPLAIN
  10773. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10774. #endif
  10775. int iCursor; /* The VDBE cursor number used to access this table */
  10776. Expr *pOn; /* The ON clause of a join */
  10777. IdList *pUsing; /* The USING clause of a join */
  10778. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10779. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10780. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10781. } a[1]; /* One entry for each identifier on the list */
  10782. };
  10783. /*
  10784. ** Permitted values of the SrcList.a.jointype field
  10785. */
  10786. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10787. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10788. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10789. #define JT_LEFT 0x0008 /* Left outer join */
  10790. #define JT_RIGHT 0x0010 /* Right outer join */
  10791. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10792. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10793. /*
  10794. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10795. ** and the WhereInfo.wctrlFlags member.
  10796. */
  10797. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10798. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10799. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10800. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10801. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10802. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10803. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10804. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10805. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10806. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  10807. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  10808. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  10809. /* Allowed return values from sqlite3WhereIsDistinct()
  10810. */
  10811. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  10812. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  10813. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  10814. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  10815. /*
  10816. ** A NameContext defines a context in which to resolve table and column
  10817. ** names. The context consists of a list of tables (the pSrcList) field and
  10818. ** a list of named expression (pEList). The named expression list may
  10819. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10820. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10821. ** pEList corresponds to the result set of a SELECT and is NULL for
  10822. ** other statements.
  10823. **
  10824. ** NameContexts can be nested. When resolving names, the inner-most
  10825. ** context is searched first. If no match is found, the next outer
  10826. ** context is checked. If there is still no match, the next context
  10827. ** is checked. This process continues until either a match is found
  10828. ** or all contexts are check. When a match is found, the nRef member of
  10829. ** the context containing the match is incremented.
  10830. **
  10831. ** Each subquery gets a new NameContext. The pNext field points to the
  10832. ** NameContext in the parent query. Thus the process of scanning the
  10833. ** NameContext list corresponds to searching through successively outer
  10834. ** subqueries looking for a match.
  10835. */
  10836. struct NameContext {
  10837. Parse *pParse; /* The parser */
  10838. SrcList *pSrcList; /* One or more tables used to resolve names */
  10839. ExprList *pEList; /* Optional list of result-set columns */
  10840. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10841. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10842. int nRef; /* Number of names resolved by this context */
  10843. int nErr; /* Number of errors encountered while resolving names */
  10844. u8 ncFlags; /* Zero or more NC_* flags defined below */
  10845. };
  10846. /*
  10847. ** Allowed values for the NameContext, ncFlags field.
  10848. */
  10849. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  10850. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  10851. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  10852. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  10853. #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
  10854. /*
  10855. ** An instance of the following structure contains all information
  10856. ** needed to generate code for a single SELECT statement.
  10857. **
  10858. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10859. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10860. ** limit and nOffset to the value of the offset (or 0 if there is not
  10861. ** offset). But later on, nLimit and nOffset become the memory locations
  10862. ** in the VDBE that record the limit and offset counters.
  10863. **
  10864. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10865. ** These addresses must be stored so that we can go back and fill in
  10866. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10867. ** the number of columns in P2 can be computed at the same time
  10868. ** as the OP_OpenEphm instruction is coded because not
  10869. ** enough information about the compound query is known at that point.
  10870. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10871. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10872. ** sequences for the ORDER BY clause.
  10873. */
  10874. struct Select {
  10875. ExprList *pEList; /* The fields of the result */
  10876. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10877. u16 selFlags; /* Various SF_* values */
  10878. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10879. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10880. u64 nSelectRow; /* Estimated number of result rows */
  10881. SrcList *pSrc; /* The FROM clause */
  10882. Expr *pWhere; /* The WHERE clause */
  10883. ExprList *pGroupBy; /* The GROUP BY clause */
  10884. Expr *pHaving; /* The HAVING clause */
  10885. ExprList *pOrderBy; /* The ORDER BY clause */
  10886. Select *pPrior; /* Prior select in a compound select statement */
  10887. Select *pNext; /* Next select to the left in a compound */
  10888. Select *pRightmost; /* Right-most select in a compound select statement */
  10889. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10890. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10891. };
  10892. /*
  10893. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10894. ** "Select Flag".
  10895. */
  10896. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10897. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10898. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10899. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10900. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10901. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10902. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10903. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10904. #define SF_Materialize 0x0100 /* Force materialization of views */
  10905. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  10906. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  10907. /*
  10908. ** The results of a select can be distributed in several ways. The
  10909. ** "SRT" prefix means "SELECT Result Type".
  10910. */
  10911. #define SRT_Union 1 /* Store result as keys in an index */
  10912. #define SRT_Except 2 /* Remove result from a UNION index */
  10913. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10914. #define SRT_Discard 4 /* Do not save the results anywhere */
  10915. /* The ORDER BY clause is ignored for all of the above */
  10916. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10917. #define SRT_Output 5 /* Output each row of result */
  10918. #define SRT_Mem 6 /* Store result in a memory cell */
  10919. #define SRT_Set 7 /* Store results as keys in an index */
  10920. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10921. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10922. #define SRT_Coroutine 10 /* Generate a single row of result */
  10923. /*
  10924. ** An instance of this object describes where to put of the results of
  10925. ** a SELECT statement.
  10926. */
  10927. struct SelectDest {
  10928. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  10929. char affSdst; /* Affinity used when eDest==SRT_Set */
  10930. int iSDParm; /* A parameter used by the eDest disposal method */
  10931. int iSdst; /* Base register where results are written */
  10932. int nSdst; /* Number of registers allocated */
  10933. };
  10934. /*
  10935. ** During code generation of statements that do inserts into AUTOINCREMENT
  10936. ** tables, the following information is attached to the Table.u.autoInc.p
  10937. ** pointer of each autoincrement table to record some side information that
  10938. ** the code generator needs. We have to keep per-table autoincrement
  10939. ** information in case inserts are down within triggers. Triggers do not
  10940. ** normally coordinate their activities, but we do need to coordinate the
  10941. ** loading and saving of autoincrement information.
  10942. */
  10943. struct AutoincInfo {
  10944. AutoincInfo *pNext; /* Next info block in a list of them all */
  10945. Table *pTab; /* Table this info block refers to */
  10946. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10947. int regCtr; /* Memory register holding the rowid counter */
  10948. };
  10949. /*
  10950. ** Size of the column cache
  10951. */
  10952. #ifndef SQLITE_N_COLCACHE
  10953. # define SQLITE_N_COLCACHE 10
  10954. #endif
  10955. /*
  10956. ** At least one instance of the following structure is created for each
  10957. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10958. ** statement. All such objects are stored in the linked list headed at
  10959. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10960. ** completed.
  10961. **
  10962. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10963. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10964. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10965. ** The Parse.pTriggerPrg list never contains two entries with the same
  10966. ** values for both pTrigger and orconf.
  10967. **
  10968. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10969. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10970. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10971. ** a mask of new.* columns used by the program.
  10972. */
  10973. struct TriggerPrg {
  10974. Trigger *pTrigger; /* Trigger this program was coded from */
  10975. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10976. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10977. int orconf; /* Default ON CONFLICT policy */
  10978. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10979. };
  10980. /*
  10981. ** The yDbMask datatype for the bitmask of all attached databases.
  10982. */
  10983. #if SQLITE_MAX_ATTACHED>30
  10984. typedef sqlite3_uint64 yDbMask;
  10985. #else
  10986. typedef unsigned int yDbMask;
  10987. #endif
  10988. /*
  10989. ** An SQL parser context. A copy of this structure is passed through
  10990. ** the parser and down into all the parser action routine in order to
  10991. ** carry around information that is global to the entire parse.
  10992. **
  10993. ** The structure is divided into two parts. When the parser and code
  10994. ** generate call themselves recursively, the first part of the structure
  10995. ** is constant but the second part is reset at the beginning and end of
  10996. ** each recursion.
  10997. **
  10998. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10999. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  11000. ** used to store the set of table-locks required by the statement being
  11001. ** compiled. Function sqlite3TableLock() is used to add entries to the
  11002. ** list.
  11003. */
  11004. struct Parse {
  11005. sqlite3 *db; /* The main database structure */
  11006. char *zErrMsg; /* An error message */
  11007. Vdbe *pVdbe; /* An engine for executing database bytecode */
  11008. int rc; /* Return code from execution */
  11009. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  11010. u8 checkSchema; /* Causes schema cookie check after an error */
  11011. u8 nested; /* Number of nested calls to the parser/code generator */
  11012. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  11013. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  11014. u8 nColCache; /* Number of entries in aColCache[] */
  11015. u8 iColCache; /* Next entry in aColCache[] to replace */
  11016. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  11017. u8 mayAbort; /* True if statement may throw an ABORT exception */
  11018. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  11019. int aTempReg[8]; /* Holding area for temporary registers */
  11020. int nRangeReg; /* Size of the temporary register block */
  11021. int iRangeReg; /* First register in temporary register block */
  11022. int nErr; /* Number of errors seen */
  11023. int nTab; /* Number of previously allocated VDBE cursors */
  11024. int nMem; /* Number of memory cells used so far */
  11025. int nSet; /* Number of sets used so far */
  11026. int nOnce; /* Number of OP_Once instructions so far */
  11027. int ckBase; /* Base register of data during check constraints */
  11028. int iPartIdxTab; /* Table corresponding to a partial index */
  11029. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  11030. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  11031. struct yColCache {
  11032. int iTable; /* Table cursor number */
  11033. int iColumn; /* Table column number */
  11034. u8 tempReg; /* iReg is a temp register that needs to be freed */
  11035. int iLevel; /* Nesting level */
  11036. int iReg; /* Reg with value of this column. 0 means none. */
  11037. int lru; /* Least recently used entry has the smallest value */
  11038. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  11039. yDbMask writeMask; /* Start a write transaction on these databases */
  11040. yDbMask cookieMask; /* Bitmask of schema verified databases */
  11041. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  11042. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  11043. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  11044. int regRoot; /* Register holding root page number for new objects */
  11045. int nMaxArg; /* Max args passed to user function by sub-program */
  11046. Token constraintName;/* Name of the constraint currently being parsed */
  11047. #ifndef SQLITE_OMIT_SHARED_CACHE
  11048. int nTableLock; /* Number of locks in aTableLock */
  11049. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  11050. #endif
  11051. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  11052. /* Information used while coding trigger programs. */
  11053. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  11054. Table *pTriggerTab; /* Table triggers are being coded for */
  11055. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  11056. u32 oldmask; /* Mask of old.* columns referenced */
  11057. u32 newmask; /* Mask of new.* columns referenced */
  11058. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11059. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11060. u8 disableTriggers; /* True to disable triggers */
  11061. /* Above is constant between recursions. Below is reset before and after
  11062. ** each recursion */
  11063. int nVar; /* Number of '?' variables seen in the SQL so far */
  11064. int nzVar; /* Number of available slots in azVar[] */
  11065. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11066. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11067. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11068. int nVtabLock; /* Number of virtual tables to lock */
  11069. #endif
  11070. int nAlias; /* Number of aliased result set columns */
  11071. int nHeight; /* Expression tree height of current sub-select */
  11072. #ifndef SQLITE_OMIT_EXPLAIN
  11073. int iSelectId; /* ID of current select for EXPLAIN output */
  11074. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11075. #endif
  11076. char **azVar; /* Pointers to names of parameters */
  11077. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11078. int *aAlias; /* Register used to hold aliased result */
  11079. const char *zTail; /* All SQL text past the last semicolon parsed */
  11080. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11081. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11082. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11083. Token sNameToken; /* Token with unqualified schema object name */
  11084. Token sLastToken; /* The last token parsed */
  11085. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11086. Token sArg; /* Complete text of a module argument */
  11087. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11088. #endif
  11089. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11090. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11091. };
  11092. /*
  11093. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11094. */
  11095. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11096. #define IN_DECLARE_VTAB 0
  11097. #else
  11098. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11099. #endif
  11100. /*
  11101. ** An instance of the following structure can be declared on a stack and used
  11102. ** to save the Parse.zAuthContext value so that it can be restored later.
  11103. */
  11104. struct AuthContext {
  11105. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11106. Parse *pParse; /* The Parse structure */
  11107. };
  11108. /*
  11109. ** Bitfield flags for P5 value in various opcodes.
  11110. */
  11111. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11112. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11113. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11114. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11115. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11116. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  11117. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11118. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11119. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11120. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11121. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11122. /*
  11123. * Each trigger present in the database schema is stored as an instance of
  11124. * struct Trigger.
  11125. *
  11126. * Pointers to instances of struct Trigger are stored in two ways.
  11127. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11128. * database). This allows Trigger structures to be retrieved by name.
  11129. * 2. All triggers associated with a single table form a linked list, using the
  11130. * pNext member of struct Trigger. A pointer to the first element of the
  11131. * linked list is stored as the "pTrigger" member of the associated
  11132. * struct Table.
  11133. *
  11134. * The "step_list" member points to the first element of a linked list
  11135. * containing the SQL statements specified as the trigger program.
  11136. */
  11137. struct Trigger {
  11138. char *zName; /* The name of the trigger */
  11139. char *table; /* The table or view to which the trigger applies */
  11140. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11141. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11142. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11143. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11144. the <column-list> is stored here */
  11145. Schema *pSchema; /* Schema containing the trigger */
  11146. Schema *pTabSchema; /* Schema containing the table */
  11147. TriggerStep *step_list; /* Link list of trigger program steps */
  11148. Trigger *pNext; /* Next trigger associated with the table */
  11149. };
  11150. /*
  11151. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11152. ** determine which.
  11153. **
  11154. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11155. ** In that cases, the constants below can be ORed together.
  11156. */
  11157. #define TRIGGER_BEFORE 1
  11158. #define TRIGGER_AFTER 2
  11159. /*
  11160. * An instance of struct TriggerStep is used to store a single SQL statement
  11161. * that is a part of a trigger-program.
  11162. *
  11163. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11164. * using the "pNext" member) referenced by the "step_list" member of the
  11165. * associated struct Trigger instance. The first element of the linked list is
  11166. * the first step of the trigger-program.
  11167. *
  11168. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11169. * "SELECT" statement. The meanings of the other members is determined by the
  11170. * value of "op" as follows:
  11171. *
  11172. * (op == TK_INSERT)
  11173. * orconf -> stores the ON CONFLICT algorithm
  11174. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11175. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11176. * target -> A token holding the quoted name of the table to insert into.
  11177. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11178. * this stores values to be inserted. Otherwise NULL.
  11179. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11180. * statement, then this stores the column-names to be
  11181. * inserted into.
  11182. *
  11183. * (op == TK_DELETE)
  11184. * target -> A token holding the quoted name of the table to delete from.
  11185. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11186. * Otherwise NULL.
  11187. *
  11188. * (op == TK_UPDATE)
  11189. * target -> A token holding the quoted name of the table to update rows of.
  11190. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11191. * Otherwise NULL.
  11192. * pExprList -> A list of the columns to update and the expressions to update
  11193. * them to. See sqlite3Update() documentation of "pChanges"
  11194. * argument.
  11195. *
  11196. */
  11197. struct TriggerStep {
  11198. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11199. u8 orconf; /* OE_Rollback etc. */
  11200. Trigger *pTrig; /* The trigger that this step is a part of */
  11201. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11202. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11203. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11204. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  11205. IdList *pIdList; /* Column names for INSERT */
  11206. TriggerStep *pNext; /* Next in the link-list */
  11207. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11208. };
  11209. /*
  11210. ** The following structure contains information used by the sqliteFix...
  11211. ** routines as they walk the parse tree to make database references
  11212. ** explicit.
  11213. */
  11214. typedef struct DbFixer DbFixer;
  11215. struct DbFixer {
  11216. Parse *pParse; /* The parsing context. Error messages written here */
  11217. Schema *pSchema; /* Fix items to this schema */
  11218. int bVarOnly; /* Check for variable references only */
  11219. const char *zDb; /* Make sure all objects are contained in this database */
  11220. const char *zType; /* Type of the container - used for error messages */
  11221. const Token *pName; /* Name of the container - used for error messages */
  11222. };
  11223. /*
  11224. ** An objected used to accumulate the text of a string where we
  11225. ** do not necessarily know how big the string will be in the end.
  11226. */
  11227. struct StrAccum {
  11228. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11229. char *zBase; /* A base allocation. Not from malloc. */
  11230. char *zText; /* The string collected so far */
  11231. int nChar; /* Length of the string so far */
  11232. int nAlloc; /* Amount of space allocated in zText */
  11233. int mxAlloc; /* Maximum allowed string length */
  11234. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11235. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11236. };
  11237. #define STRACCUM_NOMEM 1
  11238. #define STRACCUM_TOOBIG 2
  11239. /*
  11240. ** A pointer to this structure is used to communicate information
  11241. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11242. */
  11243. typedef struct {
  11244. sqlite3 *db; /* The database being initialized */
  11245. char **pzErrMsg; /* Error message stored here */
  11246. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11247. int rc; /* Result code stored here */
  11248. } InitData;
  11249. /*
  11250. ** Structure containing global configuration data for the SQLite library.
  11251. **
  11252. ** This structure also contains some state information.
  11253. */
  11254. struct Sqlite3Config {
  11255. int bMemstat; /* True to enable memory status */
  11256. int bCoreMutex; /* True to enable core mutexing */
  11257. int bFullMutex; /* True to enable full mutexing */
  11258. int bOpenUri; /* True to interpret filenames as URIs */
  11259. int bUseCis; /* Use covering indices for full-scans */
  11260. int mxStrlen; /* Maximum string length */
  11261. int szLookaside; /* Default lookaside buffer size */
  11262. int nLookaside; /* Default lookaside buffer count */
  11263. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11264. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11265. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11266. void *pHeap; /* Heap storage space */
  11267. int nHeap; /* Size of pHeap[] */
  11268. int mnReq, mxReq; /* Min and max heap requests sizes */
  11269. sqlite3_int64 szMmap; /* mmap() space per open file */
  11270. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11271. void *pScratch; /* Scratch memory */
  11272. int szScratch; /* Size of each scratch buffer */
  11273. int nScratch; /* Number of scratch buffers */
  11274. void *pPage; /* Page cache memory */
  11275. int szPage; /* Size of each page in pPage[] */
  11276. int nPage; /* Number of pages in pPage[] */
  11277. int mxParserStack; /* maximum depth of the parser stack */
  11278. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11279. /* The above might be initialized to non-zero. The following need to always
  11280. ** initially be zero, however. */
  11281. int isInit; /* True after initialization has finished */
  11282. int inProgress; /* True while initialization in progress */
  11283. int isMutexInit; /* True after mutexes are initialized */
  11284. int isMallocInit; /* True after malloc is initialized */
  11285. int isPCacheInit; /* True after malloc is initialized */
  11286. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11287. int nRefInitMutex; /* Number of users of pInitMutex */
  11288. void (*xLog)(void*,int,const char*); /* Function for logging */
  11289. void *pLogArg; /* First argument to xLog() */
  11290. int bLocaltimeFault; /* True to fail localtime() calls */
  11291. #ifdef SQLITE_ENABLE_SQLLOG
  11292. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11293. void *pSqllogArg;
  11294. #endif
  11295. };
  11296. /*
  11297. ** Context pointer passed down through the tree-walk.
  11298. */
  11299. struct Walker {
  11300. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11301. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11302. Parse *pParse; /* Parser context. */
  11303. int walkerDepth; /* Number of subqueries */
  11304. u8 bSelectDepthFirst; /* Do subqueries first */
  11305. union { /* Extra data for callback */
  11306. NameContext *pNC; /* Naming context */
  11307. int i; /* Integer value */
  11308. SrcList *pSrcList; /* FROM clause */
  11309. struct SrcCount *pSrcCount; /* Counting column references */
  11310. } u;
  11311. };
  11312. /* Forward declarations */
  11313. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11314. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11315. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11316. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11317. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11318. /*
  11319. ** Return code from the parse-tree walking primitives and their
  11320. ** callbacks.
  11321. */
  11322. #define WRC_Continue 0 /* Continue down into children */
  11323. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11324. #define WRC_Abort 2 /* Abandon the tree walk */
  11325. /*
  11326. ** Assuming zIn points to the first byte of a UTF-8 character,
  11327. ** advance zIn to point to the first byte of the next UTF-8 character.
  11328. */
  11329. #define SQLITE_SKIP_UTF8(zIn) { \
  11330. if( (*(zIn++))>=0xc0 ){ \
  11331. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11332. } \
  11333. }
  11334. /*
  11335. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11336. ** the same name but without the _BKPT suffix. These macros invoke
  11337. ** routines that report the line-number on which the error originated
  11338. ** using sqlite3_log(). The routines also provide a convenient place
  11339. ** to set a debugger breakpoint.
  11340. */
  11341. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11342. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11343. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11344. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11345. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11346. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11347. /*
  11348. ** FTS4 is really an extension for FTS3. It is enabled using the
  11349. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11350. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11351. */
  11352. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11353. # define SQLITE_ENABLE_FTS3
  11354. #endif
  11355. /*
  11356. ** The ctype.h header is needed for non-ASCII systems. It is also
  11357. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11358. */
  11359. #if !defined(SQLITE_ASCII) || \
  11360. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11361. # include <ctype.h>
  11362. #endif
  11363. /*
  11364. ** The following macros mimic the standard library functions toupper(),
  11365. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11366. ** sqlite versions only work for ASCII characters, regardless of locale.
  11367. */
  11368. #ifdef SQLITE_ASCII
  11369. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11370. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11371. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11372. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11373. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11374. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11375. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11376. #else
  11377. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11378. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11379. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11380. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11381. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11382. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11383. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11384. #endif
  11385. /*
  11386. ** Internal function prototypes
  11387. */
  11388. #define sqlite3StrICmp sqlite3_stricmp
  11389. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11390. #define sqlite3StrNICmp sqlite3_strnicmp
  11391. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11392. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11393. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11394. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11395. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11396. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11397. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11398. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11399. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11400. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11401. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11402. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11403. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11404. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11405. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11406. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11407. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11408. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11409. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11410. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11411. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11412. /*
  11413. ** On systems with ample stack space and that support alloca(), make
  11414. ** use of alloca() to obtain space for large automatic objects. By default,
  11415. ** obtain space from malloc().
  11416. **
  11417. ** The alloca() routine never returns NULL. This will cause code paths
  11418. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11419. */
  11420. #ifdef SQLITE_USE_ALLOCA
  11421. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11422. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11423. # define sqlite3StackFree(D,P)
  11424. #else
  11425. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11426. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11427. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11428. #endif
  11429. #ifdef SQLITE_ENABLE_MEMSYS3
  11430. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11431. #endif
  11432. #ifdef SQLITE_ENABLE_MEMSYS5
  11433. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11434. #endif
  11435. #ifndef SQLITE_MUTEX_OMIT
  11436. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11437. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11438. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11439. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11440. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11441. #endif
  11442. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11443. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11444. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11445. #ifndef SQLITE_OMIT_FLOATING_POINT
  11446. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11447. #else
  11448. # define sqlite3IsNaN(X) 0
  11449. #endif
  11450. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11451. #ifndef SQLITE_OMIT_TRACE
  11452. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11453. #endif
  11454. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11455. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11456. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11457. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11458. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11459. #endif
  11460. #if defined(SQLITE_TEST)
  11461. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11462. #endif
  11463. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11464. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11465. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11466. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11467. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11468. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11469. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11470. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11471. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11472. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11473. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11474. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11475. #else
  11476. # define sqlite3ExplainBegin(X)
  11477. # define sqlite3ExplainSelect(A,B)
  11478. # define sqlite3ExplainExpr(A,B)
  11479. # define sqlite3ExplainExprList(A,B)
  11480. # define sqlite3ExplainFinish(X)
  11481. # define sqlite3VdbeExplanation(X) 0
  11482. #endif
  11483. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11484. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11485. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11486. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11487. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11488. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11489. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11490. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11491. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11492. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11493. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11494. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11495. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11496. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11497. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11498. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11499. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11500. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11501. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11502. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11503. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11504. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11505. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11506. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11507. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11508. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11509. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11510. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11511. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11512. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11513. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11514. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11515. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11516. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11517. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11518. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11519. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11520. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11521. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11522. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11523. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11524. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11525. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11526. sqlite3_vfs**,char**,char **);
  11527. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11528. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11529. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11530. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11531. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11532. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11533. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11534. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11535. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11536. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11537. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11538. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11539. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11540. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11541. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11542. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11543. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11544. #else
  11545. # define sqlite3ViewGetColumnNames(A,B) 0
  11546. #endif
  11547. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11548. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11549. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11550. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11551. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11552. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11553. #else
  11554. # define sqlite3AutoincrementBegin(X)
  11555. # define sqlite3AutoincrementEnd(X)
  11556. #endif
  11557. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11558. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11559. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11560. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11561. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11562. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11563. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11564. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11565. Token*, Select*, Expr*, IdList*);
  11566. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11567. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11568. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11569. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11570. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11571. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11572. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11573. Expr*, int, int);
  11574. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11575. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11576. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11577. Expr*,ExprList*,u16,Expr*,Expr*);
  11578. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11579. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11580. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11581. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11582. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11583. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  11584. #endif
  11585. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11586. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11587. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11588. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11589. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  11590. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  11591. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  11592. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  11593. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  11594. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
  11595. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11596. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11597. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11598. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11599. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11600. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11601. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11602. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11603. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11604. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11605. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11606. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11607. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11608. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11609. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11610. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11611. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11612. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11613. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11614. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11615. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11616. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11617. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11618. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11619. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11620. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11621. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  11622. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  11623. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  11624. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11625. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11626. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11627. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11628. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11629. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11630. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11631. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11632. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11633. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11634. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11635. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11636. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11637. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11638. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11639. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11640. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11641. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11642. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11643. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11644. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11645. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11646. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11647. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11648. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11649. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11650. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  11651. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11652. int*,int,int,int,int,int*);
  11653. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11654. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11655. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11656. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11657. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11658. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  11659. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11660. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11661. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11662. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11663. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11664. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11665. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11666. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11667. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11668. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11669. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11670. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11671. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11672. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11673. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11674. #endif
  11675. #ifndef SQLITE_OMIT_TRIGGER
  11676. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11677. Expr*,int, int);
  11678. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11679. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11680. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11681. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11682. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11683. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11684. int, int, int);
  11685. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11686. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11687. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11688. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11689. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11690. ExprList*,Select*,u8);
  11691. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11692. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11693. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11694. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11695. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11696. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11697. #else
  11698. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11699. # define sqlite3DeleteTrigger(A,B)
  11700. # define sqlite3DropTriggerPtr(A,B)
  11701. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11702. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11703. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11704. # define sqlite3TriggerList(X, Y) 0
  11705. # define sqlite3ParseToplevel(p) p
  11706. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11707. #endif
  11708. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11709. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11710. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11711. #ifndef SQLITE_OMIT_AUTHORIZATION
  11712. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11713. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11714. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11715. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11716. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11717. #else
  11718. # define sqlite3AuthRead(a,b,c,d)
  11719. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11720. # define sqlite3AuthContextPush(a,b,c)
  11721. # define sqlite3AuthContextPop(a) ((void)(a))
  11722. #endif
  11723. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11724. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11725. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11726. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11727. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11728. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11729. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11730. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11731. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11732. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11733. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11734. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11735. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11736. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11737. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  11738. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  11739. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11740. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  11741. #endif
  11742. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  11743. /*
  11744. ** Routines to read and write variable-length integers. These used to
  11745. ** be defined locally, but now we use the varint routines in the util.c
  11746. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11747. ** are coded to assume the single byte case is already handled (which
  11748. ** the MACRO form does).
  11749. */
  11750. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11751. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11752. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11753. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11754. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11755. /*
  11756. ** The header of a record consists of a sequence variable-length integers.
  11757. ** These integers are almost always small and are encoded as a single byte.
  11758. ** The following macros take advantage this fact to provide a fast encode
  11759. ** and decode of the integers in a record header. It is faster for the common
  11760. ** case where the integer is a single byte. It is a little slower when the
  11761. ** integer is two or more bytes. But overall it is faster.
  11762. **
  11763. ** The following expressions are equivalent:
  11764. **
  11765. ** x = sqlite3GetVarint32( A, &B );
  11766. ** x = sqlite3PutVarint32( A, B );
  11767. **
  11768. ** x = getVarint32( A, B );
  11769. ** x = putVarint32( A, B );
  11770. **
  11771. */
  11772. #define getVarint32(A,B) \
  11773. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  11774. #define putVarint32(A,B) \
  11775. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  11776. sqlite3PutVarint32((A),(B)))
  11777. #define getVarint sqlite3GetVarint
  11778. #define putVarint sqlite3PutVarint
  11779. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11780. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11781. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11782. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11783. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11784. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11785. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11786. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11787. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11788. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11789. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  11790. defined(SQLITE_DEBUG_OS_TRACE)
  11791. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  11792. #endif
  11793. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11794. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11795. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11796. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11797. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11798. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11799. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11800. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11801. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11802. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11803. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11804. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11805. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11806. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11807. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11808. #ifdef SQLITE_ENABLE_8_3_NAMES
  11809. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11810. #else
  11811. # define sqlite3FileSuffix3(X,Y)
  11812. #endif
  11813. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11814. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11815. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11816. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11817. void(*)(void*));
  11818. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11819. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11820. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11821. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11822. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11823. #ifndef SQLITE_AMALGAMATION
  11824. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11825. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11826. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11827. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11828. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11829. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11830. #ifndef SQLITE_OMIT_WSD
  11831. SQLITE_PRIVATE int sqlite3PendingByte;
  11832. #endif
  11833. #endif
  11834. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11835. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11836. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11837. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11838. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11839. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11840. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11841. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11842. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11843. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  11844. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11845. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11846. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  11847. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11848. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11849. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11850. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11851. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11852. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  11853. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11854. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11855. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11856. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11857. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11858. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11859. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11860. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11861. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11862. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11863. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11864. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11865. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11866. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  11867. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11868. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11869. void (*)(sqlite3_context*,int,sqlite3_value **),
  11870. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11871. FuncDestructor *pDestructor
  11872. );
  11873. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11874. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11875. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11876. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11877. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11878. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11879. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11880. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11881. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11882. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11883. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11884. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11885. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  11886. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  11887. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  11888. #endif
  11889. /*
  11890. ** The interface to the LEMON-generated parser
  11891. */
  11892. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11893. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11894. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11895. #ifdef YYTRACKMAXSTACKDEPTH
  11896. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11897. #endif
  11898. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11899. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11900. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11901. #else
  11902. # define sqlite3CloseExtensions(X)
  11903. #endif
  11904. #ifndef SQLITE_OMIT_SHARED_CACHE
  11905. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11906. #else
  11907. #define sqlite3TableLock(v,w,x,y,z)
  11908. #endif
  11909. #ifdef SQLITE_TEST
  11910. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11911. #endif
  11912. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11913. # define sqlite3VtabClear(Y)
  11914. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11915. # define sqlite3VtabRollback(X)
  11916. # define sqlite3VtabCommit(X)
  11917. # define sqlite3VtabInSync(db) 0
  11918. # define sqlite3VtabLock(X)
  11919. # define sqlite3VtabUnlock(X)
  11920. # define sqlite3VtabUnlockList(X)
  11921. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11922. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11923. #else
  11924. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11925. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11926. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  11927. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11928. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11929. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11930. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11931. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11932. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11933. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  11934. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11935. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11936. #endif
  11937. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11938. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11939. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11940. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11941. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11942. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11943. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11944. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11945. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11946. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11947. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11948. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  11949. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11950. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11951. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11952. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11953. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11954. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11955. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11956. #ifndef SQLITE_OMIT_WAL
  11957. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11958. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11959. #endif
  11960. /* Declarations for functions in fkey.c. All of these are replaced by
  11961. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11962. ** key functionality is available. If OMIT_TRIGGER is defined but
  11963. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11964. ** this case foreign keys are parsed, but no other functionality is
  11965. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11966. */
  11967. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11968. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  11969. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11970. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  11971. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11972. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11973. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11974. #else
  11975. #define sqlite3FkActions(a,b,c,d,e,f)
  11976. #define sqlite3FkCheck(a,b,c,d,e,f)
  11977. #define sqlite3FkDropTable(a,b,c)
  11978. #define sqlite3FkOldmask(a,b) 0
  11979. #define sqlite3FkRequired(a,b,c,d) 0
  11980. #endif
  11981. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11982. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11983. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  11984. #else
  11985. #define sqlite3FkDelete(a,b)
  11986. #define sqlite3FkLocateIndex(a,b,c,d,e)
  11987. #endif
  11988. /*
  11989. ** Available fault injectors. Should be numbered beginning with 0.
  11990. */
  11991. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11992. #define SQLITE_FAULTINJECTOR_COUNT 1
  11993. /*
  11994. ** The interface to the code in fault.c used for identifying "benign"
  11995. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11996. ** is not defined.
  11997. */
  11998. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11999. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  12000. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  12001. #else
  12002. #define sqlite3BeginBenignMalloc()
  12003. #define sqlite3EndBenignMalloc()
  12004. #endif
  12005. #define IN_INDEX_ROWID 1
  12006. #define IN_INDEX_EPH 2
  12007. #define IN_INDEX_INDEX_ASC 3
  12008. #define IN_INDEX_INDEX_DESC 4
  12009. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  12010. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12011. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  12012. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  12013. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  12014. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  12015. #else
  12016. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  12017. #define sqlite3JournalExists(p) 1
  12018. #endif
  12019. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  12020. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  12021. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  12022. #if SQLITE_MAX_EXPR_DEPTH>0
  12023. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  12024. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  12025. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  12026. #else
  12027. #define sqlite3ExprSetHeight(x,y)
  12028. #define sqlite3SelectExprHeight(x) 0
  12029. #define sqlite3ExprCheckHeight(x,y)
  12030. #endif
  12031. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  12032. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  12033. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12034. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  12035. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  12036. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  12037. #else
  12038. #define sqlite3ConnectionBlocked(x,y)
  12039. #define sqlite3ConnectionUnlocked(x)
  12040. #define sqlite3ConnectionClosed(x)
  12041. #endif
  12042. #ifdef SQLITE_DEBUG
  12043. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  12044. #endif
  12045. /*
  12046. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  12047. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  12048. ** print I/O tracing messages.
  12049. */
  12050. #ifdef SQLITE_ENABLE_IOTRACE
  12051. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  12052. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  12053. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  12054. #else
  12055. # define IOTRACE(A)
  12056. # define sqlite3VdbeIOTraceSql(X)
  12057. #endif
  12058. /*
  12059. ** These routines are available for the mem2.c debugging memory allocator
  12060. ** only. They are used to verify that different "types" of memory
  12061. ** allocations are properly tracked by the system.
  12062. **
  12063. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12064. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12065. ** a single bit set.
  12066. **
  12067. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12068. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12069. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12070. **
  12071. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12072. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12073. **
  12074. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12075. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12076. ** it might have been allocated by lookaside, except the allocation was
  12077. ** too large or lookaside was already full. It is important to verify
  12078. ** that allocations that might have been satisfied by lookaside are not
  12079. ** passed back to non-lookaside free() routines. Asserts such as the
  12080. ** example above are placed on the non-lookaside free() routines to verify
  12081. ** this constraint.
  12082. **
  12083. ** All of this is no-op for a production build. It only comes into
  12084. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12085. */
  12086. #ifdef SQLITE_MEMDEBUG
  12087. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12088. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12089. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12090. #else
  12091. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12092. # define sqlite3MemdebugHasType(X,Y) 1
  12093. # define sqlite3MemdebugNoType(X,Y) 1
  12094. #endif
  12095. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12096. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  12097. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12098. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12099. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  12100. #endif /* _SQLITEINT_H_ */
  12101. /************** End of sqliteInt.h *******************************************/
  12102. /************** Begin file global.c ******************************************/
  12103. /*
  12104. ** 2008 June 13
  12105. **
  12106. ** The author disclaims copyright to this source code. In place of
  12107. ** a legal notice, here is a blessing:
  12108. **
  12109. ** May you do good and not evil.
  12110. ** May you find forgiveness for yourself and forgive others.
  12111. ** May you share freely, never taking more than you give.
  12112. **
  12113. *************************************************************************
  12114. **
  12115. ** This file contains definitions of global variables and contants.
  12116. */
  12117. /* An array to map all upper-case characters into their corresponding
  12118. ** lower-case character.
  12119. **
  12120. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12121. ** handle case conversions for the UTF character set since the tables
  12122. ** involved are nearly as big or bigger than SQLite itself.
  12123. */
  12124. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12125. #ifdef SQLITE_ASCII
  12126. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12127. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12128. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12129. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12130. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12131. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12132. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12133. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12134. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12135. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12136. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12137. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12138. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12139. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12140. 252,253,254,255
  12141. #endif
  12142. #ifdef SQLITE_EBCDIC
  12143. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12144. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12145. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12146. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12147. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12148. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12149. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12150. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12151. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12152. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12153. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12154. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12155. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12156. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12157. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12158. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12159. #endif
  12160. };
  12161. /*
  12162. ** The following 256 byte lookup table is used to support SQLites built-in
  12163. ** equivalents to the following standard library functions:
  12164. **
  12165. ** isspace() 0x01
  12166. ** isalpha() 0x02
  12167. ** isdigit() 0x04
  12168. ** isalnum() 0x06
  12169. ** isxdigit() 0x08
  12170. ** toupper() 0x20
  12171. ** SQLite identifier character 0x40
  12172. **
  12173. ** Bit 0x20 is set if the mapped character requires translation to upper
  12174. ** case. i.e. if the character is a lower-case ASCII character.
  12175. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12176. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12177. **
  12178. ** (x & ~(map[x]&0x20))
  12179. **
  12180. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12181. ** array. tolower() is used more often than toupper() by SQLite.
  12182. **
  12183. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12184. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12185. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12186. ** part of an identifier is 0x46.
  12187. **
  12188. ** SQLite's versions are identical to the standard versions assuming a
  12189. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12190. */
  12191. #ifdef SQLITE_ASCII
  12192. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12193. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12194. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12195. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12196. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12197. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12198. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12199. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12200. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12201. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12202. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12203. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12204. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12205. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12206. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12207. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12208. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12209. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12210. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12211. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12212. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12213. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12214. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12215. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12216. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12217. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12218. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12219. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12220. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12221. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12222. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12223. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12224. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12225. };
  12226. #endif
  12227. #ifndef SQLITE_USE_URI
  12228. # define SQLITE_USE_URI 0
  12229. #endif
  12230. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12231. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12232. #endif
  12233. /*
  12234. ** The following singleton contains the global configuration for
  12235. ** the SQLite library.
  12236. */
  12237. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12238. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12239. 1, /* bCoreMutex */
  12240. SQLITE_THREADSAFE==1, /* bFullMutex */
  12241. SQLITE_USE_URI, /* bOpenUri */
  12242. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12243. 0x7ffffffe, /* mxStrlen */
  12244. 128, /* szLookaside */
  12245. 500, /* nLookaside */
  12246. {0,0,0,0,0,0,0,0}, /* m */
  12247. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12248. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12249. (void*)0, /* pHeap */
  12250. 0, /* nHeap */
  12251. 0, 0, /* mnHeap, mxHeap */
  12252. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12253. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12254. (void*)0, /* pScratch */
  12255. 0, /* szScratch */
  12256. 0, /* nScratch */
  12257. (void*)0, /* pPage */
  12258. 0, /* szPage */
  12259. 0, /* nPage */
  12260. 0, /* mxParserStack */
  12261. 0, /* sharedCacheEnabled */
  12262. /* All the rest should always be initialized to zero */
  12263. 0, /* isInit */
  12264. 0, /* inProgress */
  12265. 0, /* isMutexInit */
  12266. 0, /* isMallocInit */
  12267. 0, /* isPCacheInit */
  12268. 0, /* pInitMutex */
  12269. 0, /* nRefInitMutex */
  12270. 0, /* xLog */
  12271. 0, /* pLogArg */
  12272. 0, /* bLocaltimeFault */
  12273. #ifdef SQLITE_ENABLE_SQLLOG
  12274. 0, /* xSqllog */
  12275. 0 /* pSqllogArg */
  12276. #endif
  12277. };
  12278. /*
  12279. ** Hash table for global functions - functions common to all
  12280. ** database connections. After initialization, this table is
  12281. ** read-only.
  12282. */
  12283. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12284. /*
  12285. ** Constant tokens for values 0 and 1.
  12286. */
  12287. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12288. { "0", 1 },
  12289. { "1", 1 }
  12290. };
  12291. /*
  12292. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12293. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12294. ** the database page that contains the pending byte. It never attempts
  12295. ** to read or write that page. The pending byte page is set assign
  12296. ** for use by the VFS layers as space for managing file locks.
  12297. **
  12298. ** During testing, it is often desirable to move the pending byte to
  12299. ** a different position in the file. This allows code that has to
  12300. ** deal with the pending byte to run on files that are much smaller
  12301. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12302. ** move the pending byte.
  12303. **
  12304. ** IMPORTANT: Changing the pending byte to any value other than
  12305. ** 0x40000000 results in an incompatible database file format!
  12306. ** Changing the pending byte during operating results in undefined
  12307. ** and dileterious behavior.
  12308. */
  12309. #ifndef SQLITE_OMIT_WSD
  12310. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12311. #endif
  12312. /*
  12313. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12314. ** created by mkopcodeh.awk during compilation. Data is obtained
  12315. ** from the comments following the "case OP_xxxx:" statements in
  12316. ** the vdbe.c file.
  12317. */
  12318. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12319. /************** End of global.c **********************************************/
  12320. /************** Begin file ctime.c *******************************************/
  12321. /*
  12322. ** 2010 February 23
  12323. **
  12324. ** The author disclaims copyright to this source code. In place of
  12325. ** a legal notice, here is a blessing:
  12326. **
  12327. ** May you do good and not evil.
  12328. ** May you find forgiveness for yourself and forgive others.
  12329. ** May you share freely, never taking more than you give.
  12330. **
  12331. *************************************************************************
  12332. **
  12333. ** This file implements routines used to report what compile-time options
  12334. ** SQLite was built with.
  12335. */
  12336. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12337. /*
  12338. ** An array of names of all compile-time options. This array should
  12339. ** be sorted A-Z.
  12340. **
  12341. ** This array looks large, but in a typical installation actually uses
  12342. ** only a handful of compile-time options, so most times this array is usually
  12343. ** rather short and uses little memory space.
  12344. */
  12345. static const char * const azCompileOpt[] = {
  12346. /* These macros are provided to "stringify" the value of the define
  12347. ** for those options in which the value is meaningful. */
  12348. #define CTIMEOPT_VAL_(opt) #opt
  12349. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12350. #ifdef SQLITE_32BIT_ROWID
  12351. "32BIT_ROWID",
  12352. #endif
  12353. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12354. "4_BYTE_ALIGNED_MALLOC",
  12355. #endif
  12356. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12357. "CASE_SENSITIVE_LIKE",
  12358. #endif
  12359. #ifdef SQLITE_CHECK_PAGES
  12360. "CHECK_PAGES",
  12361. #endif
  12362. #ifdef SQLITE_COVERAGE_TEST
  12363. "COVERAGE_TEST",
  12364. #endif
  12365. #ifdef SQLITE_DEBUG
  12366. "DEBUG",
  12367. #endif
  12368. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12369. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12370. #endif
  12371. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  12372. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  12373. #endif
  12374. #ifdef SQLITE_DISABLE_DIRSYNC
  12375. "DISABLE_DIRSYNC",
  12376. #endif
  12377. #ifdef SQLITE_DISABLE_LFS
  12378. "DISABLE_LFS",
  12379. #endif
  12380. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12381. "ENABLE_ATOMIC_WRITE",
  12382. #endif
  12383. #ifdef SQLITE_ENABLE_CEROD
  12384. "ENABLE_CEROD",
  12385. #endif
  12386. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12387. "ENABLE_COLUMN_METADATA",
  12388. #endif
  12389. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12390. "ENABLE_EXPENSIVE_ASSERT",
  12391. #endif
  12392. #ifdef SQLITE_ENABLE_FTS1
  12393. "ENABLE_FTS1",
  12394. #endif
  12395. #ifdef SQLITE_ENABLE_FTS2
  12396. "ENABLE_FTS2",
  12397. #endif
  12398. #ifdef SQLITE_ENABLE_FTS3
  12399. "ENABLE_FTS3",
  12400. #endif
  12401. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12402. "ENABLE_FTS3_PARENTHESIS",
  12403. #endif
  12404. #ifdef SQLITE_ENABLE_FTS4
  12405. "ENABLE_FTS4",
  12406. #endif
  12407. #ifdef SQLITE_ENABLE_ICU
  12408. "ENABLE_ICU",
  12409. #endif
  12410. #ifdef SQLITE_ENABLE_IOTRACE
  12411. "ENABLE_IOTRACE",
  12412. #endif
  12413. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12414. "ENABLE_LOAD_EXTENSION",
  12415. #endif
  12416. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12417. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12418. #endif
  12419. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12420. "ENABLE_MEMORY_MANAGEMENT",
  12421. #endif
  12422. #ifdef SQLITE_ENABLE_MEMSYS3
  12423. "ENABLE_MEMSYS3",
  12424. #endif
  12425. #ifdef SQLITE_ENABLE_MEMSYS5
  12426. "ENABLE_MEMSYS5",
  12427. #endif
  12428. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12429. "ENABLE_OVERSIZE_CELL_CHECK",
  12430. #endif
  12431. #ifdef SQLITE_ENABLE_RTREE
  12432. "ENABLE_RTREE",
  12433. #endif
  12434. #if defined(SQLITE_ENABLE_STAT4)
  12435. "ENABLE_STAT4",
  12436. #elif defined(SQLITE_ENABLE_STAT3)
  12437. "ENABLE_STAT3",
  12438. #endif
  12439. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12440. "ENABLE_UNLOCK_NOTIFY",
  12441. #endif
  12442. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12443. "ENABLE_UPDATE_DELETE_LIMIT",
  12444. #endif
  12445. #ifdef SQLITE_HAS_CODEC
  12446. "HAS_CODEC",
  12447. #endif
  12448. #ifdef SQLITE_HAVE_ISNAN
  12449. "HAVE_ISNAN",
  12450. #endif
  12451. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12452. "HOMEGROWN_RECURSIVE_MUTEX",
  12453. #endif
  12454. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12455. "IGNORE_AFP_LOCK_ERRORS",
  12456. #endif
  12457. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12458. "IGNORE_FLOCK_LOCK_ERRORS",
  12459. #endif
  12460. #ifdef SQLITE_INT64_TYPE
  12461. "INT64_TYPE",
  12462. #endif
  12463. #ifdef SQLITE_LOCK_TRACE
  12464. "LOCK_TRACE",
  12465. #endif
  12466. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  12467. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  12468. #endif
  12469. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12470. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12471. #endif
  12472. #ifdef SQLITE_MEMDEBUG
  12473. "MEMDEBUG",
  12474. #endif
  12475. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12476. "MIXED_ENDIAN_64BIT_FLOAT",
  12477. #endif
  12478. #ifdef SQLITE_NO_SYNC
  12479. "NO_SYNC",
  12480. #endif
  12481. #ifdef SQLITE_OMIT_ALTERTABLE
  12482. "OMIT_ALTERTABLE",
  12483. #endif
  12484. #ifdef SQLITE_OMIT_ANALYZE
  12485. "OMIT_ANALYZE",
  12486. #endif
  12487. #ifdef SQLITE_OMIT_ATTACH
  12488. "OMIT_ATTACH",
  12489. #endif
  12490. #ifdef SQLITE_OMIT_AUTHORIZATION
  12491. "OMIT_AUTHORIZATION",
  12492. #endif
  12493. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12494. "OMIT_AUTOINCREMENT",
  12495. #endif
  12496. #ifdef SQLITE_OMIT_AUTOINIT
  12497. "OMIT_AUTOINIT",
  12498. #endif
  12499. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12500. "OMIT_AUTOMATIC_INDEX",
  12501. #endif
  12502. #ifdef SQLITE_OMIT_AUTORESET
  12503. "OMIT_AUTORESET",
  12504. #endif
  12505. #ifdef SQLITE_OMIT_AUTOVACUUM
  12506. "OMIT_AUTOVACUUM",
  12507. #endif
  12508. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12509. "OMIT_BETWEEN_OPTIMIZATION",
  12510. #endif
  12511. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12512. "OMIT_BLOB_LITERAL",
  12513. #endif
  12514. #ifdef SQLITE_OMIT_BTREECOUNT
  12515. "OMIT_BTREECOUNT",
  12516. #endif
  12517. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12518. "OMIT_BUILTIN_TEST",
  12519. #endif
  12520. #ifdef SQLITE_OMIT_CAST
  12521. "OMIT_CAST",
  12522. #endif
  12523. #ifdef SQLITE_OMIT_CHECK
  12524. "OMIT_CHECK",
  12525. #endif
  12526. #ifdef SQLITE_OMIT_COMPLETE
  12527. "OMIT_COMPLETE",
  12528. #endif
  12529. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12530. "OMIT_COMPOUND_SELECT",
  12531. #endif
  12532. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12533. "OMIT_DATETIME_FUNCS",
  12534. #endif
  12535. #ifdef SQLITE_OMIT_DECLTYPE
  12536. "OMIT_DECLTYPE",
  12537. #endif
  12538. #ifdef SQLITE_OMIT_DEPRECATED
  12539. "OMIT_DEPRECATED",
  12540. #endif
  12541. #ifdef SQLITE_OMIT_DISKIO
  12542. "OMIT_DISKIO",
  12543. #endif
  12544. #ifdef SQLITE_OMIT_EXPLAIN
  12545. "OMIT_EXPLAIN",
  12546. #endif
  12547. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12548. "OMIT_FLAG_PRAGMAS",
  12549. #endif
  12550. #ifdef SQLITE_OMIT_FLOATING_POINT
  12551. "OMIT_FLOATING_POINT",
  12552. #endif
  12553. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12554. "OMIT_FOREIGN_KEY",
  12555. #endif
  12556. #ifdef SQLITE_OMIT_GET_TABLE
  12557. "OMIT_GET_TABLE",
  12558. #endif
  12559. #ifdef SQLITE_OMIT_INCRBLOB
  12560. "OMIT_INCRBLOB",
  12561. #endif
  12562. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12563. "OMIT_INTEGRITY_CHECK",
  12564. #endif
  12565. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12566. "OMIT_LIKE_OPTIMIZATION",
  12567. #endif
  12568. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12569. "OMIT_LOAD_EXTENSION",
  12570. #endif
  12571. #ifdef SQLITE_OMIT_LOCALTIME
  12572. "OMIT_LOCALTIME",
  12573. #endif
  12574. #ifdef SQLITE_OMIT_LOOKASIDE
  12575. "OMIT_LOOKASIDE",
  12576. #endif
  12577. #ifdef SQLITE_OMIT_MEMORYDB
  12578. "OMIT_MEMORYDB",
  12579. #endif
  12580. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12581. "OMIT_OR_OPTIMIZATION",
  12582. #endif
  12583. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12584. "OMIT_PAGER_PRAGMAS",
  12585. #endif
  12586. #ifdef SQLITE_OMIT_PRAGMA
  12587. "OMIT_PRAGMA",
  12588. #endif
  12589. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12590. "OMIT_PROGRESS_CALLBACK",
  12591. #endif
  12592. #ifdef SQLITE_OMIT_QUICKBALANCE
  12593. "OMIT_QUICKBALANCE",
  12594. #endif
  12595. #ifdef SQLITE_OMIT_REINDEX
  12596. "OMIT_REINDEX",
  12597. #endif
  12598. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12599. "OMIT_SCHEMA_PRAGMAS",
  12600. #endif
  12601. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12602. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12603. #endif
  12604. #ifdef SQLITE_OMIT_SHARED_CACHE
  12605. "OMIT_SHARED_CACHE",
  12606. #endif
  12607. #ifdef SQLITE_OMIT_SUBQUERY
  12608. "OMIT_SUBQUERY",
  12609. #endif
  12610. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12611. "OMIT_TCL_VARIABLE",
  12612. #endif
  12613. #ifdef SQLITE_OMIT_TEMPDB
  12614. "OMIT_TEMPDB",
  12615. #endif
  12616. #ifdef SQLITE_OMIT_TRACE
  12617. "OMIT_TRACE",
  12618. #endif
  12619. #ifdef SQLITE_OMIT_TRIGGER
  12620. "OMIT_TRIGGER",
  12621. #endif
  12622. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12623. "OMIT_TRUNCATE_OPTIMIZATION",
  12624. #endif
  12625. #ifdef SQLITE_OMIT_UTF16
  12626. "OMIT_UTF16",
  12627. #endif
  12628. #ifdef SQLITE_OMIT_VACUUM
  12629. "OMIT_VACUUM",
  12630. #endif
  12631. #ifdef SQLITE_OMIT_VIEW
  12632. "OMIT_VIEW",
  12633. #endif
  12634. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12635. "OMIT_VIRTUALTABLE",
  12636. #endif
  12637. #ifdef SQLITE_OMIT_WAL
  12638. "OMIT_WAL",
  12639. #endif
  12640. #ifdef SQLITE_OMIT_WSD
  12641. "OMIT_WSD",
  12642. #endif
  12643. #ifdef SQLITE_OMIT_XFER_OPT
  12644. "OMIT_XFER_OPT",
  12645. #endif
  12646. #ifdef SQLITE_PERFORMANCE_TRACE
  12647. "PERFORMANCE_TRACE",
  12648. #endif
  12649. #ifdef SQLITE_PROXY_DEBUG
  12650. "PROXY_DEBUG",
  12651. #endif
  12652. #ifdef SQLITE_RTREE_INT_ONLY
  12653. "RTREE_INT_ONLY",
  12654. #endif
  12655. #ifdef SQLITE_SECURE_DELETE
  12656. "SECURE_DELETE",
  12657. #endif
  12658. #ifdef SQLITE_SMALL_STACK
  12659. "SMALL_STACK",
  12660. #endif
  12661. #ifdef SQLITE_SOUNDEX
  12662. "SOUNDEX",
  12663. #endif
  12664. #ifdef SQLITE_TCL
  12665. "TCL",
  12666. #endif
  12667. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  12668. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12669. #endif
  12670. #ifdef SQLITE_TEST
  12671. "TEST",
  12672. #endif
  12673. #if defined(SQLITE_THREADSAFE)
  12674. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12675. #endif
  12676. #ifdef SQLITE_USE_ALLOCA
  12677. "USE_ALLOCA",
  12678. #endif
  12679. #ifdef SQLITE_ZERO_MALLOC
  12680. "ZERO_MALLOC"
  12681. #endif
  12682. };
  12683. /*
  12684. ** Given the name of a compile-time option, return true if that option
  12685. ** was used and false if not.
  12686. **
  12687. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12688. ** is not required for a match.
  12689. */
  12690. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12691. int i, n;
  12692. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12693. n = sqlite3Strlen30(zOptName);
  12694. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12695. ** linear search is adequate. No need for a binary search. */
  12696. for(i=0; i<ArraySize(azCompileOpt); i++){
  12697. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  12698. && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
  12699. ){
  12700. return 1;
  12701. }
  12702. }
  12703. return 0;
  12704. }
  12705. /*
  12706. ** Return the N-th compile-time option string. If N is out of range,
  12707. ** return a NULL pointer.
  12708. */
  12709. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12710. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12711. return azCompileOpt[N];
  12712. }
  12713. return 0;
  12714. }
  12715. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12716. /************** End of ctime.c ***********************************************/
  12717. /************** Begin file status.c ******************************************/
  12718. /*
  12719. ** 2008 June 18
  12720. **
  12721. ** The author disclaims copyright to this source code. In place of
  12722. ** a legal notice, here is a blessing:
  12723. **
  12724. ** May you do good and not evil.
  12725. ** May you find forgiveness for yourself and forgive others.
  12726. ** May you share freely, never taking more than you give.
  12727. **
  12728. *************************************************************************
  12729. **
  12730. ** This module implements the sqlite3_status() interface and related
  12731. ** functionality.
  12732. */
  12733. /************** Include vdbeInt.h in the middle of status.c ******************/
  12734. /************** Begin file vdbeInt.h *****************************************/
  12735. /*
  12736. ** 2003 September 6
  12737. **
  12738. ** The author disclaims copyright to this source code. In place of
  12739. ** a legal notice, here is a blessing:
  12740. **
  12741. ** May you do good and not evil.
  12742. ** May you find forgiveness for yourself and forgive others.
  12743. ** May you share freely, never taking more than you give.
  12744. **
  12745. *************************************************************************
  12746. ** This is the header file for information that is private to the
  12747. ** VDBE. This information used to all be at the top of the single
  12748. ** source code file "vdbe.c". When that file became too big (over
  12749. ** 6000 lines long) it was split up into several smaller files and
  12750. ** this header information was factored out.
  12751. */
  12752. #ifndef _VDBEINT_H_
  12753. #define _VDBEINT_H_
  12754. /*
  12755. ** The maximum number of times that a statement will try to reparse
  12756. ** itself before giving up and returning SQLITE_SCHEMA.
  12757. */
  12758. #ifndef SQLITE_MAX_SCHEMA_RETRY
  12759. # define SQLITE_MAX_SCHEMA_RETRY 50
  12760. #endif
  12761. /*
  12762. ** SQL is translated into a sequence of instructions to be
  12763. ** executed by a virtual machine. Each instruction is an instance
  12764. ** of the following structure.
  12765. */
  12766. typedef struct VdbeOp Op;
  12767. /*
  12768. ** Boolean values
  12769. */
  12770. typedef unsigned char Bool;
  12771. /* Opaque type used by code in vdbesort.c */
  12772. typedef struct VdbeSorter VdbeSorter;
  12773. /* Opaque type used by the explainer */
  12774. typedef struct Explain Explain;
  12775. /* Elements of the linked list at Vdbe.pAuxData */
  12776. typedef struct AuxData AuxData;
  12777. /*
  12778. ** A cursor is a pointer into a single BTree within a database file.
  12779. ** The cursor can seek to a BTree entry with a particular key, or
  12780. ** loop over all entries of the Btree. You can also insert new BTree
  12781. ** entries or retrieve the key or data from the entry that the cursor
  12782. ** is currently pointing to.
  12783. **
  12784. ** Every cursor that the virtual machine has open is represented by an
  12785. ** instance of the following structure.
  12786. */
  12787. struct VdbeCursor {
  12788. BtCursor *pCursor; /* The cursor structure of the backend */
  12789. Btree *pBt; /* Separate file holding temporary table */
  12790. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12791. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12792. int pseudoTableReg; /* Register holding pseudotable content. */
  12793. int nField; /* Number of fields in the header */
  12794. Bool zeroed; /* True if zeroed out and ready for reuse */
  12795. Bool rowidIsValid; /* True if lastRowid is valid */
  12796. Bool atFirst; /* True if pointing to first entry */
  12797. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12798. Bool nullRow; /* True if pointing to a row with no data */
  12799. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12800. Bool isTable; /* True if a table requiring integer keys */
  12801. Bool isIndex; /* True if an index containing keys only - no data */
  12802. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12803. Bool isSorter; /* True if a new-style sorter */
  12804. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12805. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12806. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12807. i64 seqCount; /* Sequence counter */
  12808. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12809. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12810. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12811. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12812. ** OP_IsUnique opcode on this cursor. */
  12813. int seekResult;
  12814. /* Cached information about the header for the data record that the
  12815. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12816. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12817. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12818. ** the cache is out of date.
  12819. **
  12820. ** aRow might point to (ephemeral) data for the current row, or it might
  12821. ** be NULL.
  12822. */
  12823. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12824. int payloadSize; /* Total number of bytes in the record */
  12825. u32 *aType; /* Type values for all entries in the record */
  12826. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12827. u8 *aRow; /* Data for the current row, if all on one page */
  12828. };
  12829. typedef struct VdbeCursor VdbeCursor;
  12830. /*
  12831. ** When a sub-program is executed (OP_Program), a structure of this type
  12832. ** is allocated to store the current value of the program counter, as
  12833. ** well as the current memory cell array and various other frame specific
  12834. ** values stored in the Vdbe struct. When the sub-program is finished,
  12835. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12836. ** restoring the state of the VM to as it was before the sub-program
  12837. ** began executing.
  12838. **
  12839. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12840. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12841. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12842. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12843. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12844. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12845. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12846. ** child frame are released.
  12847. **
  12848. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12849. ** set to NULL if the currently executing frame is the main program.
  12850. */
  12851. typedef struct VdbeFrame VdbeFrame;
  12852. struct VdbeFrame {
  12853. Vdbe *v; /* VM this frame belongs to */
  12854. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12855. Op *aOp; /* Program instructions for parent frame */
  12856. Mem *aMem; /* Array of memory cells for parent frame */
  12857. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12858. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12859. void *token; /* Copy of SubProgram.token */
  12860. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12861. int nCursor; /* Number of entries in apCsr */
  12862. int pc; /* Program Counter in parent (calling) frame */
  12863. int nOp; /* Size of aOp array */
  12864. int nMem; /* Number of entries in aMem */
  12865. int nOnceFlag; /* Number of entries in aOnceFlag */
  12866. int nChildMem; /* Number of memory cells for child frame */
  12867. int nChildCsr; /* Number of cursors for child frame */
  12868. int nChange; /* Statement changes (Vdbe.nChanges) */
  12869. };
  12870. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12871. /*
  12872. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12873. */
  12874. #define CACHE_STALE 0
  12875. /*
  12876. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12877. ** structures. Each Mem struct may cache multiple representations (string,
  12878. ** integer etc.) of the same value.
  12879. */
  12880. struct Mem {
  12881. sqlite3 *db; /* The associated database connection */
  12882. char *z; /* String or BLOB value */
  12883. double r; /* Real value */
  12884. union {
  12885. i64 i; /* Integer value used when MEM_Int is set in flags */
  12886. int nZero; /* Used when bit MEM_Zero is set in flags */
  12887. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12888. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12889. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12890. } u;
  12891. int n; /* Number of characters in string value, excluding '\0' */
  12892. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12893. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12894. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12895. #ifdef SQLITE_DEBUG
  12896. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12897. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12898. #endif
  12899. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12900. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12901. };
  12902. /* One or more of the following flags are set to indicate the validOK
  12903. ** representations of the value stored in the Mem struct.
  12904. **
  12905. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12906. ** No other flags may be set in this case.
  12907. **
  12908. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12909. ** Usually this is encoded in the same unicode encoding as the main
  12910. ** database (see below for exceptions). If the MEM_Term flag is also
  12911. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12912. ** flags may coexist with the MEM_Str flag.
  12913. */
  12914. #define MEM_Null 0x0001 /* Value is NULL */
  12915. #define MEM_Str 0x0002 /* Value is a string */
  12916. #define MEM_Int 0x0004 /* Value is an integer */
  12917. #define MEM_Real 0x0008 /* Value is a real number */
  12918. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12919. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12920. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12921. #define MEM_Invalid 0x0080 /* Value is undefined */
  12922. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12923. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12924. /* Whenever Mem contains a valid string or blob representation, one of
  12925. ** the following flags must be set to determine the memory management
  12926. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12927. ** string is \000 or \u0000 terminated
  12928. */
  12929. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12930. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12931. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12932. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12933. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12934. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12935. #ifdef SQLITE_OMIT_INCRBLOB
  12936. #undef MEM_Zero
  12937. #define MEM_Zero 0x0000
  12938. #endif
  12939. /*
  12940. ** Clear any existing type flags from a Mem and replace them with f
  12941. */
  12942. #define MemSetTypeFlag(p, f) \
  12943. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12944. /*
  12945. ** Return true if a memory cell is not marked as invalid. This macro
  12946. ** is for use inside assert() statements only.
  12947. */
  12948. #ifdef SQLITE_DEBUG
  12949. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12950. #endif
  12951. /*
  12952. ** Each auxilliary data pointer stored by a user defined function
  12953. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  12954. ** of this structure. All such structures associated with a single VM
  12955. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  12956. ** when the VM is halted (if not before).
  12957. */
  12958. struct AuxData {
  12959. int iOp; /* Instruction number of OP_Function opcode */
  12960. int iArg; /* Index of function argument. */
  12961. void *pAux; /* Aux data pointer */
  12962. void (*xDelete)(void *); /* Destructor for the aux data */
  12963. AuxData *pNext; /* Next element in list */
  12964. };
  12965. /*
  12966. ** The "context" argument for a installable function. A pointer to an
  12967. ** instance of this structure is the first argument to the routines used
  12968. ** implement the SQL functions.
  12969. **
  12970. ** There is a typedef for this structure in sqlite.h. So all routines,
  12971. ** even the public interface to SQLite, can use a pointer to this structure.
  12972. ** But this file is the only place where the internal details of this
  12973. ** structure are known.
  12974. **
  12975. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12976. ** (Mem) which are only defined there.
  12977. */
  12978. struct sqlite3_context {
  12979. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12980. Mem s; /* The return value is stored here */
  12981. Mem *pMem; /* Memory cell used to store aggregate context */
  12982. CollSeq *pColl; /* Collating sequence */
  12983. Vdbe *pVdbe; /* The VM that owns this context */
  12984. int iOp; /* Instruction number of OP_Function */
  12985. int isError; /* Error code returned by the function. */
  12986. u8 skipFlag; /* Skip skip accumulator loading if true */
  12987. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  12988. };
  12989. /*
  12990. ** An Explain object accumulates indented output which is helpful
  12991. ** in describing recursive data structures.
  12992. */
  12993. struct Explain {
  12994. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12995. StrAccum str; /* The string being accumulated */
  12996. int nIndent; /* Number of elements in aIndent */
  12997. u16 aIndent[100]; /* Levels of indentation */
  12998. char zBase[100]; /* Initial space */
  12999. };
  13000. /* A bitfield type for use inside of structures. Always follow with :N where
  13001. ** N is the number of bits.
  13002. */
  13003. typedef unsigned bft; /* Bit Field Type */
  13004. /*
  13005. ** An instance of the virtual machine. This structure contains the complete
  13006. ** state of the virtual machine.
  13007. **
  13008. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  13009. ** is really a pointer to an instance of this structure.
  13010. **
  13011. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  13012. ** any virtual table method invocations made by the vdbe program. It is
  13013. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  13014. ** variable is used for two purposes: to allow xDestroy methods to execute
  13015. ** "DROP TABLE" statements and to prevent some nasty side effects of
  13016. ** malloc failure when SQLite is invoked recursively by a virtual table
  13017. ** method function.
  13018. */
  13019. struct Vdbe {
  13020. sqlite3 *db; /* The database connection that owns this statement */
  13021. Op *aOp; /* Space to hold the virtual machine's program */
  13022. Mem *aMem; /* The memory locations */
  13023. Mem **apArg; /* Arguments to currently executing user function */
  13024. Mem *aColName; /* Column names to return */
  13025. Mem *pResultSet; /* Pointer to an array of results */
  13026. int nMem; /* Number of memory locations currently allocated */
  13027. int nOp; /* Number of instructions in the program */
  13028. int nOpAlloc; /* Number of slots allocated for aOp[] */
  13029. int nLabel; /* Number of labels used */
  13030. int *aLabel; /* Space to hold the labels */
  13031. u16 nResColumn; /* Number of columns in one row of the result set */
  13032. int nCursor; /* Number of slots in apCsr[] */
  13033. u32 magic; /* Magic number for sanity checking */
  13034. char *zErrMsg; /* Error message written here */
  13035. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  13036. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  13037. Mem *aVar; /* Values for the OP_Variable opcode. */
  13038. char **azVar; /* Name of variables */
  13039. ynVar nVar; /* Number of entries in aVar[] */
  13040. ynVar nzVar; /* Number of entries in azVar[] */
  13041. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  13042. int pc; /* The program counter */
  13043. int rc; /* Value to return */
  13044. u8 errorAction; /* Recovery action to do in case of an error */
  13045. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  13046. bft explain:2; /* True if EXPLAIN present on SQL command */
  13047. bft inVtabMethod:2; /* See comments above */
  13048. bft changeCntOn:1; /* True to update the change-counter */
  13049. bft expired:1; /* True if the VM needs to be recompiled */
  13050. bft runOnlyOnce:1; /* Automatically expire on reset */
  13051. bft usesStmtJournal:1; /* True if uses a statement journal */
  13052. bft readOnly:1; /* True for statements that do not write */
  13053. bft bIsReader:1; /* True for statements that read */
  13054. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  13055. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  13056. int nChange; /* Number of db changes made since last reset */
  13057. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  13058. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13059. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13060. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13061. #ifndef SQLITE_OMIT_TRACE
  13062. i64 startTime; /* Time when query started - used for profiling */
  13063. #endif
  13064. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13065. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13066. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13067. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13068. char *zSql; /* Text of the SQL statement that generated this */
  13069. void *pFree; /* Free this when deleting the vdbe */
  13070. #ifdef SQLITE_DEBUG
  13071. FILE *trace; /* Write an execution trace here, if not NULL */
  13072. #endif
  13073. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  13074. Explain *pExplain; /* The explainer */
  13075. char *zExplain; /* Explanation of data structures */
  13076. #endif
  13077. VdbeFrame *pFrame; /* Parent frame */
  13078. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13079. int nFrame; /* Number of frames in pFrame list */
  13080. u32 expmask; /* Binding to these vars invalidates VM */
  13081. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13082. int nOnceFlag; /* Size of array aOnceFlag[] */
  13083. u8 *aOnceFlag; /* Flags for OP_Once */
  13084. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13085. };
  13086. /*
  13087. ** The following are allowed values for Vdbe.magic
  13088. */
  13089. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13090. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13091. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13092. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13093. /*
  13094. ** Function prototypes
  13095. */
  13096. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13097. void sqliteVdbePopStack(Vdbe*,int);
  13098. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13099. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13100. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13101. #endif
  13102. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13103. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13104. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  13105. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13106. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13107. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13108. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  13109. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  13110. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13111. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13112. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13113. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13114. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13115. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13116. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13117. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13118. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13119. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13120. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13121. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13122. #ifdef SQLITE_OMIT_FLOATING_POINT
  13123. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13124. #else
  13125. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13126. #endif
  13127. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13128. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13129. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13130. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13131. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  13132. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13133. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13134. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13135. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13136. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13137. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13138. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  13139. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13140. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  13141. #define VdbeMemRelease(X) \
  13142. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  13143. sqlite3VdbeMemReleaseExternal(X);
  13144. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13145. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13146. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13147. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13148. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13149. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13150. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  13151. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13152. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  13153. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13154. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13155. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13156. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  13157. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  13158. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  13159. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13160. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13161. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13162. #else
  13163. # define sqlite3VdbeEnter(X)
  13164. # define sqlite3VdbeLeave(X)
  13165. #endif
  13166. #ifdef SQLITE_DEBUG
  13167. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13168. #endif
  13169. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13170. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13171. #else
  13172. # define sqlite3VdbeCheckFk(p,i) 0
  13173. #endif
  13174. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13175. #ifdef SQLITE_DEBUG
  13176. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13177. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13178. #endif
  13179. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13180. #ifndef SQLITE_OMIT_INCRBLOB
  13181. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13182. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13183. #else
  13184. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13185. #define ExpandBlob(P) SQLITE_OK
  13186. #endif
  13187. #endif /* !defined(_VDBEINT_H_) */
  13188. /************** End of vdbeInt.h *********************************************/
  13189. /************** Continuing where we left off in status.c *********************/
  13190. /*
  13191. ** Variables in which to record status information.
  13192. */
  13193. typedef struct sqlite3StatType sqlite3StatType;
  13194. static SQLITE_WSD struct sqlite3StatType {
  13195. int nowValue[10]; /* Current value */
  13196. int mxValue[10]; /* Maximum value */
  13197. } sqlite3Stat = { {0,}, {0,} };
  13198. /* The "wsdStat" macro will resolve to the status information
  13199. ** state vector. If writable static data is unsupported on the target,
  13200. ** we have to locate the state vector at run-time. In the more common
  13201. ** case where writable static data is supported, wsdStat can refer directly
  13202. ** to the "sqlite3Stat" state vector declared above.
  13203. */
  13204. #ifdef SQLITE_OMIT_WSD
  13205. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13206. # define wsdStat x[0]
  13207. #else
  13208. # define wsdStatInit
  13209. # define wsdStat sqlite3Stat
  13210. #endif
  13211. /*
  13212. ** Return the current value of a status parameter.
  13213. */
  13214. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13215. wsdStatInit;
  13216. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13217. return wsdStat.nowValue[op];
  13218. }
  13219. /*
  13220. ** Add N to the value of a status record. It is assumed that the
  13221. ** caller holds appropriate locks.
  13222. */
  13223. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13224. wsdStatInit;
  13225. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13226. wsdStat.nowValue[op] += N;
  13227. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13228. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13229. }
  13230. }
  13231. /*
  13232. ** Set the value of a status to X.
  13233. */
  13234. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13235. wsdStatInit;
  13236. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13237. wsdStat.nowValue[op] = X;
  13238. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13239. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13240. }
  13241. }
  13242. /*
  13243. ** Query status information.
  13244. **
  13245. ** This implementation assumes that reading or writing an aligned
  13246. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13247. ** then this routine is not threadsafe.
  13248. */
  13249. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13250. wsdStatInit;
  13251. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13252. return SQLITE_MISUSE_BKPT;
  13253. }
  13254. *pCurrent = wsdStat.nowValue[op];
  13255. *pHighwater = wsdStat.mxValue[op];
  13256. if( resetFlag ){
  13257. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13258. }
  13259. return SQLITE_OK;
  13260. }
  13261. /*
  13262. ** Query status information for a single database connection
  13263. */
  13264. SQLITE_API int sqlite3_db_status(
  13265. sqlite3 *db, /* The database connection whose status is desired */
  13266. int op, /* Status verb */
  13267. int *pCurrent, /* Write current value here */
  13268. int *pHighwater, /* Write high-water mark here */
  13269. int resetFlag /* Reset high-water mark if true */
  13270. ){
  13271. int rc = SQLITE_OK; /* Return code */
  13272. sqlite3_mutex_enter(db->mutex);
  13273. switch( op ){
  13274. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13275. *pCurrent = db->lookaside.nOut;
  13276. *pHighwater = db->lookaside.mxOut;
  13277. if( resetFlag ){
  13278. db->lookaside.mxOut = db->lookaside.nOut;
  13279. }
  13280. break;
  13281. }
  13282. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13283. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13284. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13285. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13286. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13287. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13288. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13289. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13290. *pCurrent = 0;
  13291. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13292. if( resetFlag ){
  13293. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13294. }
  13295. break;
  13296. }
  13297. /*
  13298. ** Return an approximation for the amount of memory currently used
  13299. ** by all pagers associated with the given database connection. The
  13300. ** highwater mark is meaningless and is returned as zero.
  13301. */
  13302. case SQLITE_DBSTATUS_CACHE_USED: {
  13303. int totalUsed = 0;
  13304. int i;
  13305. sqlite3BtreeEnterAll(db);
  13306. for(i=0; i<db->nDb; i++){
  13307. Btree *pBt = db->aDb[i].pBt;
  13308. if( pBt ){
  13309. Pager *pPager = sqlite3BtreePager(pBt);
  13310. totalUsed += sqlite3PagerMemUsed(pPager);
  13311. }
  13312. }
  13313. sqlite3BtreeLeaveAll(db);
  13314. *pCurrent = totalUsed;
  13315. *pHighwater = 0;
  13316. break;
  13317. }
  13318. /*
  13319. ** *pCurrent gets an accurate estimate of the amount of memory used
  13320. ** to store the schema for all databases (main, temp, and any ATTACHed
  13321. ** databases. *pHighwater is set to zero.
  13322. */
  13323. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13324. int i; /* Used to iterate through schemas */
  13325. int nByte = 0; /* Used to accumulate return value */
  13326. sqlite3BtreeEnterAll(db);
  13327. db->pnBytesFreed = &nByte;
  13328. for(i=0; i<db->nDb; i++){
  13329. Schema *pSchema = db->aDb[i].pSchema;
  13330. if( ALWAYS(pSchema!=0) ){
  13331. HashElem *p;
  13332. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13333. pSchema->tblHash.count
  13334. + pSchema->trigHash.count
  13335. + pSchema->idxHash.count
  13336. + pSchema->fkeyHash.count
  13337. );
  13338. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13339. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13340. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13341. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13342. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13343. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13344. }
  13345. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13346. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13347. }
  13348. }
  13349. }
  13350. db->pnBytesFreed = 0;
  13351. sqlite3BtreeLeaveAll(db);
  13352. *pHighwater = 0;
  13353. *pCurrent = nByte;
  13354. break;
  13355. }
  13356. /*
  13357. ** *pCurrent gets an accurate estimate of the amount of memory used
  13358. ** to store all prepared statements.
  13359. ** *pHighwater is set to zero.
  13360. */
  13361. case SQLITE_DBSTATUS_STMT_USED: {
  13362. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13363. int nByte = 0; /* Used to accumulate return value */
  13364. db->pnBytesFreed = &nByte;
  13365. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13366. sqlite3VdbeClearObject(db, pVdbe);
  13367. sqlite3DbFree(db, pVdbe);
  13368. }
  13369. db->pnBytesFreed = 0;
  13370. *pHighwater = 0;
  13371. *pCurrent = nByte;
  13372. break;
  13373. }
  13374. /*
  13375. ** Set *pCurrent to the total cache hits or misses encountered by all
  13376. ** pagers the database handle is connected to. *pHighwater is always set
  13377. ** to zero.
  13378. */
  13379. case SQLITE_DBSTATUS_CACHE_HIT:
  13380. case SQLITE_DBSTATUS_CACHE_MISS:
  13381. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13382. int i;
  13383. int nRet = 0;
  13384. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13385. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13386. for(i=0; i<db->nDb; i++){
  13387. if( db->aDb[i].pBt ){
  13388. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13389. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13390. }
  13391. }
  13392. *pHighwater = 0;
  13393. *pCurrent = nRet;
  13394. break;
  13395. }
  13396. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  13397. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  13398. ** have been satisfied. The *pHighwater is always set to zero.
  13399. */
  13400. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  13401. *pHighwater = 0;
  13402. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  13403. break;
  13404. }
  13405. default: {
  13406. rc = SQLITE_ERROR;
  13407. }
  13408. }
  13409. sqlite3_mutex_leave(db->mutex);
  13410. return rc;
  13411. }
  13412. /************** End of status.c **********************************************/
  13413. /************** Begin file date.c ********************************************/
  13414. /*
  13415. ** 2003 October 31
  13416. **
  13417. ** The author disclaims copyright to this source code. In place of
  13418. ** a legal notice, here is a blessing:
  13419. **
  13420. ** May you do good and not evil.
  13421. ** May you find forgiveness for yourself and forgive others.
  13422. ** May you share freely, never taking more than you give.
  13423. **
  13424. *************************************************************************
  13425. ** This file contains the C functions that implement date and time
  13426. ** functions for SQLite.
  13427. **
  13428. ** There is only one exported symbol in this file - the function
  13429. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13430. ** All other code has file scope.
  13431. **
  13432. ** SQLite processes all times and dates as Julian Day numbers. The
  13433. ** dates and times are stored as the number of days since noon
  13434. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13435. ** calendar system.
  13436. **
  13437. ** 1970-01-01 00:00:00 is JD 2440587.5
  13438. ** 2000-01-01 00:00:00 is JD 2451544.5
  13439. **
  13440. ** This implemention requires years to be expressed as a 4-digit number
  13441. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13442. ** be represented, even though julian day numbers allow a much wider
  13443. ** range of dates.
  13444. **
  13445. ** The Gregorian calendar system is used for all dates and times,
  13446. ** even those that predate the Gregorian calendar. Historians usually
  13447. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13448. ** dates afterwards, depending on locale. Beware of this difference.
  13449. **
  13450. ** The conversion algorithms are implemented based on descriptions
  13451. ** in the following text:
  13452. **
  13453. ** Jean Meeus
  13454. ** Astronomical Algorithms, 2nd Edition, 1998
  13455. ** ISBM 0-943396-61-1
  13456. ** Willmann-Bell, Inc
  13457. ** Richmond, Virginia (USA)
  13458. */
  13459. /* #include <stdlib.h> */
  13460. /* #include <assert.h> */
  13461. #include <time.h>
  13462. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13463. /*
  13464. ** A structure for holding a single date and time.
  13465. */
  13466. typedef struct DateTime DateTime;
  13467. struct DateTime {
  13468. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13469. int Y, M, D; /* Year, month, and day */
  13470. int h, m; /* Hour and minutes */
  13471. int tz; /* Timezone offset in minutes */
  13472. double s; /* Seconds */
  13473. char validYMD; /* True (1) if Y,M,D are valid */
  13474. char validHMS; /* True (1) if h,m,s are valid */
  13475. char validJD; /* True (1) if iJD is valid */
  13476. char validTZ; /* True (1) if tz is valid */
  13477. };
  13478. /*
  13479. ** Convert zDate into one or more integers. Additional arguments
  13480. ** come in groups of 5 as follows:
  13481. **
  13482. ** N number of digits in the integer
  13483. ** min minimum allowed value of the integer
  13484. ** max maximum allowed value of the integer
  13485. ** nextC first character after the integer
  13486. ** pVal where to write the integers value.
  13487. **
  13488. ** Conversions continue until one with nextC==0 is encountered.
  13489. ** The function returns the number of successful conversions.
  13490. */
  13491. static int getDigits(const char *zDate, ...){
  13492. va_list ap;
  13493. int val;
  13494. int N;
  13495. int min;
  13496. int max;
  13497. int nextC;
  13498. int *pVal;
  13499. int cnt = 0;
  13500. va_start(ap, zDate);
  13501. do{
  13502. N = va_arg(ap, int);
  13503. min = va_arg(ap, int);
  13504. max = va_arg(ap, int);
  13505. nextC = va_arg(ap, int);
  13506. pVal = va_arg(ap, int*);
  13507. val = 0;
  13508. while( N-- ){
  13509. if( !sqlite3Isdigit(*zDate) ){
  13510. goto end_getDigits;
  13511. }
  13512. val = val*10 + *zDate - '0';
  13513. zDate++;
  13514. }
  13515. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13516. goto end_getDigits;
  13517. }
  13518. *pVal = val;
  13519. zDate++;
  13520. cnt++;
  13521. }while( nextC );
  13522. end_getDigits:
  13523. va_end(ap);
  13524. return cnt;
  13525. }
  13526. /*
  13527. ** Parse a timezone extension on the end of a date-time.
  13528. ** The extension is of the form:
  13529. **
  13530. ** (+/-)HH:MM
  13531. **
  13532. ** Or the "zulu" notation:
  13533. **
  13534. ** Z
  13535. **
  13536. ** If the parse is successful, write the number of minutes
  13537. ** of change in p->tz and return 0. If a parser error occurs,
  13538. ** return non-zero.
  13539. **
  13540. ** A missing specifier is not considered an error.
  13541. */
  13542. static int parseTimezone(const char *zDate, DateTime *p){
  13543. int sgn = 0;
  13544. int nHr, nMn;
  13545. int c;
  13546. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13547. p->tz = 0;
  13548. c = *zDate;
  13549. if( c=='-' ){
  13550. sgn = -1;
  13551. }else if( c=='+' ){
  13552. sgn = +1;
  13553. }else if( c=='Z' || c=='z' ){
  13554. zDate++;
  13555. goto zulu_time;
  13556. }else{
  13557. return c!=0;
  13558. }
  13559. zDate++;
  13560. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13561. return 1;
  13562. }
  13563. zDate += 5;
  13564. p->tz = sgn*(nMn + nHr*60);
  13565. zulu_time:
  13566. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13567. return *zDate!=0;
  13568. }
  13569. /*
  13570. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13571. ** The HH, MM, and SS must each be exactly 2 digits. The
  13572. ** fractional seconds FFFF can be one or more digits.
  13573. **
  13574. ** Return 1 if there is a parsing error and 0 on success.
  13575. */
  13576. static int parseHhMmSs(const char *zDate, DateTime *p){
  13577. int h, m, s;
  13578. double ms = 0.0;
  13579. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13580. return 1;
  13581. }
  13582. zDate += 5;
  13583. if( *zDate==':' ){
  13584. zDate++;
  13585. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13586. return 1;
  13587. }
  13588. zDate += 2;
  13589. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13590. double rScale = 1.0;
  13591. zDate++;
  13592. while( sqlite3Isdigit(*zDate) ){
  13593. ms = ms*10.0 + *zDate - '0';
  13594. rScale *= 10.0;
  13595. zDate++;
  13596. }
  13597. ms /= rScale;
  13598. }
  13599. }else{
  13600. s = 0;
  13601. }
  13602. p->validJD = 0;
  13603. p->validHMS = 1;
  13604. p->h = h;
  13605. p->m = m;
  13606. p->s = s + ms;
  13607. if( parseTimezone(zDate, p) ) return 1;
  13608. p->validTZ = (p->tz!=0)?1:0;
  13609. return 0;
  13610. }
  13611. /*
  13612. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13613. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13614. **
  13615. ** Reference: Meeus page 61
  13616. */
  13617. static void computeJD(DateTime *p){
  13618. int Y, M, D, A, B, X1, X2;
  13619. if( p->validJD ) return;
  13620. if( p->validYMD ){
  13621. Y = p->Y;
  13622. M = p->M;
  13623. D = p->D;
  13624. }else{
  13625. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13626. M = 1;
  13627. D = 1;
  13628. }
  13629. if( M<=2 ){
  13630. Y--;
  13631. M += 12;
  13632. }
  13633. A = Y/100;
  13634. B = 2 - A + (A/4);
  13635. X1 = 36525*(Y+4716)/100;
  13636. X2 = 306001*(M+1)/10000;
  13637. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13638. p->validJD = 1;
  13639. if( p->validHMS ){
  13640. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13641. if( p->validTZ ){
  13642. p->iJD -= p->tz*60000;
  13643. p->validYMD = 0;
  13644. p->validHMS = 0;
  13645. p->validTZ = 0;
  13646. }
  13647. }
  13648. }
  13649. /*
  13650. ** Parse dates of the form
  13651. **
  13652. ** YYYY-MM-DD HH:MM:SS.FFF
  13653. ** YYYY-MM-DD HH:MM:SS
  13654. ** YYYY-MM-DD HH:MM
  13655. ** YYYY-MM-DD
  13656. **
  13657. ** Write the result into the DateTime structure and return 0
  13658. ** on success and 1 if the input string is not a well-formed
  13659. ** date.
  13660. */
  13661. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13662. int Y, M, D, neg;
  13663. if( zDate[0]=='-' ){
  13664. zDate++;
  13665. neg = 1;
  13666. }else{
  13667. neg = 0;
  13668. }
  13669. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13670. return 1;
  13671. }
  13672. zDate += 10;
  13673. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13674. if( parseHhMmSs(zDate, p)==0 ){
  13675. /* We got the time */
  13676. }else if( *zDate==0 ){
  13677. p->validHMS = 0;
  13678. }else{
  13679. return 1;
  13680. }
  13681. p->validJD = 0;
  13682. p->validYMD = 1;
  13683. p->Y = neg ? -Y : Y;
  13684. p->M = M;
  13685. p->D = D;
  13686. if( p->validTZ ){
  13687. computeJD(p);
  13688. }
  13689. return 0;
  13690. }
  13691. /*
  13692. ** Set the time to the current time reported by the VFS.
  13693. **
  13694. ** Return the number of errors.
  13695. */
  13696. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13697. p->iJD = sqlite3StmtCurrentTime(context);
  13698. if( p->iJD>0 ){
  13699. p->validJD = 1;
  13700. return 0;
  13701. }else{
  13702. return 1;
  13703. }
  13704. }
  13705. /*
  13706. ** Attempt to parse the given string into a Julian Day Number. Return
  13707. ** the number of errors.
  13708. **
  13709. ** The following are acceptable forms for the input string:
  13710. **
  13711. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13712. ** DDDD.DD
  13713. ** now
  13714. **
  13715. ** In the first form, the +/-HH:MM is always optional. The fractional
  13716. ** seconds extension (the ".FFF") is optional. The seconds portion
  13717. ** (":SS.FFF") is option. The year and date can be omitted as long
  13718. ** as there is a time string. The time string can be omitted as long
  13719. ** as there is a year and date.
  13720. */
  13721. static int parseDateOrTime(
  13722. sqlite3_context *context,
  13723. const char *zDate,
  13724. DateTime *p
  13725. ){
  13726. double r;
  13727. if( parseYyyyMmDd(zDate,p)==0 ){
  13728. return 0;
  13729. }else if( parseHhMmSs(zDate, p)==0 ){
  13730. return 0;
  13731. }else if( sqlite3StrICmp(zDate,"now")==0){
  13732. return setDateTimeToCurrent(context, p);
  13733. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13734. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13735. p->validJD = 1;
  13736. return 0;
  13737. }
  13738. return 1;
  13739. }
  13740. /*
  13741. ** Compute the Year, Month, and Day from the julian day number.
  13742. */
  13743. static void computeYMD(DateTime *p){
  13744. int Z, A, B, C, D, E, X1;
  13745. if( p->validYMD ) return;
  13746. if( !p->validJD ){
  13747. p->Y = 2000;
  13748. p->M = 1;
  13749. p->D = 1;
  13750. }else{
  13751. Z = (int)((p->iJD + 43200000)/86400000);
  13752. A = (int)((Z - 1867216.25)/36524.25);
  13753. A = Z + 1 + A - (A/4);
  13754. B = A + 1524;
  13755. C = (int)((B - 122.1)/365.25);
  13756. D = (36525*C)/100;
  13757. E = (int)((B-D)/30.6001);
  13758. X1 = (int)(30.6001*E);
  13759. p->D = B - D - X1;
  13760. p->M = E<14 ? E-1 : E-13;
  13761. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13762. }
  13763. p->validYMD = 1;
  13764. }
  13765. /*
  13766. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13767. */
  13768. static void computeHMS(DateTime *p){
  13769. int s;
  13770. if( p->validHMS ) return;
  13771. computeJD(p);
  13772. s = (int)((p->iJD + 43200000) % 86400000);
  13773. p->s = s/1000.0;
  13774. s = (int)p->s;
  13775. p->s -= s;
  13776. p->h = s/3600;
  13777. s -= p->h*3600;
  13778. p->m = s/60;
  13779. p->s += s - p->m*60;
  13780. p->validHMS = 1;
  13781. }
  13782. /*
  13783. ** Compute both YMD and HMS
  13784. */
  13785. static void computeYMD_HMS(DateTime *p){
  13786. computeYMD(p);
  13787. computeHMS(p);
  13788. }
  13789. /*
  13790. ** Clear the YMD and HMS and the TZ
  13791. */
  13792. static void clearYMD_HMS_TZ(DateTime *p){
  13793. p->validYMD = 0;
  13794. p->validHMS = 0;
  13795. p->validTZ = 0;
  13796. }
  13797. /*
  13798. ** On recent Windows platforms, the localtime_s() function is available
  13799. ** as part of the "Secure CRT". It is essentially equivalent to
  13800. ** localtime_r() available under most POSIX platforms, except that the
  13801. ** order of the parameters is reversed.
  13802. **
  13803. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13804. **
  13805. ** If the user has not indicated to use localtime_r() or localtime_s()
  13806. ** already, check for an MSVC build environment that provides
  13807. ** localtime_s().
  13808. */
  13809. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13810. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13811. #define HAVE_LOCALTIME_S 1
  13812. #endif
  13813. #ifndef SQLITE_OMIT_LOCALTIME
  13814. /*
  13815. ** The following routine implements the rough equivalent of localtime_r()
  13816. ** using whatever operating-system specific localtime facility that
  13817. ** is available. This routine returns 0 on success and
  13818. ** non-zero on any kind of error.
  13819. **
  13820. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13821. ** routine will always fail.
  13822. **
  13823. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  13824. ** library function localtime_r() is used to assist in the calculation of
  13825. ** local time.
  13826. */
  13827. static int osLocaltime(time_t *t, struct tm *pTm){
  13828. int rc;
  13829. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13830. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13831. struct tm *pX;
  13832. #if SQLITE_THREADSAFE>0
  13833. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13834. #endif
  13835. sqlite3_mutex_enter(mutex);
  13836. pX = localtime(t);
  13837. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13838. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13839. #endif
  13840. if( pX ) *pTm = *pX;
  13841. sqlite3_mutex_leave(mutex);
  13842. rc = pX==0;
  13843. #else
  13844. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13845. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13846. #endif
  13847. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13848. rc = localtime_r(t, pTm)==0;
  13849. #else
  13850. rc = localtime_s(pTm, t);
  13851. #endif /* HAVE_LOCALTIME_R */
  13852. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13853. return rc;
  13854. }
  13855. #endif /* SQLITE_OMIT_LOCALTIME */
  13856. #ifndef SQLITE_OMIT_LOCALTIME
  13857. /*
  13858. ** Compute the difference (in milliseconds) between localtime and UTC
  13859. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13860. ** return this value and set *pRc to SQLITE_OK.
  13861. **
  13862. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13863. ** is undefined in this case.
  13864. */
  13865. static sqlite3_int64 localtimeOffset(
  13866. DateTime *p, /* Date at which to calculate offset */
  13867. sqlite3_context *pCtx, /* Write error here if one occurs */
  13868. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13869. ){
  13870. DateTime x, y;
  13871. time_t t;
  13872. struct tm sLocal;
  13873. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13874. memset(&sLocal, 0, sizeof(sLocal));
  13875. x = *p;
  13876. computeYMD_HMS(&x);
  13877. if( x.Y<1971 || x.Y>=2038 ){
  13878. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  13879. ** works for years between 1970 and 2037. For dates outside this range,
  13880. ** SQLite attempts to map the year into an equivalent year within this
  13881. ** range, do the calculation, then map the year back.
  13882. */
  13883. x.Y = 2000;
  13884. x.M = 1;
  13885. x.D = 1;
  13886. x.h = 0;
  13887. x.m = 0;
  13888. x.s = 0.0;
  13889. } else {
  13890. int s = (int)(x.s + 0.5);
  13891. x.s = s;
  13892. }
  13893. x.tz = 0;
  13894. x.validJD = 0;
  13895. computeJD(&x);
  13896. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13897. if( osLocaltime(&t, &sLocal) ){
  13898. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13899. *pRc = SQLITE_ERROR;
  13900. return 0;
  13901. }
  13902. y.Y = sLocal.tm_year + 1900;
  13903. y.M = sLocal.tm_mon + 1;
  13904. y.D = sLocal.tm_mday;
  13905. y.h = sLocal.tm_hour;
  13906. y.m = sLocal.tm_min;
  13907. y.s = sLocal.tm_sec;
  13908. y.validYMD = 1;
  13909. y.validHMS = 1;
  13910. y.validJD = 0;
  13911. y.validTZ = 0;
  13912. computeJD(&y);
  13913. *pRc = SQLITE_OK;
  13914. return y.iJD - x.iJD;
  13915. }
  13916. #endif /* SQLITE_OMIT_LOCALTIME */
  13917. /*
  13918. ** Process a modifier to a date-time stamp. The modifiers are
  13919. ** as follows:
  13920. **
  13921. ** NNN days
  13922. ** NNN hours
  13923. ** NNN minutes
  13924. ** NNN.NNNN seconds
  13925. ** NNN months
  13926. ** NNN years
  13927. ** start of month
  13928. ** start of year
  13929. ** start of week
  13930. ** start of day
  13931. ** weekday N
  13932. ** unixepoch
  13933. ** localtime
  13934. ** utc
  13935. **
  13936. ** Return 0 on success and 1 if there is any kind of error. If the error
  13937. ** is in a system call (i.e. localtime()), then an error message is written
  13938. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13939. ** written to pCtx.
  13940. */
  13941. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13942. int rc = 1;
  13943. int n;
  13944. double r;
  13945. char *z, zBuf[30];
  13946. z = zBuf;
  13947. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13948. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13949. }
  13950. z[n] = 0;
  13951. switch( z[0] ){
  13952. #ifndef SQLITE_OMIT_LOCALTIME
  13953. case 'l': {
  13954. /* localtime
  13955. **
  13956. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13957. ** show local time.
  13958. */
  13959. if( strcmp(z, "localtime")==0 ){
  13960. computeJD(p);
  13961. p->iJD += localtimeOffset(p, pCtx, &rc);
  13962. clearYMD_HMS_TZ(p);
  13963. }
  13964. break;
  13965. }
  13966. #endif
  13967. case 'u': {
  13968. /*
  13969. ** unixepoch
  13970. **
  13971. ** Treat the current value of p->iJD as the number of
  13972. ** seconds since 1970. Convert to a real julian day number.
  13973. */
  13974. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13975. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13976. clearYMD_HMS_TZ(p);
  13977. rc = 0;
  13978. }
  13979. #ifndef SQLITE_OMIT_LOCALTIME
  13980. else if( strcmp(z, "utc")==0 ){
  13981. sqlite3_int64 c1;
  13982. computeJD(p);
  13983. c1 = localtimeOffset(p, pCtx, &rc);
  13984. if( rc==SQLITE_OK ){
  13985. p->iJD -= c1;
  13986. clearYMD_HMS_TZ(p);
  13987. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13988. }
  13989. }
  13990. #endif
  13991. break;
  13992. }
  13993. case 'w': {
  13994. /*
  13995. ** weekday N
  13996. **
  13997. ** Move the date to the same time on the next occurrence of
  13998. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13999. ** date is already on the appropriate weekday, this is a no-op.
  14000. */
  14001. if( strncmp(z, "weekday ", 8)==0
  14002. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  14003. && (n=(int)r)==r && n>=0 && r<7 ){
  14004. sqlite3_int64 Z;
  14005. computeYMD_HMS(p);
  14006. p->validTZ = 0;
  14007. p->validJD = 0;
  14008. computeJD(p);
  14009. Z = ((p->iJD + 129600000)/86400000) % 7;
  14010. if( Z>n ) Z -= 7;
  14011. p->iJD += (n - Z)*86400000;
  14012. clearYMD_HMS_TZ(p);
  14013. rc = 0;
  14014. }
  14015. break;
  14016. }
  14017. case 's': {
  14018. /*
  14019. ** start of TTTTT
  14020. **
  14021. ** Move the date backwards to the beginning of the current day,
  14022. ** or month or year.
  14023. */
  14024. if( strncmp(z, "start of ", 9)!=0 ) break;
  14025. z += 9;
  14026. computeYMD(p);
  14027. p->validHMS = 1;
  14028. p->h = p->m = 0;
  14029. p->s = 0.0;
  14030. p->validTZ = 0;
  14031. p->validJD = 0;
  14032. if( strcmp(z,"month")==0 ){
  14033. p->D = 1;
  14034. rc = 0;
  14035. }else if( strcmp(z,"year")==0 ){
  14036. computeYMD(p);
  14037. p->M = 1;
  14038. p->D = 1;
  14039. rc = 0;
  14040. }else if( strcmp(z,"day")==0 ){
  14041. rc = 0;
  14042. }
  14043. break;
  14044. }
  14045. case '+':
  14046. case '-':
  14047. case '0':
  14048. case '1':
  14049. case '2':
  14050. case '3':
  14051. case '4':
  14052. case '5':
  14053. case '6':
  14054. case '7':
  14055. case '8':
  14056. case '9': {
  14057. double rRounder;
  14058. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14059. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14060. rc = 1;
  14061. break;
  14062. }
  14063. if( z[n]==':' ){
  14064. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14065. ** specified number of hours, minutes, seconds, and fractional seconds
  14066. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14067. ** omitted.
  14068. */
  14069. const char *z2 = z;
  14070. DateTime tx;
  14071. sqlite3_int64 day;
  14072. if( !sqlite3Isdigit(*z2) ) z2++;
  14073. memset(&tx, 0, sizeof(tx));
  14074. if( parseHhMmSs(z2, &tx) ) break;
  14075. computeJD(&tx);
  14076. tx.iJD -= 43200000;
  14077. day = tx.iJD/86400000;
  14078. tx.iJD -= day*86400000;
  14079. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14080. computeJD(p);
  14081. clearYMD_HMS_TZ(p);
  14082. p->iJD += tx.iJD;
  14083. rc = 0;
  14084. break;
  14085. }
  14086. z += n;
  14087. while( sqlite3Isspace(*z) ) z++;
  14088. n = sqlite3Strlen30(z);
  14089. if( n>10 || n<3 ) break;
  14090. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14091. computeJD(p);
  14092. rc = 0;
  14093. rRounder = r<0 ? -0.5 : +0.5;
  14094. if( n==3 && strcmp(z,"day")==0 ){
  14095. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14096. }else if( n==4 && strcmp(z,"hour")==0 ){
  14097. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14098. }else if( n==6 && strcmp(z,"minute")==0 ){
  14099. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14100. }else if( n==6 && strcmp(z,"second")==0 ){
  14101. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14102. }else if( n==5 && strcmp(z,"month")==0 ){
  14103. int x, y;
  14104. computeYMD_HMS(p);
  14105. p->M += (int)r;
  14106. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14107. p->Y += x;
  14108. p->M -= x*12;
  14109. p->validJD = 0;
  14110. computeJD(p);
  14111. y = (int)r;
  14112. if( y!=r ){
  14113. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14114. }
  14115. }else if( n==4 && strcmp(z,"year")==0 ){
  14116. int y = (int)r;
  14117. computeYMD_HMS(p);
  14118. p->Y += y;
  14119. p->validJD = 0;
  14120. computeJD(p);
  14121. if( y!=r ){
  14122. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14123. }
  14124. }else{
  14125. rc = 1;
  14126. }
  14127. clearYMD_HMS_TZ(p);
  14128. break;
  14129. }
  14130. default: {
  14131. break;
  14132. }
  14133. }
  14134. return rc;
  14135. }
  14136. /*
  14137. ** Process time function arguments. argv[0] is a date-time stamp.
  14138. ** argv[1] and following are modifiers. Parse them all and write
  14139. ** the resulting time into the DateTime structure p. Return 0
  14140. ** on success and 1 if there are any errors.
  14141. **
  14142. ** If there are zero parameters (if even argv[0] is undefined)
  14143. ** then assume a default value of "now" for argv[0].
  14144. */
  14145. static int isDate(
  14146. sqlite3_context *context,
  14147. int argc,
  14148. sqlite3_value **argv,
  14149. DateTime *p
  14150. ){
  14151. int i;
  14152. const unsigned char *z;
  14153. int eType;
  14154. memset(p, 0, sizeof(*p));
  14155. if( argc==0 ){
  14156. return setDateTimeToCurrent(context, p);
  14157. }
  14158. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14159. || eType==SQLITE_INTEGER ){
  14160. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14161. p->validJD = 1;
  14162. }else{
  14163. z = sqlite3_value_text(argv[0]);
  14164. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14165. return 1;
  14166. }
  14167. }
  14168. for(i=1; i<argc; i++){
  14169. z = sqlite3_value_text(argv[i]);
  14170. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14171. }
  14172. return 0;
  14173. }
  14174. /*
  14175. ** The following routines implement the various date and time functions
  14176. ** of SQLite.
  14177. */
  14178. /*
  14179. ** julianday( TIMESTRING, MOD, MOD, ...)
  14180. **
  14181. ** Return the julian day number of the date specified in the arguments
  14182. */
  14183. static void juliandayFunc(
  14184. sqlite3_context *context,
  14185. int argc,
  14186. sqlite3_value **argv
  14187. ){
  14188. DateTime x;
  14189. if( isDate(context, argc, argv, &x)==0 ){
  14190. computeJD(&x);
  14191. sqlite3_result_double(context, x.iJD/86400000.0);
  14192. }
  14193. }
  14194. /*
  14195. ** datetime( TIMESTRING, MOD, MOD, ...)
  14196. **
  14197. ** Return YYYY-MM-DD HH:MM:SS
  14198. */
  14199. static void datetimeFunc(
  14200. sqlite3_context *context,
  14201. int argc,
  14202. sqlite3_value **argv
  14203. ){
  14204. DateTime x;
  14205. if( isDate(context, argc, argv, &x)==0 ){
  14206. char zBuf[100];
  14207. computeYMD_HMS(&x);
  14208. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14209. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14210. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14211. }
  14212. }
  14213. /*
  14214. ** time( TIMESTRING, MOD, MOD, ...)
  14215. **
  14216. ** Return HH:MM:SS
  14217. */
  14218. static void timeFunc(
  14219. sqlite3_context *context,
  14220. int argc,
  14221. sqlite3_value **argv
  14222. ){
  14223. DateTime x;
  14224. if( isDate(context, argc, argv, &x)==0 ){
  14225. char zBuf[100];
  14226. computeHMS(&x);
  14227. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14228. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14229. }
  14230. }
  14231. /*
  14232. ** date( TIMESTRING, MOD, MOD, ...)
  14233. **
  14234. ** Return YYYY-MM-DD
  14235. */
  14236. static void dateFunc(
  14237. sqlite3_context *context,
  14238. int argc,
  14239. sqlite3_value **argv
  14240. ){
  14241. DateTime x;
  14242. if( isDate(context, argc, argv, &x)==0 ){
  14243. char zBuf[100];
  14244. computeYMD(&x);
  14245. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14246. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14247. }
  14248. }
  14249. /*
  14250. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14251. **
  14252. ** Return a string described by FORMAT. Conversions as follows:
  14253. **
  14254. ** %d day of month
  14255. ** %f ** fractional seconds SS.SSS
  14256. ** %H hour 00-24
  14257. ** %j day of year 000-366
  14258. ** %J ** Julian day number
  14259. ** %m month 01-12
  14260. ** %M minute 00-59
  14261. ** %s seconds since 1970-01-01
  14262. ** %S seconds 00-59
  14263. ** %w day of week 0-6 sunday==0
  14264. ** %W week of year 00-53
  14265. ** %Y year 0000-9999
  14266. ** %% %
  14267. */
  14268. static void strftimeFunc(
  14269. sqlite3_context *context,
  14270. int argc,
  14271. sqlite3_value **argv
  14272. ){
  14273. DateTime x;
  14274. u64 n;
  14275. size_t i,j;
  14276. char *z;
  14277. sqlite3 *db;
  14278. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14279. char zBuf[100];
  14280. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14281. db = sqlite3_context_db_handle(context);
  14282. for(i=0, n=1; zFmt[i]; i++, n++){
  14283. if( zFmt[i]=='%' ){
  14284. switch( zFmt[i+1] ){
  14285. case 'd':
  14286. case 'H':
  14287. case 'm':
  14288. case 'M':
  14289. case 'S':
  14290. case 'W':
  14291. n++;
  14292. /* fall thru */
  14293. case 'w':
  14294. case '%':
  14295. break;
  14296. case 'f':
  14297. n += 8;
  14298. break;
  14299. case 'j':
  14300. n += 3;
  14301. break;
  14302. case 'Y':
  14303. n += 8;
  14304. break;
  14305. case 's':
  14306. case 'J':
  14307. n += 50;
  14308. break;
  14309. default:
  14310. return; /* ERROR. return a NULL */
  14311. }
  14312. i++;
  14313. }
  14314. }
  14315. testcase( n==sizeof(zBuf)-1 );
  14316. testcase( n==sizeof(zBuf) );
  14317. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14318. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14319. if( n<sizeof(zBuf) ){
  14320. z = zBuf;
  14321. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14322. sqlite3_result_error_toobig(context);
  14323. return;
  14324. }else{
  14325. z = sqlite3DbMallocRaw(db, (int)n);
  14326. if( z==0 ){
  14327. sqlite3_result_error_nomem(context);
  14328. return;
  14329. }
  14330. }
  14331. computeJD(&x);
  14332. computeYMD_HMS(&x);
  14333. for(i=j=0; zFmt[i]; i++){
  14334. if( zFmt[i]!='%' ){
  14335. z[j++] = zFmt[i];
  14336. }else{
  14337. i++;
  14338. switch( zFmt[i] ){
  14339. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14340. case 'f': {
  14341. double s = x.s;
  14342. if( s>59.999 ) s = 59.999;
  14343. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14344. j += sqlite3Strlen30(&z[j]);
  14345. break;
  14346. }
  14347. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14348. case 'W': /* Fall thru */
  14349. case 'j': {
  14350. int nDay; /* Number of days since 1st day of year */
  14351. DateTime y = x;
  14352. y.validJD = 0;
  14353. y.M = 1;
  14354. y.D = 1;
  14355. computeJD(&y);
  14356. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14357. if( zFmt[i]=='W' ){
  14358. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14359. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14360. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14361. j += 2;
  14362. }else{
  14363. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14364. j += 3;
  14365. }
  14366. break;
  14367. }
  14368. case 'J': {
  14369. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14370. j+=sqlite3Strlen30(&z[j]);
  14371. break;
  14372. }
  14373. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14374. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14375. case 's': {
  14376. sqlite3_snprintf(30,&z[j],"%lld",
  14377. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14378. j += sqlite3Strlen30(&z[j]);
  14379. break;
  14380. }
  14381. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14382. case 'w': {
  14383. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14384. break;
  14385. }
  14386. case 'Y': {
  14387. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14388. break;
  14389. }
  14390. default: z[j++] = '%'; break;
  14391. }
  14392. }
  14393. }
  14394. z[j] = 0;
  14395. sqlite3_result_text(context, z, -1,
  14396. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14397. }
  14398. /*
  14399. ** current_time()
  14400. **
  14401. ** This function returns the same value as time('now').
  14402. */
  14403. static void ctimeFunc(
  14404. sqlite3_context *context,
  14405. int NotUsed,
  14406. sqlite3_value **NotUsed2
  14407. ){
  14408. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14409. timeFunc(context, 0, 0);
  14410. }
  14411. /*
  14412. ** current_date()
  14413. **
  14414. ** This function returns the same value as date('now').
  14415. */
  14416. static void cdateFunc(
  14417. sqlite3_context *context,
  14418. int NotUsed,
  14419. sqlite3_value **NotUsed2
  14420. ){
  14421. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14422. dateFunc(context, 0, 0);
  14423. }
  14424. /*
  14425. ** current_timestamp()
  14426. **
  14427. ** This function returns the same value as datetime('now').
  14428. */
  14429. static void ctimestampFunc(
  14430. sqlite3_context *context,
  14431. int NotUsed,
  14432. sqlite3_value **NotUsed2
  14433. ){
  14434. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14435. datetimeFunc(context, 0, 0);
  14436. }
  14437. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14438. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14439. /*
  14440. ** If the library is compiled to omit the full-scale date and time
  14441. ** handling (to get a smaller binary), the following minimal version
  14442. ** of the functions current_time(), current_date() and current_timestamp()
  14443. ** are included instead. This is to support column declarations that
  14444. ** include "DEFAULT CURRENT_TIME" etc.
  14445. **
  14446. ** This function uses the C-library functions time(), gmtime()
  14447. ** and strftime(). The format string to pass to strftime() is supplied
  14448. ** as the user-data for the function.
  14449. */
  14450. static void currentTimeFunc(
  14451. sqlite3_context *context,
  14452. int argc,
  14453. sqlite3_value **argv
  14454. ){
  14455. time_t t;
  14456. char *zFormat = (char *)sqlite3_user_data(context);
  14457. sqlite3 *db;
  14458. sqlite3_int64 iT;
  14459. struct tm *pTm;
  14460. struct tm sNow;
  14461. char zBuf[20];
  14462. UNUSED_PARAMETER(argc);
  14463. UNUSED_PARAMETER(argv);
  14464. iT = sqlite3StmtCurrentTime(context);
  14465. if( iT<=0 ) return;
  14466. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14467. #ifdef HAVE_GMTIME_R
  14468. pTm = gmtime_r(&t, &sNow);
  14469. #else
  14470. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14471. pTm = gmtime(&t);
  14472. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14473. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14474. #endif
  14475. if( pTm ){
  14476. strftime(zBuf, 20, zFormat, &sNow);
  14477. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14478. }
  14479. }
  14480. #endif
  14481. /*
  14482. ** This function registered all of the above C functions as SQL
  14483. ** functions. This should be the only routine in this file with
  14484. ** external linkage.
  14485. */
  14486. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14487. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14488. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14489. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14490. FUNCTION(date, -1, 0, 0, dateFunc ),
  14491. FUNCTION(time, -1, 0, 0, timeFunc ),
  14492. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14493. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14494. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14495. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14496. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14497. #else
  14498. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14499. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14500. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14501. #endif
  14502. };
  14503. int i;
  14504. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14505. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14506. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14507. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14508. }
  14509. }
  14510. /************** End of date.c ************************************************/
  14511. /************** Begin file os.c **********************************************/
  14512. /*
  14513. ** 2005 November 29
  14514. **
  14515. ** The author disclaims copyright to this source code. In place of
  14516. ** a legal notice, here is a blessing:
  14517. **
  14518. ** May you do good and not evil.
  14519. ** May you find forgiveness for yourself and forgive others.
  14520. ** May you share freely, never taking more than you give.
  14521. **
  14522. ******************************************************************************
  14523. **
  14524. ** This file contains OS interface code that is common to all
  14525. ** architectures.
  14526. */
  14527. #define _SQLITE_OS_C_ 1
  14528. #undef _SQLITE_OS_C_
  14529. /*
  14530. ** The default SQLite sqlite3_vfs implementations do not allocate
  14531. ** memory (actually, os_unix.c allocates a small amount of memory
  14532. ** from within OsOpen()), but some third-party implementations may.
  14533. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14534. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14535. **
  14536. ** The following functions are instrumented for malloc() failure
  14537. ** testing:
  14538. **
  14539. ** sqlite3OsRead()
  14540. ** sqlite3OsWrite()
  14541. ** sqlite3OsSync()
  14542. ** sqlite3OsFileSize()
  14543. ** sqlite3OsLock()
  14544. ** sqlite3OsCheckReservedLock()
  14545. ** sqlite3OsFileControl()
  14546. ** sqlite3OsShmMap()
  14547. ** sqlite3OsOpen()
  14548. ** sqlite3OsDelete()
  14549. ** sqlite3OsAccess()
  14550. ** sqlite3OsFullPathname()
  14551. **
  14552. */
  14553. #if defined(SQLITE_TEST)
  14554. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14555. #define DO_OS_MALLOC_TEST(x) \
  14556. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14557. void *pTstAlloc = sqlite3Malloc(10); \
  14558. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14559. sqlite3_free(pTstAlloc); \
  14560. }
  14561. #else
  14562. #define DO_OS_MALLOC_TEST(x)
  14563. #endif
  14564. /*
  14565. ** The following routines are convenience wrappers around methods
  14566. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14567. ** of this would be completely automatic if SQLite were coded using
  14568. ** C++ instead of plain old C.
  14569. */
  14570. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14571. int rc = SQLITE_OK;
  14572. if( pId->pMethods ){
  14573. rc = pId->pMethods->xClose(pId);
  14574. pId->pMethods = 0;
  14575. }
  14576. return rc;
  14577. }
  14578. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14579. DO_OS_MALLOC_TEST(id);
  14580. return id->pMethods->xRead(id, pBuf, amt, offset);
  14581. }
  14582. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14583. DO_OS_MALLOC_TEST(id);
  14584. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14585. }
  14586. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14587. return id->pMethods->xTruncate(id, size);
  14588. }
  14589. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14590. DO_OS_MALLOC_TEST(id);
  14591. return id->pMethods->xSync(id, flags);
  14592. }
  14593. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14594. DO_OS_MALLOC_TEST(id);
  14595. return id->pMethods->xFileSize(id, pSize);
  14596. }
  14597. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14598. DO_OS_MALLOC_TEST(id);
  14599. return id->pMethods->xLock(id, lockType);
  14600. }
  14601. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14602. return id->pMethods->xUnlock(id, lockType);
  14603. }
  14604. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14605. DO_OS_MALLOC_TEST(id);
  14606. return id->pMethods->xCheckReservedLock(id, pResOut);
  14607. }
  14608. /*
  14609. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14610. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14611. ** when simply tossing information over the wall to the VFS and we do not
  14612. ** really care if the VFS receives and understands the information since it
  14613. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14614. ** routine has no return value since the return value would be meaningless.
  14615. */
  14616. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14617. DO_OS_MALLOC_TEST(id);
  14618. return id->pMethods->xFileControl(id, op, pArg);
  14619. }
  14620. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14621. (void)id->pMethods->xFileControl(id, op, pArg);
  14622. }
  14623. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14624. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14625. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14626. }
  14627. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14628. return id->pMethods->xDeviceCharacteristics(id);
  14629. }
  14630. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14631. return id->pMethods->xShmLock(id, offset, n, flags);
  14632. }
  14633. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14634. id->pMethods->xShmBarrier(id);
  14635. }
  14636. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14637. return id->pMethods->xShmUnmap(id, deleteFlag);
  14638. }
  14639. SQLITE_PRIVATE int sqlite3OsShmMap(
  14640. sqlite3_file *id, /* Database file handle */
  14641. int iPage,
  14642. int pgsz,
  14643. int bExtend, /* True to extend file if necessary */
  14644. void volatile **pp /* OUT: Pointer to mapping */
  14645. ){
  14646. DO_OS_MALLOC_TEST(id);
  14647. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14648. }
  14649. #if SQLITE_MAX_MMAP_SIZE>0
  14650. /* The real implementation of xFetch and xUnfetch */
  14651. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14652. DO_OS_MALLOC_TEST(id);
  14653. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  14654. }
  14655. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14656. return id->pMethods->xUnfetch(id, iOff, p);
  14657. }
  14658. #else
  14659. /* No-op stubs to use when memory-mapped I/O is disabled */
  14660. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14661. *pp = 0;
  14662. return SQLITE_OK;
  14663. }
  14664. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14665. return SQLITE_OK;
  14666. }
  14667. #endif
  14668. /*
  14669. ** The next group of routines are convenience wrappers around the
  14670. ** VFS methods.
  14671. */
  14672. SQLITE_PRIVATE int sqlite3OsOpen(
  14673. sqlite3_vfs *pVfs,
  14674. const char *zPath,
  14675. sqlite3_file *pFile,
  14676. int flags,
  14677. int *pFlagsOut
  14678. ){
  14679. int rc;
  14680. DO_OS_MALLOC_TEST(0);
  14681. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14682. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14683. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14684. ** reaching the VFS. */
  14685. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14686. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14687. return rc;
  14688. }
  14689. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14690. DO_OS_MALLOC_TEST(0);
  14691. assert( dirSync==0 || dirSync==1 );
  14692. return pVfs->xDelete(pVfs, zPath, dirSync);
  14693. }
  14694. SQLITE_PRIVATE int sqlite3OsAccess(
  14695. sqlite3_vfs *pVfs,
  14696. const char *zPath,
  14697. int flags,
  14698. int *pResOut
  14699. ){
  14700. DO_OS_MALLOC_TEST(0);
  14701. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14702. }
  14703. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14704. sqlite3_vfs *pVfs,
  14705. const char *zPath,
  14706. int nPathOut,
  14707. char *zPathOut
  14708. ){
  14709. DO_OS_MALLOC_TEST(0);
  14710. zPathOut[0] = 0;
  14711. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14712. }
  14713. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14714. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14715. return pVfs->xDlOpen(pVfs, zPath);
  14716. }
  14717. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14718. pVfs->xDlError(pVfs, nByte, zBufOut);
  14719. }
  14720. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14721. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14722. }
  14723. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14724. pVfs->xDlClose(pVfs, pHandle);
  14725. }
  14726. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14727. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14728. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14729. }
  14730. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14731. return pVfs->xSleep(pVfs, nMicro);
  14732. }
  14733. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14734. int rc;
  14735. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14736. ** method to get the current date and time if that method is available
  14737. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14738. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14739. ** unavailable.
  14740. */
  14741. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14742. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14743. }else{
  14744. double r;
  14745. rc = pVfs->xCurrentTime(pVfs, &r);
  14746. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14747. }
  14748. return rc;
  14749. }
  14750. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14751. sqlite3_vfs *pVfs,
  14752. const char *zFile,
  14753. sqlite3_file **ppFile,
  14754. int flags,
  14755. int *pOutFlags
  14756. ){
  14757. int rc = SQLITE_NOMEM;
  14758. sqlite3_file *pFile;
  14759. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14760. if( pFile ){
  14761. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14762. if( rc!=SQLITE_OK ){
  14763. sqlite3_free(pFile);
  14764. }else{
  14765. *ppFile = pFile;
  14766. }
  14767. }
  14768. return rc;
  14769. }
  14770. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14771. int rc = SQLITE_OK;
  14772. assert( pFile );
  14773. rc = sqlite3OsClose(pFile);
  14774. sqlite3_free(pFile);
  14775. return rc;
  14776. }
  14777. /*
  14778. ** This function is a wrapper around the OS specific implementation of
  14779. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14780. ** ability to simulate a malloc failure, so that the handling of an
  14781. ** error in sqlite3_os_init() by the upper layers can be tested.
  14782. */
  14783. SQLITE_PRIVATE int sqlite3OsInit(void){
  14784. void *p = sqlite3_malloc(10);
  14785. if( p==0 ) return SQLITE_NOMEM;
  14786. sqlite3_free(p);
  14787. return sqlite3_os_init();
  14788. }
  14789. /*
  14790. ** The list of all registered VFS implementations.
  14791. */
  14792. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14793. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14794. /*
  14795. ** Locate a VFS by name. If no name is given, simply return the
  14796. ** first VFS on the list.
  14797. */
  14798. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14799. sqlite3_vfs *pVfs = 0;
  14800. #if SQLITE_THREADSAFE
  14801. sqlite3_mutex *mutex;
  14802. #endif
  14803. #ifndef SQLITE_OMIT_AUTOINIT
  14804. int rc = sqlite3_initialize();
  14805. if( rc ) return 0;
  14806. #endif
  14807. #if SQLITE_THREADSAFE
  14808. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14809. #endif
  14810. sqlite3_mutex_enter(mutex);
  14811. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14812. if( zVfs==0 ) break;
  14813. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14814. }
  14815. sqlite3_mutex_leave(mutex);
  14816. return pVfs;
  14817. }
  14818. /*
  14819. ** Unlink a VFS from the linked list
  14820. */
  14821. static void vfsUnlink(sqlite3_vfs *pVfs){
  14822. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14823. if( pVfs==0 ){
  14824. /* No-op */
  14825. }else if( vfsList==pVfs ){
  14826. vfsList = pVfs->pNext;
  14827. }else if( vfsList ){
  14828. sqlite3_vfs *p = vfsList;
  14829. while( p->pNext && p->pNext!=pVfs ){
  14830. p = p->pNext;
  14831. }
  14832. if( p->pNext==pVfs ){
  14833. p->pNext = pVfs->pNext;
  14834. }
  14835. }
  14836. }
  14837. /*
  14838. ** Register a VFS with the system. It is harmless to register the same
  14839. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14840. ** true.
  14841. */
  14842. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14843. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14844. #ifndef SQLITE_OMIT_AUTOINIT
  14845. int rc = sqlite3_initialize();
  14846. if( rc ) return rc;
  14847. #endif
  14848. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14849. sqlite3_mutex_enter(mutex);
  14850. vfsUnlink(pVfs);
  14851. if( makeDflt || vfsList==0 ){
  14852. pVfs->pNext = vfsList;
  14853. vfsList = pVfs;
  14854. }else{
  14855. pVfs->pNext = vfsList->pNext;
  14856. vfsList->pNext = pVfs;
  14857. }
  14858. assert(vfsList);
  14859. sqlite3_mutex_leave(mutex);
  14860. return SQLITE_OK;
  14861. }
  14862. /*
  14863. ** Unregister a VFS so that it is no longer accessible.
  14864. */
  14865. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14866. #if SQLITE_THREADSAFE
  14867. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14868. #endif
  14869. sqlite3_mutex_enter(mutex);
  14870. vfsUnlink(pVfs);
  14871. sqlite3_mutex_leave(mutex);
  14872. return SQLITE_OK;
  14873. }
  14874. /************** End of os.c **************************************************/
  14875. /************** Begin file fault.c *******************************************/
  14876. /*
  14877. ** 2008 Jan 22
  14878. **
  14879. ** The author disclaims copyright to this source code. In place of
  14880. ** a legal notice, here is a blessing:
  14881. **
  14882. ** May you do good and not evil.
  14883. ** May you find forgiveness for yourself and forgive others.
  14884. ** May you share freely, never taking more than you give.
  14885. **
  14886. *************************************************************************
  14887. **
  14888. ** This file contains code to support the concept of "benign"
  14889. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14890. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14891. ** and returns 0).
  14892. **
  14893. ** Most malloc failures are non-benign. After they occur, SQLite
  14894. ** abandons the current operation and returns an error code (usually
  14895. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14896. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14897. ** is completely recoverable simply by not carrying out the resize. The
  14898. ** hash table will continue to function normally. So a malloc failure
  14899. ** during a hash table resize is a benign fault.
  14900. */
  14901. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14902. /*
  14903. ** Global variables.
  14904. */
  14905. typedef struct BenignMallocHooks BenignMallocHooks;
  14906. static SQLITE_WSD struct BenignMallocHooks {
  14907. void (*xBenignBegin)(void);
  14908. void (*xBenignEnd)(void);
  14909. } sqlite3Hooks = { 0, 0 };
  14910. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14911. ** structure. If writable static data is unsupported on the target,
  14912. ** we have to locate the state vector at run-time. In the more common
  14913. ** case where writable static data is supported, wsdHooks can refer directly
  14914. ** to the "sqlite3Hooks" state vector declared above.
  14915. */
  14916. #ifdef SQLITE_OMIT_WSD
  14917. # define wsdHooksInit \
  14918. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14919. # define wsdHooks x[0]
  14920. #else
  14921. # define wsdHooksInit
  14922. # define wsdHooks sqlite3Hooks
  14923. #endif
  14924. /*
  14925. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14926. ** sqlite3EndBenignMalloc() are called, respectively.
  14927. */
  14928. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14929. void (*xBenignBegin)(void),
  14930. void (*xBenignEnd)(void)
  14931. ){
  14932. wsdHooksInit;
  14933. wsdHooks.xBenignBegin = xBenignBegin;
  14934. wsdHooks.xBenignEnd = xBenignEnd;
  14935. }
  14936. /*
  14937. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14938. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14939. ** indicates that subsequent malloc failures are non-benign.
  14940. */
  14941. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14942. wsdHooksInit;
  14943. if( wsdHooks.xBenignBegin ){
  14944. wsdHooks.xBenignBegin();
  14945. }
  14946. }
  14947. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14948. wsdHooksInit;
  14949. if( wsdHooks.xBenignEnd ){
  14950. wsdHooks.xBenignEnd();
  14951. }
  14952. }
  14953. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14954. /************** End of fault.c ***********************************************/
  14955. /************** Begin file mem0.c ********************************************/
  14956. /*
  14957. ** 2008 October 28
  14958. **
  14959. ** The author disclaims copyright to this source code. In place of
  14960. ** a legal notice, here is a blessing:
  14961. **
  14962. ** May you do good and not evil.
  14963. ** May you find forgiveness for yourself and forgive others.
  14964. ** May you share freely, never taking more than you give.
  14965. **
  14966. *************************************************************************
  14967. **
  14968. ** This file contains a no-op memory allocation drivers for use when
  14969. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14970. ** here always fail. SQLite will not operate with these drivers. These
  14971. ** are merely placeholders. Real drivers must be substituted using
  14972. ** sqlite3_config() before SQLite will operate.
  14973. */
  14974. /*
  14975. ** This version of the memory allocator is the default. It is
  14976. ** used when no other memory allocator is specified using compile-time
  14977. ** macros.
  14978. */
  14979. #ifdef SQLITE_ZERO_MALLOC
  14980. /*
  14981. ** No-op versions of all memory allocation routines
  14982. */
  14983. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14984. static void sqlite3MemFree(void *pPrior){ return; }
  14985. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14986. static int sqlite3MemSize(void *pPrior){ return 0; }
  14987. static int sqlite3MemRoundup(int n){ return n; }
  14988. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14989. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14990. /*
  14991. ** This routine is the only routine in this file with external linkage.
  14992. **
  14993. ** Populate the low-level memory allocation function pointers in
  14994. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14995. */
  14996. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14997. static const sqlite3_mem_methods defaultMethods = {
  14998. sqlite3MemMalloc,
  14999. sqlite3MemFree,
  15000. sqlite3MemRealloc,
  15001. sqlite3MemSize,
  15002. sqlite3MemRoundup,
  15003. sqlite3MemInit,
  15004. sqlite3MemShutdown,
  15005. 0
  15006. };
  15007. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15008. }
  15009. #endif /* SQLITE_ZERO_MALLOC */
  15010. /************** End of mem0.c ************************************************/
  15011. /************** Begin file mem1.c ********************************************/
  15012. /*
  15013. ** 2007 August 14
  15014. **
  15015. ** The author disclaims copyright to this source code. In place of
  15016. ** a legal notice, here is a blessing:
  15017. **
  15018. ** May you do good and not evil.
  15019. ** May you find forgiveness for yourself and forgive others.
  15020. ** May you share freely, never taking more than you give.
  15021. **
  15022. *************************************************************************
  15023. **
  15024. ** This file contains low-level memory allocation drivers for when
  15025. ** SQLite will use the standard C-library malloc/realloc/free interface
  15026. ** to obtain the memory it needs.
  15027. **
  15028. ** This file contains implementations of the low-level memory allocation
  15029. ** routines specified in the sqlite3_mem_methods object. The content of
  15030. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  15031. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  15032. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  15033. ** default configuration is to use memory allocation routines in this
  15034. ** file.
  15035. **
  15036. ** C-preprocessor macro summary:
  15037. **
  15038. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  15039. ** the malloc_usable_size() interface exists
  15040. ** on the target platform. Or, this symbol
  15041. ** can be set manually, if desired.
  15042. ** If an equivalent interface exists by
  15043. ** a different name, using a separate -D
  15044. ** option to rename it.
  15045. **
  15046. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  15047. ** memory allocator. Set this symbol to enable
  15048. ** building on older macs.
  15049. **
  15050. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  15051. ** _msize() on windows systems. This might
  15052. ** be necessary when compiling for Delphi,
  15053. ** for example.
  15054. */
  15055. /*
  15056. ** This version of the memory allocator is the default. It is
  15057. ** used when no other memory allocator is specified using compile-time
  15058. ** macros.
  15059. */
  15060. #ifdef SQLITE_SYSTEM_MALLOC
  15061. /*
  15062. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  15063. ** The use of _msize() is automatic, but can be disabled by compiling
  15064. ** with -DSQLITE_WITHOUT_MSIZE
  15065. */
  15066. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15067. # define SQLITE_MALLOCSIZE _msize
  15068. #endif
  15069. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15070. /*
  15071. ** Use the zone allocator available on apple products unless the
  15072. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15073. */
  15074. #include <sys/sysctl.h>
  15075. #include <malloc/malloc.h>
  15076. #include <libkern/OSAtomic.h>
  15077. static malloc_zone_t* _sqliteZone_;
  15078. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15079. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15080. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15081. #define SQLITE_MALLOCSIZE(x) \
  15082. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15083. #elif defined(SQLITE_OS_RTTHREAD)
  15084. #include <rtthread.h>
  15085. /*
  15086. ** Use standard C library malloc and free on non-Apple systems.
  15087. ** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15088. */
  15089. #define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x)
  15090. #define SQLITE_FREE(x) rt_free(x)
  15091. #define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y))
  15092. #if (!defined(SQLITE_WITHOUT_MSIZE)) \
  15093. && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15094. # error "not have malloc_usable_size()"
  15095. #endif
  15096. #ifdef HAVE_MALLOC_USABLE_SIZE
  15097. # undef SQLITE_MALLOCSIZE
  15098. #endif
  15099. #else /* if not __APPLE__ */
  15100. /*
  15101. ** Use standard C library malloc and free on non-Apple systems.
  15102. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15103. */
  15104. #define SQLITE_MALLOC(x) malloc(x)
  15105. #define SQLITE_FREE(x) free(x)
  15106. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15107. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  15108. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15109. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  15110. #endif
  15111. #ifdef HAVE_MALLOC_USABLE_SIZE
  15112. # ifndef SQLITE_MALLOCSIZE
  15113. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15114. # endif
  15115. #else
  15116. # undef SQLITE_MALLOCSIZE
  15117. #endif
  15118. #endif /* __APPLE__ or not __APPLE__ */
  15119. /*
  15120. ** Like malloc(), but remember the size of the allocation
  15121. ** so that we can find it later using sqlite3MemSize().
  15122. **
  15123. ** For this low-level routine, we are guaranteed that nByte>0 because
  15124. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15125. ** routines.
  15126. */
  15127. static void *sqlite3MemMalloc(int nByte){
  15128. #ifdef SQLITE_MALLOCSIZE
  15129. void *p = SQLITE_MALLOC( nByte );
  15130. if( p==0 ){
  15131. testcase( sqlite3GlobalConfig.xLog!=0 );
  15132. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15133. }
  15134. return p;
  15135. #else
  15136. sqlite3_int64 *p;
  15137. assert( nByte>0 );
  15138. nByte = ROUND8(nByte);
  15139. p = SQLITE_MALLOC( nByte+8 );
  15140. if( p ){
  15141. p[0] = nByte;
  15142. p++;
  15143. }else{
  15144. testcase( sqlite3GlobalConfig.xLog!=0 );
  15145. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15146. }
  15147. return (void *)p;
  15148. #endif
  15149. }
  15150. /*
  15151. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15152. ** or sqlite3MemRealloc().
  15153. **
  15154. ** For this low-level routine, we already know that pPrior!=0 since
  15155. ** cases where pPrior==0 will have been intecepted and dealt with
  15156. ** by higher-level routines.
  15157. */
  15158. static void sqlite3MemFree(void *pPrior){
  15159. #ifdef SQLITE_MALLOCSIZE
  15160. SQLITE_FREE(pPrior);
  15161. #else
  15162. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15163. assert( pPrior!=0 );
  15164. p--;
  15165. SQLITE_FREE(p);
  15166. #endif
  15167. }
  15168. /*
  15169. ** Report the allocated size of a prior return from xMalloc()
  15170. ** or xRealloc().
  15171. */
  15172. static int sqlite3MemSize(void *pPrior){
  15173. #ifdef SQLITE_MALLOCSIZE
  15174. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15175. #else
  15176. sqlite3_int64 *p;
  15177. if( pPrior==0 ) return 0;
  15178. p = (sqlite3_int64*)pPrior;
  15179. p--;
  15180. return (int)p[0];
  15181. #endif
  15182. }
  15183. /*
  15184. ** Like realloc(). Resize an allocation previously obtained from
  15185. ** sqlite3MemMalloc().
  15186. **
  15187. ** For this low-level interface, we know that pPrior!=0. Cases where
  15188. ** pPrior==0 while have been intercepted by higher-level routine and
  15189. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  15190. ** cases where nByte<=0 will have been intercepted by higher-level
  15191. ** routines and redirected to xFree.
  15192. */
  15193. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15194. #ifdef SQLITE_MALLOCSIZE
  15195. void *p = SQLITE_REALLOC(pPrior, nByte);
  15196. if( p==0 ){
  15197. testcase( sqlite3GlobalConfig.xLog!=0 );
  15198. sqlite3_log(SQLITE_NOMEM,
  15199. "failed memory resize %u to %u bytes",
  15200. SQLITE_MALLOCSIZE(pPrior), nByte);
  15201. }
  15202. return p;
  15203. #else
  15204. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15205. assert( pPrior!=0 && nByte>0 );
  15206. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15207. p--;
  15208. p = SQLITE_REALLOC(p, nByte+8 );
  15209. if( p ){
  15210. p[0] = nByte;
  15211. p++;
  15212. }else{
  15213. testcase( sqlite3GlobalConfig.xLog!=0 );
  15214. sqlite3_log(SQLITE_NOMEM,
  15215. "failed memory resize %u to %u bytes",
  15216. sqlite3MemSize(pPrior), nByte);
  15217. }
  15218. return (void*)p;
  15219. #endif
  15220. }
  15221. /*
  15222. ** Round up a request size to the next valid allocation size.
  15223. */
  15224. static int sqlite3MemRoundup(int n){
  15225. return ROUND8(n);
  15226. }
  15227. /*
  15228. ** Initialize this module.
  15229. */
  15230. static int sqlite3MemInit(void *NotUsed){
  15231. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15232. int cpuCount;
  15233. size_t len;
  15234. if( _sqliteZone_ ){
  15235. return SQLITE_OK;
  15236. }
  15237. len = sizeof(cpuCount);
  15238. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15239. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15240. if( cpuCount>1 ){
  15241. /* defer MT decisions to system malloc */
  15242. _sqliteZone_ = malloc_default_zone();
  15243. }else{
  15244. /* only 1 core, use our own zone to contention over global locks,
  15245. ** e.g. we have our own dedicated locks */
  15246. bool success;
  15247. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15248. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15249. do{
  15250. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15251. (void * volatile *)&_sqliteZone_);
  15252. }while(!_sqliteZone_);
  15253. if( !success ){
  15254. /* somebody registered a zone first */
  15255. malloc_destroy_zone(newzone);
  15256. }
  15257. }
  15258. #endif
  15259. UNUSED_PARAMETER(NotUsed);
  15260. return SQLITE_OK;
  15261. }
  15262. /*
  15263. ** Deinitialize this module.
  15264. */
  15265. static void sqlite3MemShutdown(void *NotUsed){
  15266. UNUSED_PARAMETER(NotUsed);
  15267. return;
  15268. }
  15269. /*
  15270. ** This routine is the only routine in this file with external linkage.
  15271. **
  15272. ** Populate the low-level memory allocation function pointers in
  15273. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15274. */
  15275. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15276. static const sqlite3_mem_methods defaultMethods = {
  15277. sqlite3MemMalloc,
  15278. sqlite3MemFree,
  15279. sqlite3MemRealloc,
  15280. sqlite3MemSize,
  15281. sqlite3MemRoundup,
  15282. sqlite3MemInit,
  15283. sqlite3MemShutdown,
  15284. 0
  15285. };
  15286. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15287. }
  15288. #endif /* SQLITE_SYSTEM_MALLOC */
  15289. /************** End of mem1.c ************************************************/
  15290. /************** Begin file mem2.c ********************************************/
  15291. /*
  15292. ** 2007 August 15
  15293. **
  15294. ** The author disclaims copyright to this source code. In place of
  15295. ** a legal notice, here is a blessing:
  15296. **
  15297. ** May you do good and not evil.
  15298. ** May you find forgiveness for yourself and forgive others.
  15299. ** May you share freely, never taking more than you give.
  15300. **
  15301. *************************************************************************
  15302. **
  15303. ** This file contains low-level memory allocation drivers for when
  15304. ** SQLite will use the standard C-library malloc/realloc/free interface
  15305. ** to obtain the memory it needs while adding lots of additional debugging
  15306. ** information to each allocation in order to help detect and fix memory
  15307. ** leaks and memory usage errors.
  15308. **
  15309. ** This file contains implementations of the low-level memory allocation
  15310. ** routines specified in the sqlite3_mem_methods object.
  15311. */
  15312. /*
  15313. ** This version of the memory allocator is used only if the
  15314. ** SQLITE_MEMDEBUG macro is defined
  15315. */
  15316. #ifdef SQLITE_MEMDEBUG
  15317. /*
  15318. ** The backtrace functionality is only available with GLIBC
  15319. */
  15320. #ifdef __GLIBC__
  15321. extern int backtrace(void**,int);
  15322. extern void backtrace_symbols_fd(void*const*,int,int);
  15323. #else
  15324. # define backtrace(A,B) 1
  15325. # define backtrace_symbols_fd(A,B,C)
  15326. #endif
  15327. /* #include <stdio.h> */
  15328. /*
  15329. ** Each memory allocation looks like this:
  15330. **
  15331. ** ------------------------------------------------------------------------
  15332. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15333. ** ------------------------------------------------------------------------
  15334. **
  15335. ** The application code sees only a pointer to the allocation. We have
  15336. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15337. ** MemBlockHdr tells us the size of the allocation and the number of
  15338. ** backtrace pointers. There is also a guard word at the end of the
  15339. ** MemBlockHdr.
  15340. */
  15341. struct MemBlockHdr {
  15342. i64 iSize; /* Size of this allocation */
  15343. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15344. char nBacktrace; /* Number of backtraces on this alloc */
  15345. char nBacktraceSlots; /* Available backtrace slots */
  15346. u8 nTitle; /* Bytes of title; includes '\0' */
  15347. u8 eType; /* Allocation type code */
  15348. int iForeGuard; /* Guard word for sanity */
  15349. };
  15350. /*
  15351. ** Guard words
  15352. */
  15353. #define FOREGUARD 0x80F5E153
  15354. #define REARGUARD 0xE4676B53
  15355. /*
  15356. ** Number of malloc size increments to track.
  15357. */
  15358. #define NCSIZE 1000
  15359. /*
  15360. ** All of the static variables used by this module are collected
  15361. ** into a single structure named "mem". This is to keep the
  15362. ** static variables organized and to reduce namespace pollution
  15363. ** when this module is combined with other in the amalgamation.
  15364. */
  15365. static struct {
  15366. /*
  15367. ** Mutex to control access to the memory allocation subsystem.
  15368. */
  15369. sqlite3_mutex *mutex;
  15370. /*
  15371. ** Head and tail of a linked list of all outstanding allocations
  15372. */
  15373. struct MemBlockHdr *pFirst;
  15374. struct MemBlockHdr *pLast;
  15375. /*
  15376. ** The number of levels of backtrace to save in new allocations.
  15377. */
  15378. int nBacktrace;
  15379. void (*xBacktrace)(int, int, void **);
  15380. /*
  15381. ** Title text to insert in front of each block
  15382. */
  15383. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15384. char zTitle[100]; /* The title text */
  15385. /*
  15386. ** sqlite3MallocDisallow() increments the following counter.
  15387. ** sqlite3MallocAllow() decrements it.
  15388. */
  15389. int disallow; /* Do not allow memory allocation */
  15390. /*
  15391. ** Gather statistics on the sizes of memory allocations.
  15392. ** nAlloc[i] is the number of allocation attempts of i*8
  15393. ** bytes. i==NCSIZE is the number of allocation attempts for
  15394. ** sizes more than NCSIZE*8 bytes.
  15395. */
  15396. int nAlloc[NCSIZE]; /* Total number of allocations */
  15397. int nCurrent[NCSIZE]; /* Current number of allocations */
  15398. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15399. } mem;
  15400. /*
  15401. ** Adjust memory usage statistics
  15402. */
  15403. static void adjustStats(int iSize, int increment){
  15404. int i = ROUND8(iSize)/8;
  15405. if( i>NCSIZE-1 ){
  15406. i = NCSIZE - 1;
  15407. }
  15408. if( increment>0 ){
  15409. mem.nAlloc[i]++;
  15410. mem.nCurrent[i]++;
  15411. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15412. mem.mxCurrent[i] = mem.nCurrent[i];
  15413. }
  15414. }else{
  15415. mem.nCurrent[i]--;
  15416. assert( mem.nCurrent[i]>=0 );
  15417. }
  15418. }
  15419. /*
  15420. ** Given an allocation, find the MemBlockHdr for that allocation.
  15421. **
  15422. ** This routine checks the guards at either end of the allocation and
  15423. ** if they are incorrect it asserts.
  15424. */
  15425. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15426. struct MemBlockHdr *p;
  15427. int *pInt;
  15428. u8 *pU8;
  15429. int nReserve;
  15430. p = (struct MemBlockHdr*)pAllocation;
  15431. p--;
  15432. assert( p->iForeGuard==(int)FOREGUARD );
  15433. nReserve = ROUND8(p->iSize);
  15434. pInt = (int*)pAllocation;
  15435. pU8 = (u8*)pAllocation;
  15436. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15437. /* This checks any of the "extra" bytes allocated due
  15438. ** to rounding up to an 8 byte boundary to ensure
  15439. ** they haven't been overwritten.
  15440. */
  15441. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15442. return p;
  15443. }
  15444. /*
  15445. ** Return the number of bytes currently allocated at address p.
  15446. */
  15447. static int sqlite3MemSize(void *p){
  15448. struct MemBlockHdr *pHdr;
  15449. if( !p ){
  15450. return 0;
  15451. }
  15452. pHdr = sqlite3MemsysGetHeader(p);
  15453. return (int)pHdr->iSize;
  15454. }
  15455. /*
  15456. ** Initialize the memory allocation subsystem.
  15457. */
  15458. static int sqlite3MemInit(void *NotUsed){
  15459. UNUSED_PARAMETER(NotUsed);
  15460. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15461. if( !sqlite3GlobalConfig.bMemstat ){
  15462. /* If memory status is enabled, then the malloc.c wrapper will already
  15463. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15464. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15465. }
  15466. return SQLITE_OK;
  15467. }
  15468. /*
  15469. ** Deinitialize the memory allocation subsystem.
  15470. */
  15471. static void sqlite3MemShutdown(void *NotUsed){
  15472. UNUSED_PARAMETER(NotUsed);
  15473. mem.mutex = 0;
  15474. }
  15475. /*
  15476. ** Round up a request size to the next valid allocation size.
  15477. */
  15478. static int sqlite3MemRoundup(int n){
  15479. return ROUND8(n);
  15480. }
  15481. /*
  15482. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15483. ** the content of a new memory allocation to unpredictable values and
  15484. ** to clear the content of a freed allocation to unpredictable values.
  15485. */
  15486. static void randomFill(char *pBuf, int nByte){
  15487. unsigned int x, y, r;
  15488. x = SQLITE_PTR_TO_INT(pBuf);
  15489. y = nByte | 1;
  15490. while( nByte >= 4 ){
  15491. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15492. y = y*1103515245 + 12345;
  15493. r = x ^ y;
  15494. *(int*)pBuf = r;
  15495. pBuf += 4;
  15496. nByte -= 4;
  15497. }
  15498. while( nByte-- > 0 ){
  15499. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15500. y = y*1103515245 + 12345;
  15501. r = x ^ y;
  15502. *(pBuf++) = r & 0xff;
  15503. }
  15504. }
  15505. /*
  15506. ** Allocate nByte bytes of memory.
  15507. */
  15508. static void *sqlite3MemMalloc(int nByte){
  15509. struct MemBlockHdr *pHdr;
  15510. void **pBt;
  15511. char *z;
  15512. int *pInt;
  15513. void *p = 0;
  15514. int totalSize;
  15515. int nReserve;
  15516. sqlite3_mutex_enter(mem.mutex);
  15517. assert( mem.disallow==0 );
  15518. nReserve = ROUND8(nByte);
  15519. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15520. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15521. p = malloc(totalSize);
  15522. if( p ){
  15523. z = p;
  15524. pBt = (void**)&z[mem.nTitle];
  15525. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15526. pHdr->pNext = 0;
  15527. pHdr->pPrev = mem.pLast;
  15528. if( mem.pLast ){
  15529. mem.pLast->pNext = pHdr;
  15530. }else{
  15531. mem.pFirst = pHdr;
  15532. }
  15533. mem.pLast = pHdr;
  15534. pHdr->iForeGuard = FOREGUARD;
  15535. pHdr->eType = MEMTYPE_HEAP;
  15536. pHdr->nBacktraceSlots = mem.nBacktrace;
  15537. pHdr->nTitle = mem.nTitle;
  15538. if( mem.nBacktrace ){
  15539. void *aAddr[40];
  15540. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15541. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15542. assert(pBt[0]);
  15543. if( mem.xBacktrace ){
  15544. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15545. }
  15546. }else{
  15547. pHdr->nBacktrace = 0;
  15548. }
  15549. if( mem.nTitle ){
  15550. memcpy(z, mem.zTitle, mem.nTitle);
  15551. }
  15552. pHdr->iSize = nByte;
  15553. adjustStats(nByte, +1);
  15554. pInt = (int*)&pHdr[1];
  15555. pInt[nReserve/sizeof(int)] = REARGUARD;
  15556. randomFill((char*)pInt, nByte);
  15557. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15558. p = (void*)pInt;
  15559. }
  15560. sqlite3_mutex_leave(mem.mutex);
  15561. return p;
  15562. }
  15563. /*
  15564. ** Free memory.
  15565. */
  15566. static void sqlite3MemFree(void *pPrior){
  15567. struct MemBlockHdr *pHdr;
  15568. void **pBt;
  15569. char *z;
  15570. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15571. || mem.mutex!=0 );
  15572. pHdr = sqlite3MemsysGetHeader(pPrior);
  15573. pBt = (void**)pHdr;
  15574. pBt -= pHdr->nBacktraceSlots;
  15575. sqlite3_mutex_enter(mem.mutex);
  15576. if( pHdr->pPrev ){
  15577. assert( pHdr->pPrev->pNext==pHdr );
  15578. pHdr->pPrev->pNext = pHdr->pNext;
  15579. }else{
  15580. assert( mem.pFirst==pHdr );
  15581. mem.pFirst = pHdr->pNext;
  15582. }
  15583. if( pHdr->pNext ){
  15584. assert( pHdr->pNext->pPrev==pHdr );
  15585. pHdr->pNext->pPrev = pHdr->pPrev;
  15586. }else{
  15587. assert( mem.pLast==pHdr );
  15588. mem.pLast = pHdr->pPrev;
  15589. }
  15590. z = (char*)pBt;
  15591. z -= pHdr->nTitle;
  15592. adjustStats((int)pHdr->iSize, -1);
  15593. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15594. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15595. free(z);
  15596. sqlite3_mutex_leave(mem.mutex);
  15597. }
  15598. /*
  15599. ** Change the size of an existing memory allocation.
  15600. **
  15601. ** For this debugging implementation, we *always* make a copy of the
  15602. ** allocation into a new place in memory. In this way, if the
  15603. ** higher level code is using pointer to the old allocation, it is
  15604. ** much more likely to break and we are much more liking to find
  15605. ** the error.
  15606. */
  15607. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15608. struct MemBlockHdr *pOldHdr;
  15609. void *pNew;
  15610. assert( mem.disallow==0 );
  15611. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15612. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15613. pNew = sqlite3MemMalloc(nByte);
  15614. if( pNew ){
  15615. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  15616. if( nByte>pOldHdr->iSize ){
  15617. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  15618. }
  15619. sqlite3MemFree(pPrior);
  15620. }
  15621. return pNew;
  15622. }
  15623. /*
  15624. ** Populate the low-level memory allocation function pointers in
  15625. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15626. */
  15627. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15628. static const sqlite3_mem_methods defaultMethods = {
  15629. sqlite3MemMalloc,
  15630. sqlite3MemFree,
  15631. sqlite3MemRealloc,
  15632. sqlite3MemSize,
  15633. sqlite3MemRoundup,
  15634. sqlite3MemInit,
  15635. sqlite3MemShutdown,
  15636. 0
  15637. };
  15638. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15639. }
  15640. /*
  15641. ** Set the "type" of an allocation.
  15642. */
  15643. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15644. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15645. struct MemBlockHdr *pHdr;
  15646. pHdr = sqlite3MemsysGetHeader(p);
  15647. assert( pHdr->iForeGuard==FOREGUARD );
  15648. pHdr->eType = eType;
  15649. }
  15650. }
  15651. /*
  15652. ** Return TRUE if the mask of type in eType matches the type of the
  15653. ** allocation p. Also return true if p==NULL.
  15654. **
  15655. ** This routine is designed for use within an assert() statement, to
  15656. ** verify the type of an allocation. For example:
  15657. **
  15658. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15659. */
  15660. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15661. int rc = 1;
  15662. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15663. struct MemBlockHdr *pHdr;
  15664. pHdr = sqlite3MemsysGetHeader(p);
  15665. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15666. if( (pHdr->eType&eType)==0 ){
  15667. rc = 0;
  15668. }
  15669. }
  15670. return rc;
  15671. }
  15672. /*
  15673. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15674. ** allocation p. Also return true if p==NULL.
  15675. **
  15676. ** This routine is designed for use within an assert() statement, to
  15677. ** verify the type of an allocation. For example:
  15678. **
  15679. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15680. */
  15681. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15682. int rc = 1;
  15683. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15684. struct MemBlockHdr *pHdr;
  15685. pHdr = sqlite3MemsysGetHeader(p);
  15686. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15687. if( (pHdr->eType&eType)!=0 ){
  15688. rc = 0;
  15689. }
  15690. }
  15691. return rc;
  15692. }
  15693. /*
  15694. ** Set the number of backtrace levels kept for each allocation.
  15695. ** A value of zero turns off backtracing. The number is always rounded
  15696. ** up to a multiple of 2.
  15697. */
  15698. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15699. if( depth<0 ){ depth = 0; }
  15700. if( depth>20 ){ depth = 20; }
  15701. depth = (depth+1)&0xfe;
  15702. mem.nBacktrace = depth;
  15703. }
  15704. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15705. mem.xBacktrace = xBacktrace;
  15706. }
  15707. /*
  15708. ** Set the title string for subsequent allocations.
  15709. */
  15710. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15711. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15712. sqlite3_mutex_enter(mem.mutex);
  15713. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15714. memcpy(mem.zTitle, zTitle, n);
  15715. mem.zTitle[n] = 0;
  15716. mem.nTitle = ROUND8(n);
  15717. sqlite3_mutex_leave(mem.mutex);
  15718. }
  15719. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15720. struct MemBlockHdr *pHdr;
  15721. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15722. void **pBt = (void**)pHdr;
  15723. pBt -= pHdr->nBacktraceSlots;
  15724. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15725. }
  15726. }
  15727. /*
  15728. ** Open the file indicated and write a log of all unfreed memory
  15729. ** allocations into that log.
  15730. */
  15731. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15732. FILE *out;
  15733. struct MemBlockHdr *pHdr;
  15734. void **pBt;
  15735. int i;
  15736. out = fopen(zFilename, "w");
  15737. if( out==0 ){
  15738. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15739. zFilename);
  15740. return;
  15741. }
  15742. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15743. char *z = (char*)pHdr;
  15744. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15745. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15746. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15747. if( pHdr->nBacktrace ){
  15748. fflush(out);
  15749. pBt = (void**)pHdr;
  15750. pBt -= pHdr->nBacktraceSlots;
  15751. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15752. fprintf(out, "\n");
  15753. }
  15754. }
  15755. fprintf(out, "COUNTS:\n");
  15756. for(i=0; i<NCSIZE-1; i++){
  15757. if( mem.nAlloc[i] ){
  15758. fprintf(out, " %5d: %10d %10d %10d\n",
  15759. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15760. }
  15761. }
  15762. if( mem.nAlloc[NCSIZE-1] ){
  15763. fprintf(out, " %5d: %10d %10d %10d\n",
  15764. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15765. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15766. }
  15767. fclose(out);
  15768. }
  15769. /*
  15770. ** Return the number of times sqlite3MemMalloc() has been called.
  15771. */
  15772. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15773. int i;
  15774. int nTotal = 0;
  15775. for(i=0; i<NCSIZE; i++){
  15776. nTotal += mem.nAlloc[i];
  15777. }
  15778. return nTotal;
  15779. }
  15780. #endif /* SQLITE_MEMDEBUG */
  15781. /************** End of mem2.c ************************************************/
  15782. /************** Begin file mem3.c ********************************************/
  15783. /*
  15784. ** 2007 October 14
  15785. **
  15786. ** The author disclaims copyright to this source code. In place of
  15787. ** a legal notice, here is a blessing:
  15788. **
  15789. ** May you do good and not evil.
  15790. ** May you find forgiveness for yourself and forgive others.
  15791. ** May you share freely, never taking more than you give.
  15792. **
  15793. *************************************************************************
  15794. ** This file contains the C functions that implement a memory
  15795. ** allocation subsystem for use by SQLite.
  15796. **
  15797. ** This version of the memory allocation subsystem omits all
  15798. ** use of malloc(). The SQLite user supplies a block of memory
  15799. ** before calling sqlite3_initialize() from which allocations
  15800. ** are made and returned by the xMalloc() and xRealloc()
  15801. ** implementations. Once sqlite3_initialize() has been called,
  15802. ** the amount of memory available to SQLite is fixed and cannot
  15803. ** be changed.
  15804. **
  15805. ** This version of the memory allocation subsystem is included
  15806. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15807. */
  15808. /*
  15809. ** This version of the memory allocator is only built into the library
  15810. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15811. ** mean that the library will use a memory-pool by default, just that
  15812. ** it is available. The mempool allocator is activated by calling
  15813. ** sqlite3_config().
  15814. */
  15815. #ifdef SQLITE_ENABLE_MEMSYS3
  15816. /*
  15817. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15818. */
  15819. #define MX_SMALL 10
  15820. /*
  15821. ** Number of freelist hash slots
  15822. */
  15823. #define N_HASH 61
  15824. /*
  15825. ** A memory allocation (also called a "chunk") consists of two or
  15826. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15827. ** a header that is not returned to the user.
  15828. **
  15829. ** A chunk is two or more blocks that is either checked out or
  15830. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15831. ** size of the allocation in blocks if the allocation is free.
  15832. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15833. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15834. ** is true if the previous chunk is checked out and false if the
  15835. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15836. ** the previous chunk in blocks if the previous chunk is on the
  15837. ** freelist. If the previous chunk is checked out, then
  15838. ** u.hdr.prevSize can be part of the data for that chunk and should
  15839. ** not be read or written.
  15840. **
  15841. ** We often identify a chunk by its index in mem3.aPool[]. When
  15842. ** this is done, the chunk index refers to the second block of
  15843. ** the chunk. In this way, the first chunk has an index of 1.
  15844. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15845. ** of a NULL pointer.
  15846. **
  15847. ** The second block of free chunks is of the form u.list. The
  15848. ** two fields form a double-linked list of chunks of related sizes.
  15849. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15850. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15851. **
  15852. ** The second block of a chunk is user data if the chunk is checked
  15853. ** out. If a chunk is checked out, the user data may extend into
  15854. ** the u.hdr.prevSize value of the following chunk.
  15855. */
  15856. typedef struct Mem3Block Mem3Block;
  15857. struct Mem3Block {
  15858. union {
  15859. struct {
  15860. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15861. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15862. } hdr;
  15863. struct {
  15864. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15865. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15866. } list;
  15867. } u;
  15868. };
  15869. /*
  15870. ** All of the static variables used by this module are collected
  15871. ** into a single structure named "mem3". This is to keep the
  15872. ** static variables organized and to reduce namespace pollution
  15873. ** when this module is combined with other in the amalgamation.
  15874. */
  15875. static SQLITE_WSD struct Mem3Global {
  15876. /*
  15877. ** Memory available for allocation. nPool is the size of the array
  15878. ** (in Mem3Blocks) pointed to by aPool less 2.
  15879. */
  15880. u32 nPool;
  15881. Mem3Block *aPool;
  15882. /*
  15883. ** True if we are evaluating an out-of-memory callback.
  15884. */
  15885. int alarmBusy;
  15886. /*
  15887. ** Mutex to control access to the memory allocation subsystem.
  15888. */
  15889. sqlite3_mutex *mutex;
  15890. /*
  15891. ** The minimum amount of free space that we have seen.
  15892. */
  15893. u32 mnMaster;
  15894. /*
  15895. ** iMaster is the index of the master chunk. Most new allocations
  15896. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15897. ** of the current master. iMaster is 0 if there is not master chunk.
  15898. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15899. */
  15900. u32 iMaster;
  15901. u32 szMaster;
  15902. /*
  15903. ** Array of lists of free blocks according to the block size
  15904. ** for smaller chunks, or a hash on the block size for larger
  15905. ** chunks.
  15906. */
  15907. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15908. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15909. } mem3 = { 97535575 };
  15910. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15911. /*
  15912. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15913. ** on. *pRoot is the list that i is a member of.
  15914. */
  15915. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15916. u32 next = mem3.aPool[i].u.list.next;
  15917. u32 prev = mem3.aPool[i].u.list.prev;
  15918. assert( sqlite3_mutex_held(mem3.mutex) );
  15919. if( prev==0 ){
  15920. *pRoot = next;
  15921. }else{
  15922. mem3.aPool[prev].u.list.next = next;
  15923. }
  15924. if( next ){
  15925. mem3.aPool[next].u.list.prev = prev;
  15926. }
  15927. mem3.aPool[i].u.list.next = 0;
  15928. mem3.aPool[i].u.list.prev = 0;
  15929. }
  15930. /*
  15931. ** Unlink the chunk at index i from
  15932. ** whatever list is currently a member of.
  15933. */
  15934. static void memsys3Unlink(u32 i){
  15935. u32 size, hash;
  15936. assert( sqlite3_mutex_held(mem3.mutex) );
  15937. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15938. assert( i>=1 );
  15939. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15940. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15941. assert( size>=2 );
  15942. if( size <= MX_SMALL ){
  15943. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15944. }else{
  15945. hash = size % N_HASH;
  15946. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15947. }
  15948. }
  15949. /*
  15950. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15951. ** at *pRoot.
  15952. */
  15953. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15954. assert( sqlite3_mutex_held(mem3.mutex) );
  15955. mem3.aPool[i].u.list.next = *pRoot;
  15956. mem3.aPool[i].u.list.prev = 0;
  15957. if( *pRoot ){
  15958. mem3.aPool[*pRoot].u.list.prev = i;
  15959. }
  15960. *pRoot = i;
  15961. }
  15962. /*
  15963. ** Link the chunk at index i into either the appropriate
  15964. ** small chunk list, or into the large chunk hash table.
  15965. */
  15966. static void memsys3Link(u32 i){
  15967. u32 size, hash;
  15968. assert( sqlite3_mutex_held(mem3.mutex) );
  15969. assert( i>=1 );
  15970. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15971. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15972. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15973. assert( size>=2 );
  15974. if( size <= MX_SMALL ){
  15975. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15976. }else{
  15977. hash = size % N_HASH;
  15978. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15979. }
  15980. }
  15981. /*
  15982. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15983. ** will already be held (obtained by code in malloc.c) if
  15984. ** sqlite3GlobalConfig.bMemStat is true.
  15985. */
  15986. static void memsys3Enter(void){
  15987. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15988. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15989. }
  15990. sqlite3_mutex_enter(mem3.mutex);
  15991. }
  15992. static void memsys3Leave(void){
  15993. sqlite3_mutex_leave(mem3.mutex);
  15994. }
  15995. /*
  15996. ** Called when we are unable to satisfy an allocation of nBytes.
  15997. */
  15998. static void memsys3OutOfMemory(int nByte){
  15999. if( !mem3.alarmBusy ){
  16000. mem3.alarmBusy = 1;
  16001. assert( sqlite3_mutex_held(mem3.mutex) );
  16002. sqlite3_mutex_leave(mem3.mutex);
  16003. sqlite3_release_memory(nByte);
  16004. sqlite3_mutex_enter(mem3.mutex);
  16005. mem3.alarmBusy = 0;
  16006. }
  16007. }
  16008. /*
  16009. ** Chunk i is a free chunk that has been unlinked. Adjust its
  16010. ** size parameters for check-out and return a pointer to the
  16011. ** user portion of the chunk.
  16012. */
  16013. static void *memsys3Checkout(u32 i, u32 nBlock){
  16014. u32 x;
  16015. assert( sqlite3_mutex_held(mem3.mutex) );
  16016. assert( i>=1 );
  16017. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  16018. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  16019. x = mem3.aPool[i-1].u.hdr.size4x;
  16020. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  16021. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  16022. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  16023. return &mem3.aPool[i];
  16024. }
  16025. /*
  16026. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  16027. ** Return a pointer to the new allocation. Or, if the master chunk
  16028. ** is not large enough, return 0.
  16029. */
  16030. static void *memsys3FromMaster(u32 nBlock){
  16031. assert( sqlite3_mutex_held(mem3.mutex) );
  16032. assert( mem3.szMaster>=nBlock );
  16033. if( nBlock>=mem3.szMaster-1 ){
  16034. /* Use the entire master */
  16035. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  16036. mem3.iMaster = 0;
  16037. mem3.szMaster = 0;
  16038. mem3.mnMaster = 0;
  16039. return p;
  16040. }else{
  16041. /* Split the master block. Return the tail. */
  16042. u32 newi, x;
  16043. newi = mem3.iMaster + mem3.szMaster - nBlock;
  16044. assert( newi > mem3.iMaster+1 );
  16045. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  16046. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  16047. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  16048. mem3.szMaster -= nBlock;
  16049. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  16050. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16051. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16052. if( mem3.szMaster < mem3.mnMaster ){
  16053. mem3.mnMaster = mem3.szMaster;
  16054. }
  16055. return (void*)&mem3.aPool[newi];
  16056. }
  16057. }
  16058. /*
  16059. ** *pRoot is the head of a list of free chunks of the same size
  16060. ** or same size hash. In other words, *pRoot is an entry in either
  16061. ** mem3.aiSmall[] or mem3.aiHash[].
  16062. **
  16063. ** This routine examines all entries on the given list and tries
  16064. ** to coalesce each entries with adjacent free chunks.
  16065. **
  16066. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  16067. ** the current mem3.iMaster with the new larger chunk. In order for
  16068. ** this mem3.iMaster replacement to work, the master chunk must be
  16069. ** linked into the hash tables. That is not the normal state of
  16070. ** affairs, of course. The calling routine must link the master
  16071. ** chunk before invoking this routine, then must unlink the (possibly
  16072. ** changed) master chunk once this routine has finished.
  16073. */
  16074. static void memsys3Merge(u32 *pRoot){
  16075. u32 iNext, prev, size, i, x;
  16076. assert( sqlite3_mutex_held(mem3.mutex) );
  16077. for(i=*pRoot; i>0; i=iNext){
  16078. iNext = mem3.aPool[i].u.list.next;
  16079. size = mem3.aPool[i-1].u.hdr.size4x;
  16080. assert( (size&1)==0 );
  16081. if( (size&2)==0 ){
  16082. memsys3UnlinkFromList(i, pRoot);
  16083. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16084. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16085. if( prev==iNext ){
  16086. iNext = mem3.aPool[prev].u.list.next;
  16087. }
  16088. memsys3Unlink(prev);
  16089. size = i + size/4 - prev;
  16090. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16091. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16092. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16093. memsys3Link(prev);
  16094. i = prev;
  16095. }else{
  16096. size /= 4;
  16097. }
  16098. if( size>mem3.szMaster ){
  16099. mem3.iMaster = i;
  16100. mem3.szMaster = size;
  16101. }
  16102. }
  16103. }
  16104. /*
  16105. ** Return a block of memory of at least nBytes in size.
  16106. ** Return NULL if unable.
  16107. **
  16108. ** This function assumes that the necessary mutexes, if any, are
  16109. ** already held by the caller. Hence "Unsafe".
  16110. */
  16111. static void *memsys3MallocUnsafe(int nByte){
  16112. u32 i;
  16113. u32 nBlock;
  16114. u32 toFree;
  16115. assert( sqlite3_mutex_held(mem3.mutex) );
  16116. assert( sizeof(Mem3Block)==8 );
  16117. if( nByte<=12 ){
  16118. nBlock = 2;
  16119. }else{
  16120. nBlock = (nByte + 11)/8;
  16121. }
  16122. assert( nBlock>=2 );
  16123. /* STEP 1:
  16124. ** Look for an entry of the correct size in either the small
  16125. ** chunk table or in the large chunk hash table. This is
  16126. ** successful most of the time (about 9 times out of 10).
  16127. */
  16128. if( nBlock <= MX_SMALL ){
  16129. i = mem3.aiSmall[nBlock-2];
  16130. if( i>0 ){
  16131. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16132. return memsys3Checkout(i, nBlock);
  16133. }
  16134. }else{
  16135. int hash = nBlock % N_HASH;
  16136. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16137. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16138. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16139. return memsys3Checkout(i, nBlock);
  16140. }
  16141. }
  16142. }
  16143. /* STEP 2:
  16144. ** Try to satisfy the allocation by carving a piece off of the end
  16145. ** of the master chunk. This step usually works if step 1 fails.
  16146. */
  16147. if( mem3.szMaster>=nBlock ){
  16148. return memsys3FromMaster(nBlock);
  16149. }
  16150. /* STEP 3:
  16151. ** Loop through the entire memory pool. Coalesce adjacent free
  16152. ** chunks. Recompute the master chunk as the largest free chunk.
  16153. ** Then try again to satisfy the allocation by carving a piece off
  16154. ** of the end of the master chunk. This step happens very
  16155. ** rarely (we hope!)
  16156. */
  16157. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16158. memsys3OutOfMemory(toFree);
  16159. if( mem3.iMaster ){
  16160. memsys3Link(mem3.iMaster);
  16161. mem3.iMaster = 0;
  16162. mem3.szMaster = 0;
  16163. }
  16164. for(i=0; i<N_HASH; i++){
  16165. memsys3Merge(&mem3.aiHash[i]);
  16166. }
  16167. for(i=0; i<MX_SMALL-1; i++){
  16168. memsys3Merge(&mem3.aiSmall[i]);
  16169. }
  16170. if( mem3.szMaster ){
  16171. memsys3Unlink(mem3.iMaster);
  16172. if( mem3.szMaster>=nBlock ){
  16173. return memsys3FromMaster(nBlock);
  16174. }
  16175. }
  16176. }
  16177. /* If none of the above worked, then we fail. */
  16178. return 0;
  16179. }
  16180. /*
  16181. ** Free an outstanding memory allocation.
  16182. **
  16183. ** This function assumes that the necessary mutexes, if any, are
  16184. ** already held by the caller. Hence "Unsafe".
  16185. */
  16186. static void memsys3FreeUnsafe(void *pOld){
  16187. Mem3Block *p = (Mem3Block*)pOld;
  16188. int i;
  16189. u32 size, x;
  16190. assert( sqlite3_mutex_held(mem3.mutex) );
  16191. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16192. i = p - mem3.aPool;
  16193. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16194. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16195. assert( i+size<=mem3.nPool+1 );
  16196. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16197. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16198. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16199. memsys3Link(i);
  16200. /* Try to expand the master using the newly freed chunk */
  16201. if( mem3.iMaster ){
  16202. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16203. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16204. mem3.iMaster -= size;
  16205. mem3.szMaster += size;
  16206. memsys3Unlink(mem3.iMaster);
  16207. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16208. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16209. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16210. }
  16211. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16212. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16213. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16214. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16215. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16216. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16217. }
  16218. }
  16219. }
  16220. /*
  16221. ** Return the size of an outstanding allocation, in bytes. The
  16222. ** size returned omits the 8-byte header overhead. This only
  16223. ** works for chunks that are currently checked out.
  16224. */
  16225. static int memsys3Size(void *p){
  16226. Mem3Block *pBlock;
  16227. if( p==0 ) return 0;
  16228. pBlock = (Mem3Block*)p;
  16229. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16230. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16231. }
  16232. /*
  16233. ** Round up a request size to the next valid allocation size.
  16234. */
  16235. static int memsys3Roundup(int n){
  16236. if( n<=12 ){
  16237. return 12;
  16238. }else{
  16239. return ((n+11)&~7) - 4;
  16240. }
  16241. }
  16242. /*
  16243. ** Allocate nBytes of memory.
  16244. */
  16245. static void *memsys3Malloc(int nBytes){
  16246. sqlite3_int64 *p;
  16247. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16248. memsys3Enter();
  16249. p = memsys3MallocUnsafe(nBytes);
  16250. memsys3Leave();
  16251. return (void*)p;
  16252. }
  16253. /*
  16254. ** Free memory.
  16255. */
  16256. static void memsys3Free(void *pPrior){
  16257. assert( pPrior );
  16258. memsys3Enter();
  16259. memsys3FreeUnsafe(pPrior);
  16260. memsys3Leave();
  16261. }
  16262. /*
  16263. ** Change the size of an existing memory allocation
  16264. */
  16265. static void *memsys3Realloc(void *pPrior, int nBytes){
  16266. int nOld;
  16267. void *p;
  16268. if( pPrior==0 ){
  16269. return sqlite3_malloc(nBytes);
  16270. }
  16271. if( nBytes<=0 ){
  16272. sqlite3_free(pPrior);
  16273. return 0;
  16274. }
  16275. nOld = memsys3Size(pPrior);
  16276. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16277. return pPrior;
  16278. }
  16279. memsys3Enter();
  16280. p = memsys3MallocUnsafe(nBytes);
  16281. if( p ){
  16282. if( nOld<nBytes ){
  16283. memcpy(p, pPrior, nOld);
  16284. }else{
  16285. memcpy(p, pPrior, nBytes);
  16286. }
  16287. memsys3FreeUnsafe(pPrior);
  16288. }
  16289. memsys3Leave();
  16290. return p;
  16291. }
  16292. /*
  16293. ** Initialize this module.
  16294. */
  16295. static int memsys3Init(void *NotUsed){
  16296. UNUSED_PARAMETER(NotUsed);
  16297. if( !sqlite3GlobalConfig.pHeap ){
  16298. return SQLITE_ERROR;
  16299. }
  16300. /* Store a pointer to the memory block in global structure mem3. */
  16301. assert( sizeof(Mem3Block)==8 );
  16302. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16303. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16304. /* Initialize the master block. */
  16305. mem3.szMaster = mem3.nPool;
  16306. mem3.mnMaster = mem3.szMaster;
  16307. mem3.iMaster = 1;
  16308. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16309. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16310. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16311. return SQLITE_OK;
  16312. }
  16313. /*
  16314. ** Deinitialize this module.
  16315. */
  16316. static void memsys3Shutdown(void *NotUsed){
  16317. UNUSED_PARAMETER(NotUsed);
  16318. mem3.mutex = 0;
  16319. return;
  16320. }
  16321. /*
  16322. ** Open the file indicated and write a log of all unfreed memory
  16323. ** allocations into that log.
  16324. */
  16325. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16326. #ifdef SQLITE_DEBUG
  16327. FILE *out;
  16328. u32 i, j;
  16329. u32 size;
  16330. if( zFilename==0 || zFilename[0]==0 ){
  16331. out = stdout;
  16332. }else{
  16333. out = fopen(zFilename, "w");
  16334. if( out==0 ){
  16335. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16336. zFilename);
  16337. return;
  16338. }
  16339. }
  16340. memsys3Enter();
  16341. fprintf(out, "CHUNKS:\n");
  16342. for(i=1; i<=mem3.nPool; i+=size/4){
  16343. size = mem3.aPool[i-1].u.hdr.size4x;
  16344. if( size/4<=1 ){
  16345. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16346. assert( 0 );
  16347. break;
  16348. }
  16349. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16350. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16351. assert( 0 );
  16352. break;
  16353. }
  16354. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16355. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16356. assert( 0 );
  16357. break;
  16358. }
  16359. if( size&1 ){
  16360. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16361. }else{
  16362. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16363. i==mem3.iMaster ? " **master**" : "");
  16364. }
  16365. }
  16366. for(i=0; i<MX_SMALL-1; i++){
  16367. if( mem3.aiSmall[i]==0 ) continue;
  16368. fprintf(out, "small(%2d):", i);
  16369. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16370. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16371. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16372. }
  16373. fprintf(out, "\n");
  16374. }
  16375. for(i=0; i<N_HASH; i++){
  16376. if( mem3.aiHash[i]==0 ) continue;
  16377. fprintf(out, "hash(%2d):", i);
  16378. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16379. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16380. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16381. }
  16382. fprintf(out, "\n");
  16383. }
  16384. fprintf(out, "master=%d\n", mem3.iMaster);
  16385. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16386. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16387. sqlite3_mutex_leave(mem3.mutex);
  16388. if( out==stdout ){
  16389. fflush(stdout);
  16390. }else{
  16391. fclose(out);
  16392. }
  16393. #else
  16394. UNUSED_PARAMETER(zFilename);
  16395. #endif
  16396. }
  16397. /*
  16398. ** This routine is the only routine in this file with external
  16399. ** linkage.
  16400. **
  16401. ** Populate the low-level memory allocation function pointers in
  16402. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16403. ** arguments specify the block of memory to manage.
  16404. **
  16405. ** This routine is only called by sqlite3_config(), and therefore
  16406. ** is not required to be threadsafe (it is not).
  16407. */
  16408. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16409. static const sqlite3_mem_methods mempoolMethods = {
  16410. memsys3Malloc,
  16411. memsys3Free,
  16412. memsys3Realloc,
  16413. memsys3Size,
  16414. memsys3Roundup,
  16415. memsys3Init,
  16416. memsys3Shutdown,
  16417. 0
  16418. };
  16419. return &mempoolMethods;
  16420. }
  16421. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16422. /************** End of mem3.c ************************************************/
  16423. /************** Begin file mem5.c ********************************************/
  16424. /*
  16425. ** 2007 October 14
  16426. **
  16427. ** The author disclaims copyright to this source code. In place of
  16428. ** a legal notice, here is a blessing:
  16429. **
  16430. ** May you do good and not evil.
  16431. ** May you find forgiveness for yourself and forgive others.
  16432. ** May you share freely, never taking more than you give.
  16433. **
  16434. *************************************************************************
  16435. ** This file contains the C functions that implement a memory
  16436. ** allocation subsystem for use by SQLite.
  16437. **
  16438. ** This version of the memory allocation subsystem omits all
  16439. ** use of malloc(). The application gives SQLite a block of memory
  16440. ** before calling sqlite3_initialize() from which allocations
  16441. ** are made and returned by the xMalloc() and xRealloc()
  16442. ** implementations. Once sqlite3_initialize() has been called,
  16443. ** the amount of memory available to SQLite is fixed and cannot
  16444. ** be changed.
  16445. **
  16446. ** This version of the memory allocation subsystem is included
  16447. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16448. **
  16449. ** This memory allocator uses the following algorithm:
  16450. **
  16451. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16452. **
  16453. ** 2. If two adjacent free blocks are the halves of a larger block,
  16454. ** then the two blocks are coalesed into the single larger block.
  16455. **
  16456. ** 3. New memory is allocated from the first available free block.
  16457. **
  16458. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16459. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16460. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16461. **
  16462. ** Let n be the size of the largest allocation divided by the minimum
  16463. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16464. ** be the maximum amount of memory ever outstanding at one time. Let
  16465. ** N be the total amount of memory available for allocation. Robson
  16466. ** proved that this memory allocator will never breakdown due to
  16467. ** fragmentation as long as the following constraint holds:
  16468. **
  16469. ** N >= M*(1 + log2(n)/2) - n + 1
  16470. **
  16471. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16472. ** that an application can, at any time, verify this constraint.
  16473. */
  16474. /*
  16475. ** This version of the memory allocator is used only when
  16476. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16477. */
  16478. #ifdef SQLITE_ENABLE_MEMSYS5
  16479. /*
  16480. ** A minimum allocation is an instance of the following structure.
  16481. ** Larger allocations are an array of these structures where the
  16482. ** size of the array is a power of 2.
  16483. **
  16484. ** The size of this object must be a power of two. That fact is
  16485. ** verified in memsys5Init().
  16486. */
  16487. typedef struct Mem5Link Mem5Link;
  16488. struct Mem5Link {
  16489. int next; /* Index of next free chunk */
  16490. int prev; /* Index of previous free chunk */
  16491. };
  16492. /*
  16493. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16494. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16495. ** it is not actually possible to reach this limit.
  16496. */
  16497. #define LOGMAX 30
  16498. /*
  16499. ** Masks used for mem5.aCtrl[] elements.
  16500. */
  16501. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16502. #define CTRL_FREE 0x20 /* True if not checked out */
  16503. /*
  16504. ** All of the static variables used by this module are collected
  16505. ** into a single structure named "mem5". This is to keep the
  16506. ** static variables organized and to reduce namespace pollution
  16507. ** when this module is combined with other in the amalgamation.
  16508. */
  16509. static SQLITE_WSD struct Mem5Global {
  16510. /*
  16511. ** Memory available for allocation
  16512. */
  16513. int szAtom; /* Smallest possible allocation in bytes */
  16514. int nBlock; /* Number of szAtom sized blocks in zPool */
  16515. u8 *zPool; /* Memory available to be allocated */
  16516. /*
  16517. ** Mutex to control access to the memory allocation subsystem.
  16518. */
  16519. sqlite3_mutex *mutex;
  16520. /*
  16521. ** Performance statistics
  16522. */
  16523. u64 nAlloc; /* Total number of calls to malloc */
  16524. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16525. u64 totalExcess; /* Total internal fragmentation */
  16526. u32 currentOut; /* Current checkout, including internal fragmentation */
  16527. u32 currentCount; /* Current number of distinct checkouts */
  16528. u32 maxOut; /* Maximum instantaneous currentOut */
  16529. u32 maxCount; /* Maximum instantaneous currentCount */
  16530. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16531. /*
  16532. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16533. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16534. ** and so forth.
  16535. */
  16536. int aiFreelist[LOGMAX+1];
  16537. /*
  16538. ** Space for tracking which blocks are checked out and the size
  16539. ** of each block. One byte per block.
  16540. */
  16541. u8 *aCtrl;
  16542. } mem5;
  16543. /*
  16544. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  16545. */
  16546. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16547. /*
  16548. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16549. ** structures, return a pointer to the idx-th such link.
  16550. */
  16551. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16552. /*
  16553. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16554. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16555. */
  16556. static void memsys5Unlink(int i, int iLogsize){
  16557. int next, prev;
  16558. assert( i>=0 && i<mem5.nBlock );
  16559. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16560. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16561. next = MEM5LINK(i)->next;
  16562. prev = MEM5LINK(i)->prev;
  16563. if( prev<0 ){
  16564. mem5.aiFreelist[iLogsize] = next;
  16565. }else{
  16566. MEM5LINK(prev)->next = next;
  16567. }
  16568. if( next>=0 ){
  16569. MEM5LINK(next)->prev = prev;
  16570. }
  16571. }
  16572. /*
  16573. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16574. ** free list.
  16575. */
  16576. static void memsys5Link(int i, int iLogsize){
  16577. int x;
  16578. assert( sqlite3_mutex_held(mem5.mutex) );
  16579. assert( i>=0 && i<mem5.nBlock );
  16580. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16581. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16582. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16583. MEM5LINK(i)->prev = -1;
  16584. if( x>=0 ){
  16585. assert( x<mem5.nBlock );
  16586. MEM5LINK(x)->prev = i;
  16587. }
  16588. mem5.aiFreelist[iLogsize] = i;
  16589. }
  16590. /*
  16591. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16592. ** will already be held (obtained by code in malloc.c) if
  16593. ** sqlite3GlobalConfig.bMemStat is true.
  16594. */
  16595. static void memsys5Enter(void){
  16596. sqlite3_mutex_enter(mem5.mutex);
  16597. }
  16598. static void memsys5Leave(void){
  16599. sqlite3_mutex_leave(mem5.mutex);
  16600. }
  16601. /*
  16602. ** Return the size of an outstanding allocation, in bytes. The
  16603. ** size returned omits the 8-byte header overhead. This only
  16604. ** works for chunks that are currently checked out.
  16605. */
  16606. static int memsys5Size(void *p){
  16607. int iSize = 0;
  16608. if( p ){
  16609. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16610. assert( i>=0 && i<mem5.nBlock );
  16611. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16612. }
  16613. return iSize;
  16614. }
  16615. /*
  16616. ** Find the first entry on the freelist iLogsize. Unlink that
  16617. ** entry and return its index.
  16618. */
  16619. static int memsys5UnlinkFirst(int iLogsize){
  16620. int i;
  16621. int iFirst;
  16622. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16623. i = iFirst = mem5.aiFreelist[iLogsize];
  16624. assert( iFirst>=0 );
  16625. while( i>0 ){
  16626. if( i<iFirst ) iFirst = i;
  16627. i = MEM5LINK(i)->next;
  16628. }
  16629. memsys5Unlink(iFirst, iLogsize);
  16630. return iFirst;
  16631. }
  16632. /*
  16633. ** Return a block of memory of at least nBytes in size.
  16634. ** Return NULL if unable. Return NULL if nBytes==0.
  16635. **
  16636. ** The caller guarantees that nByte is positive.
  16637. **
  16638. ** The caller has obtained a mutex prior to invoking this
  16639. ** routine so there is never any chance that two or more
  16640. ** threads can be in this routine at the same time.
  16641. */
  16642. static void *memsys5MallocUnsafe(int nByte){
  16643. int i; /* Index of a mem5.aPool[] slot */
  16644. int iBin; /* Index into mem5.aiFreelist[] */
  16645. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16646. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16647. /* nByte must be a positive */
  16648. assert( nByte>0 );
  16649. /* Keep track of the maximum allocation request. Even unfulfilled
  16650. ** requests are counted */
  16651. if( (u32)nByte>mem5.maxRequest ){
  16652. mem5.maxRequest = nByte;
  16653. }
  16654. /* Abort if the requested allocation size is larger than the largest
  16655. ** power of two that we can represent using 32-bit signed integers.
  16656. */
  16657. if( nByte > 0x40000000 ){
  16658. return 0;
  16659. }
  16660. /* Round nByte up to the next valid power of two */
  16661. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16662. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16663. ** block. If not, then split a block of the next larger power of
  16664. ** two in order to create a new free block of size iLogsize.
  16665. */
  16666. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16667. if( iBin>LOGMAX ){
  16668. testcase( sqlite3GlobalConfig.xLog!=0 );
  16669. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16670. return 0;
  16671. }
  16672. i = memsys5UnlinkFirst(iBin);
  16673. while( iBin>iLogsize ){
  16674. int newSize;
  16675. iBin--;
  16676. newSize = 1 << iBin;
  16677. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16678. memsys5Link(i+newSize, iBin);
  16679. }
  16680. mem5.aCtrl[i] = iLogsize;
  16681. /* Update allocator performance statistics. */
  16682. mem5.nAlloc++;
  16683. mem5.totalAlloc += iFullSz;
  16684. mem5.totalExcess += iFullSz - nByte;
  16685. mem5.currentCount++;
  16686. mem5.currentOut += iFullSz;
  16687. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16688. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16689. /* Return a pointer to the allocated memory. */
  16690. return (void*)&mem5.zPool[i*mem5.szAtom];
  16691. }
  16692. /*
  16693. ** Free an outstanding memory allocation.
  16694. */
  16695. static void memsys5FreeUnsafe(void *pOld){
  16696. u32 size, iLogsize;
  16697. int iBlock;
  16698. /* Set iBlock to the index of the block pointed to by pOld in
  16699. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16700. */
  16701. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16702. /* Check that the pointer pOld points to a valid, non-free block. */
  16703. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16704. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16705. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16706. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16707. size = 1<<iLogsize;
  16708. assert( iBlock+size-1<(u32)mem5.nBlock );
  16709. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16710. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16711. assert( mem5.currentCount>0 );
  16712. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16713. mem5.currentCount--;
  16714. mem5.currentOut -= size*mem5.szAtom;
  16715. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16716. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16717. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16718. while( ALWAYS(iLogsize<LOGMAX) ){
  16719. int iBuddy;
  16720. if( (iBlock>>iLogsize) & 1 ){
  16721. iBuddy = iBlock - size;
  16722. }else{
  16723. iBuddy = iBlock + size;
  16724. }
  16725. assert( iBuddy>=0 );
  16726. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16727. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16728. memsys5Unlink(iBuddy, iLogsize);
  16729. iLogsize++;
  16730. if( iBuddy<iBlock ){
  16731. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16732. mem5.aCtrl[iBlock] = 0;
  16733. iBlock = iBuddy;
  16734. }else{
  16735. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16736. mem5.aCtrl[iBuddy] = 0;
  16737. }
  16738. size *= 2;
  16739. }
  16740. memsys5Link(iBlock, iLogsize);
  16741. }
  16742. /*
  16743. ** Allocate nBytes of memory.
  16744. */
  16745. static void *memsys5Malloc(int nBytes){
  16746. sqlite3_int64 *p = 0;
  16747. if( nBytes>0 ){
  16748. memsys5Enter();
  16749. p = memsys5MallocUnsafe(nBytes);
  16750. memsys5Leave();
  16751. }
  16752. return (void*)p;
  16753. }
  16754. /*
  16755. ** Free memory.
  16756. **
  16757. ** The outer layer memory allocator prevents this routine from
  16758. ** being called with pPrior==0.
  16759. */
  16760. static void memsys5Free(void *pPrior){
  16761. assert( pPrior!=0 );
  16762. memsys5Enter();
  16763. memsys5FreeUnsafe(pPrior);
  16764. memsys5Leave();
  16765. }
  16766. /*
  16767. ** Change the size of an existing memory allocation.
  16768. **
  16769. ** The outer layer memory allocator prevents this routine from
  16770. ** being called with pPrior==0.
  16771. **
  16772. ** nBytes is always a value obtained from a prior call to
  16773. ** memsys5Round(). Hence nBytes is always a non-negative power
  16774. ** of two. If nBytes==0 that means that an oversize allocation
  16775. ** (an allocation larger than 0x40000000) was requested and this
  16776. ** routine should return 0 without freeing pPrior.
  16777. */
  16778. static void *memsys5Realloc(void *pPrior, int nBytes){
  16779. int nOld;
  16780. void *p;
  16781. assert( pPrior!=0 );
  16782. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16783. assert( nBytes>=0 );
  16784. if( nBytes==0 ){
  16785. return 0;
  16786. }
  16787. nOld = memsys5Size(pPrior);
  16788. if( nBytes<=nOld ){
  16789. return pPrior;
  16790. }
  16791. memsys5Enter();
  16792. p = memsys5MallocUnsafe(nBytes);
  16793. if( p ){
  16794. memcpy(p, pPrior, nOld);
  16795. memsys5FreeUnsafe(pPrior);
  16796. }
  16797. memsys5Leave();
  16798. return p;
  16799. }
  16800. /*
  16801. ** Round up a request size to the next valid allocation size. If
  16802. ** the allocation is too large to be handled by this allocation system,
  16803. ** return 0.
  16804. **
  16805. ** All allocations must be a power of two and must be expressed by a
  16806. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16807. ** or 1073741824 bytes.
  16808. */
  16809. static int memsys5Roundup(int n){
  16810. int iFullSz;
  16811. if( n > 0x40000000 ) return 0;
  16812. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16813. return iFullSz;
  16814. }
  16815. /*
  16816. ** Return the ceiling of the logarithm base 2 of iValue.
  16817. **
  16818. ** Examples: memsys5Log(1) -> 0
  16819. ** memsys5Log(2) -> 1
  16820. ** memsys5Log(4) -> 2
  16821. ** memsys5Log(5) -> 3
  16822. ** memsys5Log(8) -> 3
  16823. ** memsys5Log(9) -> 4
  16824. */
  16825. static int memsys5Log(int iValue){
  16826. int iLog;
  16827. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16828. return iLog;
  16829. }
  16830. /*
  16831. ** Initialize the memory allocator.
  16832. **
  16833. ** This routine is not threadsafe. The caller must be holding a mutex
  16834. ** to prevent multiple threads from entering at the same time.
  16835. */
  16836. static int memsys5Init(void *NotUsed){
  16837. int ii; /* Loop counter */
  16838. int nByte; /* Number of bytes of memory available to this allocator */
  16839. u8 *zByte; /* Memory usable by this allocator */
  16840. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16841. int iOffset; /* An offset into mem5.aCtrl[] */
  16842. UNUSED_PARAMETER(NotUsed);
  16843. /* For the purposes of this routine, disable the mutex */
  16844. mem5.mutex = 0;
  16845. /* The size of a Mem5Link object must be a power of two. Verify that
  16846. ** this is case.
  16847. */
  16848. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16849. nByte = sqlite3GlobalConfig.nHeap;
  16850. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16851. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16852. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16853. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16854. mem5.szAtom = (1<<nMinLog);
  16855. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16856. mem5.szAtom = mem5.szAtom << 1;
  16857. }
  16858. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16859. mem5.zPool = zByte;
  16860. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16861. for(ii=0; ii<=LOGMAX; ii++){
  16862. mem5.aiFreelist[ii] = -1;
  16863. }
  16864. iOffset = 0;
  16865. for(ii=LOGMAX; ii>=0; ii--){
  16866. int nAlloc = (1<<ii);
  16867. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16868. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16869. memsys5Link(iOffset, ii);
  16870. iOffset += nAlloc;
  16871. }
  16872. assert((iOffset+nAlloc)>mem5.nBlock);
  16873. }
  16874. /* If a mutex is required for normal operation, allocate one */
  16875. if( sqlite3GlobalConfig.bMemstat==0 ){
  16876. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16877. }
  16878. return SQLITE_OK;
  16879. }
  16880. /*
  16881. ** Deinitialize this module.
  16882. */
  16883. static void memsys5Shutdown(void *NotUsed){
  16884. UNUSED_PARAMETER(NotUsed);
  16885. mem5.mutex = 0;
  16886. return;
  16887. }
  16888. #ifdef SQLITE_TEST
  16889. /*
  16890. ** Open the file indicated and write a log of all unfreed memory
  16891. ** allocations into that log.
  16892. */
  16893. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16894. FILE *out;
  16895. int i, j, n;
  16896. int nMinLog;
  16897. if( zFilename==0 || zFilename[0]==0 ){
  16898. out = stdout;
  16899. }else{
  16900. out = fopen(zFilename, "w");
  16901. if( out==0 ){
  16902. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16903. zFilename);
  16904. return;
  16905. }
  16906. }
  16907. memsys5Enter();
  16908. nMinLog = memsys5Log(mem5.szAtom);
  16909. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16910. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16911. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16912. }
  16913. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16914. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16915. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16916. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16917. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16918. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16919. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16920. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16921. memsys5Leave();
  16922. if( out==stdout ){
  16923. fflush(stdout);
  16924. }else{
  16925. fclose(out);
  16926. }
  16927. }
  16928. #endif
  16929. /*
  16930. ** This routine is the only routine in this file with external
  16931. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16932. ** struct populated with the memsys5 methods.
  16933. */
  16934. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16935. static const sqlite3_mem_methods memsys5Methods = {
  16936. memsys5Malloc,
  16937. memsys5Free,
  16938. memsys5Realloc,
  16939. memsys5Size,
  16940. memsys5Roundup,
  16941. memsys5Init,
  16942. memsys5Shutdown,
  16943. 0
  16944. };
  16945. return &memsys5Methods;
  16946. }
  16947. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16948. /************** End of mem5.c ************************************************/
  16949. /************** Begin file mutex.c *******************************************/
  16950. /*
  16951. ** 2007 August 14
  16952. **
  16953. ** The author disclaims copyright to this source code. In place of
  16954. ** a legal notice, here is a blessing:
  16955. **
  16956. ** May you do good and not evil.
  16957. ** May you find forgiveness for yourself and forgive others.
  16958. ** May you share freely, never taking more than you give.
  16959. **
  16960. *************************************************************************
  16961. ** This file contains the C functions that implement mutexes.
  16962. **
  16963. ** This file contains code that is common across all mutex implementations.
  16964. */
  16965. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16966. /*
  16967. ** For debugging purposes, record when the mutex subsystem is initialized
  16968. ** and uninitialized so that we can assert() if there is an attempt to
  16969. ** allocate a mutex while the system is uninitialized.
  16970. */
  16971. static SQLITE_WSD int mutexIsInit = 0;
  16972. #endif /* SQLITE_DEBUG */
  16973. #ifndef SQLITE_MUTEX_OMIT
  16974. /*
  16975. ** Initialize the mutex system.
  16976. */
  16977. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16978. int rc = SQLITE_OK;
  16979. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16980. /* If the xMutexAlloc method has not been set, then the user did not
  16981. ** install a mutex implementation via sqlite3_config() prior to
  16982. ** sqlite3_initialize() being called. This block copies pointers to
  16983. ** the default implementation into the sqlite3GlobalConfig structure.
  16984. */
  16985. sqlite3_mutex_methods const *pFrom;
  16986. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16987. if( sqlite3GlobalConfig.bCoreMutex ){
  16988. pFrom = sqlite3DefaultMutex();
  16989. }else{
  16990. pFrom = sqlite3NoopMutex();
  16991. }
  16992. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16993. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16994. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16995. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16996. }
  16997. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16998. #ifdef SQLITE_DEBUG
  16999. GLOBAL(int, mutexIsInit) = 1;
  17000. #endif
  17001. return rc;
  17002. }
  17003. /*
  17004. ** Shutdown the mutex system. This call frees resources allocated by
  17005. ** sqlite3MutexInit().
  17006. */
  17007. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  17008. int rc = SQLITE_OK;
  17009. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  17010. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  17011. }
  17012. #ifdef SQLITE_DEBUG
  17013. GLOBAL(int, mutexIsInit) = 0;
  17014. #endif
  17015. return rc;
  17016. }
  17017. /*
  17018. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  17019. */
  17020. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  17021. #ifndef SQLITE_OMIT_AUTOINIT
  17022. if( sqlite3_initialize() ) return 0;
  17023. #endif
  17024. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17025. }
  17026. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  17027. if( !sqlite3GlobalConfig.bCoreMutex ){
  17028. return 0;
  17029. }
  17030. assert( GLOBAL(int, mutexIsInit) );
  17031. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17032. }
  17033. /*
  17034. ** Free a dynamic mutex.
  17035. */
  17036. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  17037. if( p ){
  17038. sqlite3GlobalConfig.mutex.xMutexFree(p);
  17039. }
  17040. }
  17041. /*
  17042. ** Obtain the mutex p. If some other thread already has the mutex, block
  17043. ** until it can be obtained.
  17044. */
  17045. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  17046. if( p ){
  17047. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  17048. }
  17049. }
  17050. /*
  17051. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  17052. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  17053. */
  17054. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  17055. int rc = SQLITE_OK;
  17056. if( p ){
  17057. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  17058. }
  17059. return rc;
  17060. }
  17061. /*
  17062. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  17063. ** entered by the same thread. The behavior is undefined if the mutex
  17064. ** is not currently entered. If a NULL pointer is passed as an argument
  17065. ** this function is a no-op.
  17066. */
  17067. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  17068. if( p ){
  17069. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  17070. }
  17071. }
  17072. #ifndef NDEBUG
  17073. /*
  17074. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17075. ** intended for use inside assert() statements.
  17076. */
  17077. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17078. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17079. }
  17080. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17081. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17082. }
  17083. #endif
  17084. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17085. /************** End of mutex.c ***********************************************/
  17086. /************** Begin file mutex_noop.c **************************************/
  17087. /*
  17088. ** 2008 October 07
  17089. **
  17090. ** The author disclaims copyright to this source code. In place of
  17091. ** a legal notice, here is a blessing:
  17092. **
  17093. ** May you do good and not evil.
  17094. ** May you find forgiveness for yourself and forgive others.
  17095. ** May you share freely, never taking more than you give.
  17096. **
  17097. *************************************************************************
  17098. ** This file contains the C functions that implement mutexes.
  17099. **
  17100. ** This implementation in this file does not provide any mutual
  17101. ** exclusion and is thus suitable for use only in applications
  17102. ** that use SQLite in a single thread. The routines defined
  17103. ** here are place-holders. Applications can substitute working
  17104. ** mutex routines at start-time using the
  17105. **
  17106. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17107. **
  17108. ** interface.
  17109. **
  17110. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17111. ** that does error checking on mutexes to make sure they are being
  17112. ** called correctly.
  17113. */
  17114. #ifndef SQLITE_MUTEX_OMIT
  17115. #ifndef SQLITE_DEBUG
  17116. /*
  17117. ** Stub routines for all mutex methods.
  17118. **
  17119. ** This routines provide no mutual exclusion or error checking.
  17120. */
  17121. static int noopMutexInit(void){ return SQLITE_OK; }
  17122. static int noopMutexEnd(void){ return SQLITE_OK; }
  17123. static sqlite3_mutex *noopMutexAlloc(int id){
  17124. UNUSED_PARAMETER(id);
  17125. return (sqlite3_mutex*)8;
  17126. }
  17127. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17128. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17129. static int noopMutexTry(sqlite3_mutex *p){
  17130. UNUSED_PARAMETER(p);
  17131. return SQLITE_OK;
  17132. }
  17133. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17134. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17135. static const sqlite3_mutex_methods sMutex = {
  17136. noopMutexInit,
  17137. noopMutexEnd,
  17138. noopMutexAlloc,
  17139. noopMutexFree,
  17140. noopMutexEnter,
  17141. noopMutexTry,
  17142. noopMutexLeave,
  17143. 0,
  17144. 0,
  17145. };
  17146. return &sMutex;
  17147. }
  17148. #endif /* !SQLITE_DEBUG */
  17149. #ifdef SQLITE_DEBUG
  17150. /*
  17151. ** In this implementation, error checking is provided for testing
  17152. ** and debugging purposes. The mutexes still do not provide any
  17153. ** mutual exclusion.
  17154. */
  17155. /*
  17156. ** The mutex object
  17157. */
  17158. typedef struct sqlite3_debug_mutex {
  17159. int id; /* The mutex type */
  17160. int cnt; /* Number of entries without a matching leave */
  17161. } sqlite3_debug_mutex;
  17162. /*
  17163. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17164. ** intended for use inside assert() statements.
  17165. */
  17166. static int debugMutexHeld(sqlite3_mutex *pX){
  17167. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17168. return p==0 || p->cnt>0;
  17169. }
  17170. static int debugMutexNotheld(sqlite3_mutex *pX){
  17171. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17172. return p==0 || p->cnt==0;
  17173. }
  17174. /*
  17175. ** Initialize and deinitialize the mutex subsystem.
  17176. */
  17177. static int debugMutexInit(void){ return SQLITE_OK; }
  17178. static int debugMutexEnd(void){ return SQLITE_OK; }
  17179. /*
  17180. ** The sqlite3_mutex_alloc() routine allocates a new
  17181. ** mutex and returns a pointer to it. If it returns NULL
  17182. ** that means that a mutex could not be allocated.
  17183. */
  17184. static sqlite3_mutex *debugMutexAlloc(int id){
  17185. static sqlite3_debug_mutex aStatic[6];
  17186. sqlite3_debug_mutex *pNew = 0;
  17187. switch( id ){
  17188. case SQLITE_MUTEX_FAST:
  17189. case SQLITE_MUTEX_RECURSIVE: {
  17190. pNew = sqlite3Malloc(sizeof(*pNew));
  17191. if( pNew ){
  17192. pNew->id = id;
  17193. pNew->cnt = 0;
  17194. }
  17195. break;
  17196. }
  17197. default: {
  17198. assert( id-2 >= 0 );
  17199. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17200. pNew = &aStatic[id-2];
  17201. pNew->id = id;
  17202. break;
  17203. }
  17204. }
  17205. return (sqlite3_mutex*)pNew;
  17206. }
  17207. /*
  17208. ** This routine deallocates a previously allocated mutex.
  17209. */
  17210. static void debugMutexFree(sqlite3_mutex *pX){
  17211. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17212. assert( p->cnt==0 );
  17213. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17214. sqlite3_free(p);
  17215. }
  17216. /*
  17217. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17218. ** to enter a mutex. If another thread is already within the mutex,
  17219. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17220. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17221. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17222. ** be entered multiple times by the same thread. In such cases the,
  17223. ** mutex must be exited an equal number of times before another thread
  17224. ** can enter. If the same thread tries to enter any other kind of mutex
  17225. ** more than once, the behavior is undefined.
  17226. */
  17227. static void debugMutexEnter(sqlite3_mutex *pX){
  17228. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17229. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17230. p->cnt++;
  17231. }
  17232. static int debugMutexTry(sqlite3_mutex *pX){
  17233. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17234. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17235. p->cnt++;
  17236. return SQLITE_OK;
  17237. }
  17238. /*
  17239. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17240. ** previously entered by the same thread. The behavior
  17241. ** is undefined if the mutex is not currently entered or
  17242. ** is not currently allocated. SQLite will never do either.
  17243. */
  17244. static void debugMutexLeave(sqlite3_mutex *pX){
  17245. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17246. assert( debugMutexHeld(pX) );
  17247. p->cnt--;
  17248. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17249. }
  17250. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17251. static const sqlite3_mutex_methods sMutex = {
  17252. debugMutexInit,
  17253. debugMutexEnd,
  17254. debugMutexAlloc,
  17255. debugMutexFree,
  17256. debugMutexEnter,
  17257. debugMutexTry,
  17258. debugMutexLeave,
  17259. debugMutexHeld,
  17260. debugMutexNotheld
  17261. };
  17262. return &sMutex;
  17263. }
  17264. #endif /* SQLITE_DEBUG */
  17265. /*
  17266. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17267. ** is used regardless of the run-time threadsafety setting.
  17268. */
  17269. #ifdef SQLITE_MUTEX_NOOP
  17270. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17271. return sqlite3NoopMutex();
  17272. }
  17273. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17274. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17275. /************** End of mutex_noop.c ******************************************/
  17276. /************** Begin file mutex_rtthread.c **********************************/
  17277. /*
  17278. ** 2007 August 28
  17279. **
  17280. ** The author disclaims copyright to this source code. In place of
  17281. ** a legal notice, here is a blessing:
  17282. **
  17283. ** May you do good and not evil.
  17284. ** May you find forgiveness for yourself and forgive others.
  17285. ** May you share freely, never taking more than you give.
  17286. **
  17287. *************************************************************************
  17288. ** This file contains the C functions that implement mutexes for rtthread
  17289. */
  17290. /*
  17291. ** The code in this file is only used if we are compiling threadsafe
  17292. ** under rt-thread with rt_mutex.
  17293. **
  17294. ** Note that this implementation requires a version of rt-thread that
  17295. ** supports recursive mutexes.
  17296. */
  17297. #ifdef SQLITE_MUTEX_RTTHREAD
  17298. /* #include <rtthread.h> */
  17299. /*
  17300. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17301. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17302. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17303. */
  17304. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17305. # define SQLITE_MUTEX_NREF 1
  17306. #else
  17307. # define SQLITE_MUTEX_NREF 0
  17308. #endif
  17309. /*
  17310. ** Each recursive mutex is an instance of the following structure.
  17311. */
  17312. struct sqlite3_mutex {
  17313. struct rt_mutex mutex; /* Mutex controlling the lock */
  17314. #if SQLITE_MUTEX_NREF
  17315. int id; /* Mutex type */
  17316. volatile int nRef; /* Number of entrances */
  17317. volatile rt_thread_t owner; /* Thread that is within this mutex */
  17318. int trace; /* True to trace changes */
  17319. #endif
  17320. };
  17321. #define RTT_MUTEX_INITIALIZER { 0 }
  17322. #if SQLITE_MUTEX_NREF
  17323. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER, 0, 0, (rt_thread_t)0, 0 }
  17324. #else
  17325. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER }
  17326. #endif
  17327. /*
  17328. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17329. ** intended for use only inside assert() statements. On some platforms,
  17330. ** there might be race conditions that can cause these routines to
  17331. ** deliver incorrect results. In particular, if rtthread_equal() is
  17332. ** not an atomic operation, then these routines might delivery
  17333. ** incorrect results. On most platforms, rtthread_equal() is a
  17334. ** comparison of two integers and is therefore atomic. But we are
  17335. ** told that HPUX is not such a platform. If so, then these routines
  17336. ** will not always work correctly on HPUX.
  17337. **
  17338. ** On those platforms where rtthread_equal() is not atomic, SQLite
  17339. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17340. ** make sure no assert() statements are evaluated and hence these
  17341. ** routines are never called.
  17342. */
  17343. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17344. static int rtthreadMutexHeld(sqlite3_mutex *p){
  17345. return (p->nRef != 0 && p->owner == rt_thread_self());
  17346. }
  17347. static int rtthreadMutexNotheld(sqlite3_mutex *p){
  17348. return (p->nRef == 0 || p->owner != rt_thread_self());
  17349. }
  17350. #endif
  17351. /*
  17352. ** Initialize and deinitialize the mutex subsystem.
  17353. */
  17354. static int rtthreadMutexInit(void){ return SQLITE_OK; }
  17355. static int rtthreadMutexEnd(void){ return SQLITE_OK; }
  17356. /*
  17357. ** The sqlite3_mutex_alloc() routine allocates a new
  17358. ** mutex and returns a pointer to it. If it returns NULL
  17359. ** that means that a mutex could not be allocated. SQLite
  17360. ** will unwind its stack and return an error. The argument
  17361. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17362. **
  17363. ** <ul>
  17364. ** <li> SQLITE_MUTEX_FAST
  17365. ** <li> SQLITE_MUTEX_RECURSIVE
  17366. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17367. ** <li> SQLITE_MUTEX_STATIC_MEM
  17368. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17369. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17370. ** <li> SQLITE_MUTEX_STATIC_LRU
  17371. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17372. ** </ul>
  17373. **
  17374. ** The first two constants cause sqlite3_mutex_alloc() to create
  17375. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17376. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17377. ** The mutex implementation does not need to make a distinction
  17378. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17379. ** not want to. But SQLite will only request a recursive mutex in
  17380. ** cases where it really needs one. If a faster non-recursive mutex
  17381. ** implementation is available on the host platform, the mutex subsystem
  17382. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17383. **
  17384. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17385. ** a pointer to a static preexisting mutex. Six static mutexes are
  17386. ** used by the current version of SQLite. Future versions of SQLite
  17387. ** may add additional static mutexes. Static mutexes are for internal
  17388. ** use by SQLite only. Applications that use SQLite mutexes should
  17389. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17390. ** SQLITE_MUTEX_RECURSIVE.
  17391. **
  17392. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17393. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17394. ** returns a different mutex on every call. But for the static
  17395. ** mutex types, the same mutex is returned on every call that has
  17396. ** the same type number.
  17397. */
  17398. static sqlite3_mutex* rtthreadMutexAlloc(int iType){
  17399. static sqlite3_mutex staticMutexes[] = {
  17400. SQLITE3_MUTEX_INITIALIZER,
  17401. SQLITE3_MUTEX_INITIALIZER,
  17402. SQLITE3_MUTEX_INITIALIZER,
  17403. SQLITE3_MUTEX_INITIALIZER,
  17404. SQLITE3_MUTEX_INITIALIZER,
  17405. SQLITE3_MUTEX_INITIALIZER
  17406. };
  17407. sqlite3_mutex *p;
  17408. switch( iType ){
  17409. case SQLITE_MUTEX_RECURSIVE: {
  17410. p = sqlite3MallocZero( sizeof(*p) );
  17411. if( p ){
  17412. /* Use a recursive mutex if it is available */
  17413. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  17414. #if SQLITE_MUTEX_NREF
  17415. p->id = iType;
  17416. #endif
  17417. }
  17418. break;
  17419. }
  17420. case SQLITE_MUTEX_FAST: {
  17421. p = sqlite3MallocZero( sizeof(*p) );
  17422. if( p ){
  17423. #if SQLITE_MUTEX_NREF
  17424. p->id = iType;
  17425. #endif
  17426. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  17427. }
  17428. break;
  17429. }
  17430. default: {
  17431. assert( iType-2 >= 0 );
  17432. assert( iType-2 < ArraySize(staticMutexes) );
  17433. p = &staticMutexes[iType-2];
  17434. #if SQLITE_MUTEX_NREF
  17435. p->id = iType;
  17436. #endif
  17437. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  17438. break;
  17439. }
  17440. }
  17441. return p;
  17442. }
  17443. /*
  17444. ** This routine deallocates a previously
  17445. ** allocated mutex. SQLite is careful to deallocate every
  17446. ** mutex that it allocates.
  17447. */
  17448. static void rtthreadMutexFree(sqlite3_mutex *p){
  17449. assert( p->nRef==0 );
  17450. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17451. rt_mutex_detach(&p->mutex);
  17452. sqlite3_free(p);
  17453. }
  17454. /*
  17455. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17456. ** to enter a mutex. If another thread is already within the mutex,
  17457. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17458. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17459. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17460. ** be entered multiple times by the same thread. In such cases the,
  17461. ** mutex must be exited an equal number of times before another thread
  17462. ** can enter. If the same thread tries to enter any other kind of mutex
  17463. ** more than once, the behavior is undefined.
  17464. */
  17465. static void rtthreadMutexEnter(sqlite3_mutex *p){
  17466. assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) );
  17467. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17468. /* If recursive mutexes are not available, then we have to grow
  17469. ** our own. This implementation assumes that rtthread_equal()
  17470. ** is atomic - that it cannot be deceived into thinking self
  17471. ** and p->owner are equal if p->owner changes between two values
  17472. ** that are not equal to self while the comparison is taking place.
  17473. ** This implementation also assumes a coherent cache - that
  17474. ** separate processes cannot read different values from the same
  17475. ** address at the same time. If either of these two conditions
  17476. ** are not met, then the mutexes will fail and problems will result.
  17477. */
  17478. {
  17479. rt_thread_t self = rt_thread_self();
  17480. if( p->nRef>0 && (p->owner == self) ){
  17481. p->nRef++;
  17482. }else{
  17483. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  17484. assert( p->nRef==0 );
  17485. p->owner = self;
  17486. p->nRef = 1;
  17487. }
  17488. }
  17489. #else
  17490. /* Use the built-in recursive mutexes if they are available.
  17491. */
  17492. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  17493. #if SQLITE_MUTEX_NREF
  17494. assert( p->nRef>0 || p->owner==0 );
  17495. p->owner = rt_thread_self();
  17496. p->nRef++;
  17497. #endif
  17498. #endif
  17499. #ifdef SQLITE_DEBUG
  17500. if( p->trace ){
  17501. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17502. }
  17503. #endif
  17504. }
  17505. static int rtthreadMutexTry(sqlite3_mutex *p){
  17506. int rc;
  17507. assert( p->id==SQLITE_MUTEX_RECURSIVE || rtthreadMutexNotheld(p) );
  17508. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17509. /* If recursive mutexes are not available, then we have to grow
  17510. ** our own. This implementation assumes that rtthread_equal()
  17511. ** is atomic - that it cannot be deceived into thinking self
  17512. ** and p->owner are equal if p->owner changes between two values
  17513. ** that are not equal to self while the comparison is taking place.
  17514. ** This implementation also assumes a coherent cache - that
  17515. ** separate processes cannot read different values from the same
  17516. ** address at the same time. If either of these two conditions
  17517. ** are not met, then the mutexes will fail and problems will result.
  17518. */
  17519. {
  17520. rt_thread_t self = rt_thread_self();
  17521. if( p->nRef>0 && (p->owner == self) ){
  17522. p->nRef++;
  17523. rc = SQLITE_OK;
  17524. }else if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  17525. assert( p->nRef==0 );
  17526. p->owner = self;
  17527. p->nRef = 1;
  17528. rc = SQLITE_OK;
  17529. }else{
  17530. rc = SQLITE_BUSY;
  17531. }
  17532. }
  17533. #else
  17534. /* Use the built-in recursive mutexes if they are available.
  17535. */
  17536. if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  17537. #if SQLITE_MUTEX_NREF
  17538. p->owner = rt_thread_self();
  17539. p->nRef++;
  17540. #endif
  17541. rc = SQLITE_OK;
  17542. }else{
  17543. rc = SQLITE_BUSY;
  17544. }
  17545. #endif
  17546. #ifdef SQLITE_DEBUG
  17547. if( rc==SQLITE_OK && p->trace ){
  17548. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17549. }
  17550. #endif
  17551. return rc;
  17552. }
  17553. /*
  17554. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17555. ** previously entered by the same thread. The behavior
  17556. ** is undefined if the mutex is not currently entered or
  17557. ** is not currently allocated. SQLite will never do either.
  17558. */
  17559. static void rtthreadMutexLeave(sqlite3_mutex *p){
  17560. assert( rtthreadMutexHeld(p) );
  17561. #if SQLITE_MUTEX_NREF
  17562. p->nRef--;
  17563. if( p->nRef==0 ) p->owner = 0;
  17564. #endif
  17565. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17566. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17567. if( p->nRef==0 ){
  17568. rt_mutex_release(&p->mutex);
  17569. }
  17570. #else
  17571. rt_mutex_release(&p->mutex);
  17572. #endif
  17573. #ifdef SQLITE_DEBUG
  17574. if( p->trace ){
  17575. rt_kprintf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17576. }
  17577. #endif
  17578. }
  17579. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17580. static const sqlite3_mutex_methods sMutex = {
  17581. rtthreadMutexInit,
  17582. rtthreadMutexEnd,
  17583. rtthreadMutexAlloc,
  17584. rtthreadMutexFree,
  17585. rtthreadMutexEnter,
  17586. rtthreadMutexTry,
  17587. rtthreadMutexLeave,
  17588. #ifdef SQLITE_DEBUG
  17589. rtthreadMutexHeld,
  17590. rtthreadMutexNotheld
  17591. #else
  17592. 0,
  17593. 0
  17594. #endif
  17595. };
  17596. return &sMutex;
  17597. }
  17598. #endif /* SQLITE_MUTEX_RTTHREAD */
  17599. /************** End of mutex_rtthread.c **************************************/
  17600. /************** Begin file malloc.c ******************************************/
  17601. /*
  17602. ** 2001 September 15
  17603. **
  17604. ** The author disclaims copyright to this source code. In place of
  17605. ** a legal notice, here is a blessing:
  17606. **
  17607. ** May you do good and not evil.
  17608. ** May you find forgiveness for yourself and forgive others.
  17609. ** May you share freely, never taking more than you give.
  17610. **
  17611. *************************************************************************
  17612. **
  17613. ** Memory allocation functions used throughout sqlite.
  17614. */
  17615. /* #include <stdarg.h> */
  17616. /*
  17617. ** Attempt to release up to n bytes of non-essential memory currently
  17618. ** held by SQLite. An example of non-essential memory is memory used to
  17619. ** cache database pages that are not currently in use.
  17620. */
  17621. SQLITE_API int sqlite3_release_memory(int n){
  17622. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17623. return sqlite3PcacheReleaseMemory(n);
  17624. #else
  17625. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  17626. ** is a no-op returning zero if SQLite is not compiled with
  17627. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  17628. UNUSED_PARAMETER(n);
  17629. return 0;
  17630. #endif
  17631. }
  17632. /*
  17633. ** An instance of the following object records the location of
  17634. ** each unused scratch buffer.
  17635. */
  17636. typedef struct ScratchFreeslot {
  17637. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  17638. } ScratchFreeslot;
  17639. /*
  17640. ** State information local to the memory allocation subsystem.
  17641. */
  17642. static SQLITE_WSD struct Mem0Global {
  17643. sqlite3_mutex *mutex; /* Mutex to serialize access */
  17644. /*
  17645. ** The alarm callback and its arguments. The mem0.mutex lock will
  17646. ** be held while the callback is running. Recursive calls into
  17647. ** the memory subsystem are allowed, but no new callbacks will be
  17648. ** issued.
  17649. */
  17650. sqlite3_int64 alarmThreshold;
  17651. void (*alarmCallback)(void*, sqlite3_int64,int);
  17652. void *alarmArg;
  17653. /*
  17654. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  17655. ** (so that a range test can be used to determine if an allocation
  17656. ** being freed came from pScratch) and a pointer to the list of
  17657. ** unused scratch allocations.
  17658. */
  17659. void *pScratchEnd;
  17660. ScratchFreeslot *pScratchFree;
  17661. u32 nScratchFree;
  17662. /*
  17663. ** True if heap is nearly "full" where "full" is defined by the
  17664. ** sqlite3_soft_heap_limit() setting.
  17665. */
  17666. int nearlyFull;
  17667. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  17668. #define mem0 GLOBAL(struct Mem0Global, mem0)
  17669. /*
  17670. ** This routine runs when the memory allocator sees that the
  17671. ** total memory allocation is about to exceed the soft heap
  17672. ** limit.
  17673. */
  17674. static void softHeapLimitEnforcer(
  17675. void *NotUsed,
  17676. sqlite3_int64 NotUsed2,
  17677. int allocSize
  17678. ){
  17679. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  17680. sqlite3_release_memory(allocSize);
  17681. }
  17682. /*
  17683. ** Change the alarm callback
  17684. */
  17685. static int sqlite3MemoryAlarm(
  17686. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17687. void *pArg,
  17688. sqlite3_int64 iThreshold
  17689. ){
  17690. int nUsed;
  17691. sqlite3_mutex_enter(mem0.mutex);
  17692. mem0.alarmCallback = xCallback;
  17693. mem0.alarmArg = pArg;
  17694. mem0.alarmThreshold = iThreshold;
  17695. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17696. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  17697. sqlite3_mutex_leave(mem0.mutex);
  17698. return SQLITE_OK;
  17699. }
  17700. #ifndef SQLITE_OMIT_DEPRECATED
  17701. /*
  17702. ** Deprecated external interface. Internal/core SQLite code
  17703. ** should call sqlite3MemoryAlarm.
  17704. */
  17705. SQLITE_API int sqlite3_memory_alarm(
  17706. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17707. void *pArg,
  17708. sqlite3_int64 iThreshold
  17709. ){
  17710. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  17711. }
  17712. #endif
  17713. /*
  17714. ** Set the soft heap-size limit for the library. Passing a zero or
  17715. ** negative value indicates no limit.
  17716. */
  17717. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  17718. sqlite3_int64 priorLimit;
  17719. sqlite3_int64 excess;
  17720. #ifndef SQLITE_OMIT_AUTOINIT
  17721. int rc = sqlite3_initialize();
  17722. if( rc ) return -1;
  17723. #endif
  17724. sqlite3_mutex_enter(mem0.mutex);
  17725. priorLimit = mem0.alarmThreshold;
  17726. sqlite3_mutex_leave(mem0.mutex);
  17727. if( n<0 ) return priorLimit;
  17728. if( n>0 ){
  17729. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  17730. }else{
  17731. sqlite3MemoryAlarm(0, 0, 0);
  17732. }
  17733. excess = sqlite3_memory_used() - n;
  17734. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  17735. return priorLimit;
  17736. }
  17737. SQLITE_API void sqlite3_soft_heap_limit(int n){
  17738. if( n<0 ) n = 0;
  17739. sqlite3_soft_heap_limit64(n);
  17740. }
  17741. /*
  17742. ** Initialize the memory allocation subsystem.
  17743. */
  17744. SQLITE_PRIVATE int sqlite3MallocInit(void){
  17745. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  17746. sqlite3MemSetDefault();
  17747. }
  17748. memset(&mem0, 0, sizeof(mem0));
  17749. if( sqlite3GlobalConfig.bCoreMutex ){
  17750. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17751. }
  17752. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  17753. && sqlite3GlobalConfig.nScratch>0 ){
  17754. int i, n, sz;
  17755. ScratchFreeslot *pSlot;
  17756. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  17757. sqlite3GlobalConfig.szScratch = sz;
  17758. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  17759. n = sqlite3GlobalConfig.nScratch;
  17760. mem0.pScratchFree = pSlot;
  17761. mem0.nScratchFree = n;
  17762. for(i=0; i<n-1; i++){
  17763. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  17764. pSlot = pSlot->pNext;
  17765. }
  17766. pSlot->pNext = 0;
  17767. mem0.pScratchEnd = (void*)&pSlot[1];
  17768. }else{
  17769. mem0.pScratchEnd = 0;
  17770. sqlite3GlobalConfig.pScratch = 0;
  17771. sqlite3GlobalConfig.szScratch = 0;
  17772. sqlite3GlobalConfig.nScratch = 0;
  17773. }
  17774. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  17775. || sqlite3GlobalConfig.nPage<1 ){
  17776. sqlite3GlobalConfig.pPage = 0;
  17777. sqlite3GlobalConfig.szPage = 0;
  17778. sqlite3GlobalConfig.nPage = 0;
  17779. }
  17780. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  17781. }
  17782. /*
  17783. ** Return true if the heap is currently under memory pressure - in other
  17784. ** words if the amount of heap used is close to the limit set by
  17785. ** sqlite3_soft_heap_limit().
  17786. */
  17787. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  17788. return mem0.nearlyFull;
  17789. }
  17790. /*
  17791. ** Deinitialize the memory allocation subsystem.
  17792. */
  17793. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  17794. if( sqlite3GlobalConfig.m.xShutdown ){
  17795. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  17796. }
  17797. memset(&mem0, 0, sizeof(mem0));
  17798. }
  17799. /*
  17800. ** Return the amount of memory currently checked out.
  17801. */
  17802. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  17803. int n, mx;
  17804. sqlite3_int64 res;
  17805. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  17806. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  17807. return res;
  17808. }
  17809. /*
  17810. ** Return the maximum amount of memory that has ever been
  17811. ** checked out since either the beginning of this process
  17812. ** or since the most recent reset.
  17813. */
  17814. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  17815. int n, mx;
  17816. sqlite3_int64 res;
  17817. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  17818. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  17819. return res;
  17820. }
  17821. /*
  17822. ** Trigger the alarm
  17823. */
  17824. static void sqlite3MallocAlarm(int nByte){
  17825. void (*xCallback)(void*,sqlite3_int64,int);
  17826. sqlite3_int64 nowUsed;
  17827. void *pArg;
  17828. if( mem0.alarmCallback==0 ) return;
  17829. xCallback = mem0.alarmCallback;
  17830. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17831. pArg = mem0.alarmArg;
  17832. mem0.alarmCallback = 0;
  17833. sqlite3_mutex_leave(mem0.mutex);
  17834. xCallback(pArg, nowUsed, nByte);
  17835. sqlite3_mutex_enter(mem0.mutex);
  17836. mem0.alarmCallback = xCallback;
  17837. mem0.alarmArg = pArg;
  17838. }
  17839. /*
  17840. ** Do a memory allocation with statistics and alarms. Assume the
  17841. ** lock is already held.
  17842. */
  17843. static int mallocWithAlarm(int n, void **pp){
  17844. int nFull;
  17845. void *p;
  17846. assert( sqlite3_mutex_held(mem0.mutex) );
  17847. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  17848. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  17849. if( mem0.alarmCallback!=0 ){
  17850. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17851. if( nUsed >= mem0.alarmThreshold - nFull ){
  17852. mem0.nearlyFull = 1;
  17853. sqlite3MallocAlarm(nFull);
  17854. }else{
  17855. mem0.nearlyFull = 0;
  17856. }
  17857. }
  17858. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17859. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17860. if( p==0 && mem0.alarmCallback ){
  17861. sqlite3MallocAlarm(nFull);
  17862. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17863. }
  17864. #endif
  17865. if( p ){
  17866. nFull = sqlite3MallocSize(p);
  17867. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  17868. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  17869. }
  17870. *pp = p;
  17871. return nFull;
  17872. }
  17873. /*
  17874. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  17875. ** assumes the memory subsystem has already been initialized.
  17876. */
  17877. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  17878. void *p;
  17879. if( n<=0 /* IMP: R-65312-04917 */
  17880. || n>=0x7fffff00
  17881. ){
  17882. /* A memory allocation of a number of bytes which is near the maximum
  17883. ** signed integer value might cause an integer overflow inside of the
  17884. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  17885. ** 255 bytes of overhead. SQLite itself will never use anything near
  17886. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  17887. p = 0;
  17888. }else if( sqlite3GlobalConfig.bMemstat ){
  17889. sqlite3_mutex_enter(mem0.mutex);
  17890. mallocWithAlarm(n, &p);
  17891. sqlite3_mutex_leave(mem0.mutex);
  17892. }else{
  17893. p = sqlite3GlobalConfig.m.xMalloc(n);
  17894. }
  17895. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  17896. return p;
  17897. }
  17898. /*
  17899. ** This version of the memory allocation is for use by the application.
  17900. ** First make sure the memory subsystem is initialized, then do the
  17901. ** allocation.
  17902. */
  17903. SQLITE_API void *sqlite3_malloc(int n){
  17904. #ifndef SQLITE_OMIT_AUTOINIT
  17905. if( sqlite3_initialize() ) return 0;
  17906. #endif
  17907. return sqlite3Malloc(n);
  17908. }
  17909. /*
  17910. ** Each thread may only have a single outstanding allocation from
  17911. ** xScratchMalloc(). We verify this constraint in the single-threaded
  17912. ** case by setting scratchAllocOut to 1 when an allocation
  17913. ** is outstanding clearing it when the allocation is freed.
  17914. */
  17915. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17916. static int scratchAllocOut = 0;
  17917. #endif
  17918. /*
  17919. ** Allocate memory that is to be used and released right away.
  17920. ** This routine is similar to alloca() in that it is not intended
  17921. ** for situations where the memory might be held long-term. This
  17922. ** routine is intended to get memory to old large transient data
  17923. ** structures that would not normally fit on the stack of an
  17924. ** embedded processor.
  17925. */
  17926. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  17927. void *p;
  17928. assert( n>0 );
  17929. sqlite3_mutex_enter(mem0.mutex);
  17930. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  17931. p = mem0.pScratchFree;
  17932. mem0.pScratchFree = mem0.pScratchFree->pNext;
  17933. mem0.nScratchFree--;
  17934. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  17935. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17936. sqlite3_mutex_leave(mem0.mutex);
  17937. }else{
  17938. if( sqlite3GlobalConfig.bMemstat ){
  17939. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17940. n = mallocWithAlarm(n, &p);
  17941. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  17942. sqlite3_mutex_leave(mem0.mutex);
  17943. }else{
  17944. sqlite3_mutex_leave(mem0.mutex);
  17945. p = sqlite3GlobalConfig.m.xMalloc(n);
  17946. }
  17947. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  17948. }
  17949. assert( sqlite3_mutex_notheld(mem0.mutex) );
  17950. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17951. /* Verify that no more than two scratch allocations per thread
  17952. ** are outstanding at one time. (This is only checked in the
  17953. ** single-threaded case since checking in the multi-threaded case
  17954. ** would be much more complicated.) */
  17955. assert( scratchAllocOut<=1 );
  17956. if( p ) scratchAllocOut++;
  17957. #endif
  17958. return p;
  17959. }
  17960. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  17961. if( p ){
  17962. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17963. /* Verify that no more than two scratch allocation per thread
  17964. ** is outstanding at one time. (This is only checked in the
  17965. ** single-threaded case since checking in the multi-threaded case
  17966. ** would be much more complicated.) */
  17967. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  17968. scratchAllocOut--;
  17969. #endif
  17970. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  17971. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  17972. ScratchFreeslot *pSlot;
  17973. pSlot = (ScratchFreeslot*)p;
  17974. sqlite3_mutex_enter(mem0.mutex);
  17975. pSlot->pNext = mem0.pScratchFree;
  17976. mem0.pScratchFree = pSlot;
  17977. mem0.nScratchFree++;
  17978. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  17979. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  17980. sqlite3_mutex_leave(mem0.mutex);
  17981. }else{
  17982. /* Release memory back to the heap */
  17983. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  17984. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  17985. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  17986. if( sqlite3GlobalConfig.bMemstat ){
  17987. int iSize = sqlite3MallocSize(p);
  17988. sqlite3_mutex_enter(mem0.mutex);
  17989. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  17990. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  17991. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  17992. sqlite3GlobalConfig.m.xFree(p);
  17993. sqlite3_mutex_leave(mem0.mutex);
  17994. }else{
  17995. sqlite3GlobalConfig.m.xFree(p);
  17996. }
  17997. }
  17998. }
  17999. }
  18000. /*
  18001. ** TRUE if p is a lookaside memory allocation from db
  18002. */
  18003. #ifndef SQLITE_OMIT_LOOKASIDE
  18004. static int isLookaside(sqlite3 *db, void *p){
  18005. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18006. }
  18007. #else
  18008. #define isLookaside(A,B) 0
  18009. #endif
  18010. /*
  18011. ** Return the size of a memory allocation previously obtained from
  18012. ** sqlite3Malloc() or sqlite3_malloc().
  18013. */
  18014. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18015. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18016. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18017. return sqlite3GlobalConfig.m.xSize(p);
  18018. }
  18019. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18020. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18021. if( db && isLookaside(db, p) ){
  18022. return db->lookaside.sz;
  18023. }else{
  18024. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18025. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18026. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18027. return sqlite3GlobalConfig.m.xSize(p);
  18028. }
  18029. }
  18030. /*
  18031. ** Free memory previously obtained from sqlite3Malloc().
  18032. */
  18033. SQLITE_API void sqlite3_free(void *p){
  18034. if( p==0 ) return; /* IMP: R-49053-54554 */
  18035. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18036. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18037. if( sqlite3GlobalConfig.bMemstat ){
  18038. sqlite3_mutex_enter(mem0.mutex);
  18039. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18040. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18041. sqlite3GlobalConfig.m.xFree(p);
  18042. sqlite3_mutex_leave(mem0.mutex);
  18043. }else{
  18044. sqlite3GlobalConfig.m.xFree(p);
  18045. }
  18046. }
  18047. /*
  18048. ** Free memory that might be associated with a particular database
  18049. ** connection.
  18050. */
  18051. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18052. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18053. if( p==0 ) return;
  18054. if( db ){
  18055. if( db->pnBytesFreed ){
  18056. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18057. return;
  18058. }
  18059. if( isLookaside(db, p) ){
  18060. LookasideSlot *pBuf = (LookasideSlot*)p;
  18061. #if SQLITE_DEBUG
  18062. /* Trash all content in the buffer being freed */
  18063. memset(p, 0xaa, db->lookaside.sz);
  18064. #endif
  18065. pBuf->pNext = db->lookaside.pFree;
  18066. db->lookaside.pFree = pBuf;
  18067. db->lookaside.nOut--;
  18068. return;
  18069. }
  18070. }
  18071. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18072. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18073. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18074. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18075. sqlite3_free(p);
  18076. }
  18077. /*
  18078. ** Change the size of an existing memory allocation
  18079. */
  18080. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18081. int nOld, nNew, nDiff;
  18082. void *pNew;
  18083. if( pOld==0 ){
  18084. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18085. }
  18086. if( nBytes<=0 ){
  18087. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18088. return 0;
  18089. }
  18090. if( nBytes>=0x7fffff00 ){
  18091. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18092. return 0;
  18093. }
  18094. nOld = sqlite3MallocSize(pOld);
  18095. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18096. ** argument to xRealloc is always a value returned by a prior call to
  18097. ** xRoundup. */
  18098. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18099. if( nOld==nNew ){
  18100. pNew = pOld;
  18101. }else if( sqlite3GlobalConfig.bMemstat ){
  18102. sqlite3_mutex_enter(mem0.mutex);
  18103. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18104. nDiff = nNew - nOld;
  18105. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18106. mem0.alarmThreshold-nDiff ){
  18107. sqlite3MallocAlarm(nDiff);
  18108. }
  18109. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18110. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18111. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18112. if( pNew==0 && mem0.alarmCallback ){
  18113. sqlite3MallocAlarm(nBytes);
  18114. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18115. }
  18116. if( pNew ){
  18117. nNew = sqlite3MallocSize(pNew);
  18118. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18119. }
  18120. sqlite3_mutex_leave(mem0.mutex);
  18121. }else{
  18122. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18123. }
  18124. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18125. return pNew;
  18126. }
  18127. /*
  18128. ** The public interface to sqlite3Realloc. Make sure that the memory
  18129. ** subsystem is initialized prior to invoking sqliteRealloc.
  18130. */
  18131. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18132. #ifndef SQLITE_OMIT_AUTOINIT
  18133. if( sqlite3_initialize() ) return 0;
  18134. #endif
  18135. return sqlite3Realloc(pOld, n);
  18136. }
  18137. /*
  18138. ** Allocate and zero memory.
  18139. */
  18140. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18141. void *p = sqlite3Malloc(n);
  18142. if( p ){
  18143. memset(p, 0, n);
  18144. }
  18145. return p;
  18146. }
  18147. /*
  18148. ** Allocate and zero memory. If the allocation fails, make
  18149. ** the mallocFailed flag in the connection pointer.
  18150. */
  18151. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18152. void *p = sqlite3DbMallocRaw(db, n);
  18153. if( p ){
  18154. memset(p, 0, n);
  18155. }
  18156. return p;
  18157. }
  18158. /*
  18159. ** Allocate and zero memory. If the allocation fails, make
  18160. ** the mallocFailed flag in the connection pointer.
  18161. **
  18162. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18163. ** failure on the same database connection) then always return 0.
  18164. ** Hence for a particular database connection, once malloc starts
  18165. ** failing, it fails consistently until mallocFailed is reset.
  18166. ** This is an important assumption. There are many places in the
  18167. ** code that do things like this:
  18168. **
  18169. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18170. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18171. ** if( b ) a[10] = 9;
  18172. **
  18173. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18174. ** that all prior mallocs (ex: "a") worked too.
  18175. */
  18176. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18177. void *p;
  18178. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18179. assert( db==0 || db->pnBytesFreed==0 );
  18180. #ifndef SQLITE_OMIT_LOOKASIDE
  18181. if( db ){
  18182. LookasideSlot *pBuf;
  18183. if( db->mallocFailed ){
  18184. return 0;
  18185. }
  18186. if( db->lookaside.bEnabled ){
  18187. if( n>db->lookaside.sz ){
  18188. db->lookaside.anStat[1]++;
  18189. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18190. db->lookaside.anStat[2]++;
  18191. }else{
  18192. db->lookaside.pFree = pBuf->pNext;
  18193. db->lookaside.nOut++;
  18194. db->lookaside.anStat[0]++;
  18195. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18196. db->lookaside.mxOut = db->lookaside.nOut;
  18197. }
  18198. return (void*)pBuf;
  18199. }
  18200. }
  18201. }
  18202. #else
  18203. if( db && db->mallocFailed ){
  18204. return 0;
  18205. }
  18206. #endif
  18207. p = sqlite3Malloc(n);
  18208. if( !p && db ){
  18209. db->mallocFailed = 1;
  18210. }
  18211. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18212. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18213. return p;
  18214. }
  18215. /*
  18216. ** Resize the block of memory pointed to by p to n bytes. If the
  18217. ** resize fails, set the mallocFailed flag in the connection object.
  18218. */
  18219. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18220. void *pNew = 0;
  18221. assert( db!=0 );
  18222. assert( sqlite3_mutex_held(db->mutex) );
  18223. if( db->mallocFailed==0 ){
  18224. if( p==0 ){
  18225. return sqlite3DbMallocRaw(db, n);
  18226. }
  18227. if( isLookaside(db, p) ){
  18228. if( n<=db->lookaside.sz ){
  18229. return p;
  18230. }
  18231. pNew = sqlite3DbMallocRaw(db, n);
  18232. if( pNew ){
  18233. memcpy(pNew, p, db->lookaside.sz);
  18234. sqlite3DbFree(db, p);
  18235. }
  18236. }else{
  18237. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18238. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18239. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18240. pNew = sqlite3_realloc(p, n);
  18241. if( !pNew ){
  18242. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18243. db->mallocFailed = 1;
  18244. }
  18245. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18246. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18247. }
  18248. }
  18249. return pNew;
  18250. }
  18251. /*
  18252. ** Attempt to reallocate p. If the reallocation fails, then free p
  18253. ** and set the mallocFailed flag in the database connection.
  18254. */
  18255. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18256. void *pNew;
  18257. pNew = sqlite3DbRealloc(db, p, n);
  18258. if( !pNew ){
  18259. sqlite3DbFree(db, p);
  18260. }
  18261. return pNew;
  18262. }
  18263. /*
  18264. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18265. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18266. ** is because when memory debugging is turned on, these two functions are
  18267. ** called via macros that record the current file and line number in the
  18268. ** ThreadData structure.
  18269. */
  18270. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18271. char *zNew;
  18272. size_t n;
  18273. if( z==0 ){
  18274. return 0;
  18275. }
  18276. n = sqlite3Strlen30(z) + 1;
  18277. assert( (n&0x7fffffff)==n );
  18278. zNew = sqlite3DbMallocRaw(db, (int)n);
  18279. if( zNew ){
  18280. memcpy(zNew, z, n);
  18281. }
  18282. return zNew;
  18283. }
  18284. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18285. char *zNew;
  18286. if( z==0 ){
  18287. return 0;
  18288. }
  18289. assert( (n&0x7fffffff)==n );
  18290. zNew = sqlite3DbMallocRaw(db, n+1);
  18291. if( zNew ){
  18292. memcpy(zNew, z, n);
  18293. zNew[n] = 0;
  18294. }
  18295. return zNew;
  18296. }
  18297. /*
  18298. ** Create a string from the zFromat argument and the va_list that follows.
  18299. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18300. ** point to that string.
  18301. */
  18302. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18303. va_list ap;
  18304. char *z;
  18305. va_start(ap, zFormat);
  18306. z = sqlite3VMPrintf(db, zFormat, ap);
  18307. va_end(ap);
  18308. sqlite3DbFree(db, *pz);
  18309. *pz = z;
  18310. }
  18311. /*
  18312. ** This function must be called before exiting any API function (i.e.
  18313. ** returning control to the user) that has called sqlite3_malloc or
  18314. ** sqlite3_realloc.
  18315. **
  18316. ** The returned value is normally a copy of the second argument to this
  18317. ** function. However, if a malloc() failure has occurred since the previous
  18318. ** invocation SQLITE_NOMEM is returned instead.
  18319. **
  18320. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18321. ** then the connection error-code (the value returned by sqlite3_errcode())
  18322. ** is set to SQLITE_NOMEM.
  18323. */
  18324. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18325. /* If the db handle is not NULL, then we must hold the connection handle
  18326. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18327. ** is unsafe, as is the call to sqlite3Error().
  18328. */
  18329. assert( !db || sqlite3_mutex_held(db->mutex) );
  18330. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18331. sqlite3Error(db, SQLITE_NOMEM, 0);
  18332. db->mallocFailed = 0;
  18333. rc = SQLITE_NOMEM;
  18334. }
  18335. return rc & (db ? db->errMask : 0xff);
  18336. }
  18337. /************** End of malloc.c **********************************************/
  18338. /************** Begin file printf.c ******************************************/
  18339. /*
  18340. ** The "printf" code that follows dates from the 1980's. It is in
  18341. ** the public domain. The original comments are included here for
  18342. ** completeness. They are very out-of-date but might be useful as
  18343. ** an historical reference. Most of the "enhancements" have been backed
  18344. ** out so that the functionality is now the same as standard printf().
  18345. **
  18346. **************************************************************************
  18347. **
  18348. ** This file contains code for a set of "printf"-like routines. These
  18349. ** routines format strings much like the printf() from the standard C
  18350. ** library, though the implementation here has enhancements to support
  18351. ** SQLlite.
  18352. */
  18353. /*
  18354. ** Conversion types fall into various categories as defined by the
  18355. ** following enumeration.
  18356. */
  18357. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18358. #define etFLOAT 2 /* Floating point. %f */
  18359. #define etEXP 3 /* Exponentional notation. %e and %E */
  18360. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18361. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18362. #define etSTRING 6 /* Strings. %s */
  18363. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18364. #define etPERCENT 8 /* Percent symbol. %% */
  18365. #define etCHARX 9 /* Characters. %c */
  18366. /* The rest are extensions, not normally found in printf() */
  18367. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18368. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18369. NULL pointers replaced by SQL NULL. %Q */
  18370. #define etTOKEN 12 /* a pointer to a Token structure */
  18371. #define etSRCLIST 13 /* a pointer to a SrcList */
  18372. #define etPOINTER 14 /* The %p conversion */
  18373. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18374. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18375. #define etINVALID 0 /* Any unrecognized conversion type */
  18376. /*
  18377. ** An "etByte" is an 8-bit unsigned value.
  18378. */
  18379. typedef unsigned char etByte;
  18380. /*
  18381. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18382. ** by an instance of the following structure
  18383. */
  18384. typedef struct et_info { /* Information about each format field */
  18385. char fmttype; /* The format field code letter */
  18386. etByte base; /* The base for radix conversion */
  18387. etByte flags; /* One or more of FLAG_ constants below */
  18388. etByte type; /* Conversion paradigm */
  18389. etByte charset; /* Offset into aDigits[] of the digits string */
  18390. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18391. } et_info;
  18392. /*
  18393. ** Allowed values for et_info.flags
  18394. */
  18395. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  18396. #define FLAG_INTERN 2 /* True if for internal use only */
  18397. #define FLAG_STRING 4 /* Allow infinity precision */
  18398. /*
  18399. ** The following table is searched linearly, so it is good to put the
  18400. ** most frequently used conversion types first.
  18401. */
  18402. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  18403. static const char aPrefix[] = "-x0\000X0";
  18404. static const et_info fmtinfo[] = {
  18405. { 'd', 10, 1, etRADIX, 0, 0 },
  18406. { 's', 0, 4, etSTRING, 0, 0 },
  18407. { 'g', 0, 1, etGENERIC, 30, 0 },
  18408. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  18409. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  18410. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  18411. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  18412. { 'c', 0, 0, etCHARX, 0, 0 },
  18413. { 'o', 8, 0, etRADIX, 0, 2 },
  18414. { 'u', 10, 0, etRADIX, 0, 0 },
  18415. { 'x', 16, 0, etRADIX, 16, 1 },
  18416. { 'X', 16, 0, etRADIX, 0, 4 },
  18417. #ifndef SQLITE_OMIT_FLOATING_POINT
  18418. { 'f', 0, 1, etFLOAT, 0, 0 },
  18419. { 'e', 0, 1, etEXP, 30, 0 },
  18420. { 'E', 0, 1, etEXP, 14, 0 },
  18421. { 'G', 0, 1, etGENERIC, 14, 0 },
  18422. #endif
  18423. { 'i', 10, 1, etRADIX, 0, 0 },
  18424. { 'n', 0, 0, etSIZE, 0, 0 },
  18425. { '%', 0, 0, etPERCENT, 0, 0 },
  18426. { 'p', 16, 0, etPOINTER, 0, 1 },
  18427. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  18428. ** use only */
  18429. { 'T', 0, 2, etTOKEN, 0, 0 },
  18430. { 'S', 0, 2, etSRCLIST, 0, 0 },
  18431. { 'r', 10, 3, etORDINAL, 0, 0 },
  18432. };
  18433. /*
  18434. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  18435. ** conversions will work.
  18436. */
  18437. #ifndef SQLITE_OMIT_FLOATING_POINT
  18438. /*
  18439. ** "*val" is a double such that 0.1 <= *val < 10.0
  18440. ** Return the ascii code for the leading digit of *val, then
  18441. ** multiply "*val" by 10.0 to renormalize.
  18442. **
  18443. ** Example:
  18444. ** input: *val = 3.14159
  18445. ** output: *val = 1.4159 function return = '3'
  18446. **
  18447. ** The counter *cnt is incremented each time. After counter exceeds
  18448. ** 16 (the number of significant digits in a 64-bit float) '0' is
  18449. ** always returned.
  18450. */
  18451. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  18452. int digit;
  18453. LONGDOUBLE_TYPE d;
  18454. if( (*cnt)<=0 ) return '0';
  18455. (*cnt)--;
  18456. digit = (int)*val;
  18457. d = digit;
  18458. digit += '0';
  18459. *val = (*val - d)*10.0;
  18460. return (char)digit;
  18461. }
  18462. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18463. /*
  18464. ** Append N space characters to the given string buffer.
  18465. */
  18466. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  18467. static const char zSpaces[] = " ";
  18468. while( N>=(int)sizeof(zSpaces)-1 ){
  18469. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  18470. N -= sizeof(zSpaces)-1;
  18471. }
  18472. if( N>0 ){
  18473. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  18474. }
  18475. }
  18476. /*
  18477. ** On machines with a small stack size, you can redefine the
  18478. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  18479. */
  18480. #ifndef SQLITE_PRINT_BUF_SIZE
  18481. # define SQLITE_PRINT_BUF_SIZE 70
  18482. #endif
  18483. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  18484. /*
  18485. ** Render a string given by "fmt" into the StrAccum object.
  18486. */
  18487. SQLITE_PRIVATE void sqlite3VXPrintf(
  18488. StrAccum *pAccum, /* Accumulate results here */
  18489. int useExtended, /* Allow extended %-conversions */
  18490. const char *fmt, /* Format string */
  18491. va_list ap /* arguments */
  18492. ){
  18493. int c; /* Next character in the format string */
  18494. char *bufpt; /* Pointer to the conversion buffer */
  18495. int precision; /* Precision of the current field */
  18496. int length; /* Length of the field */
  18497. int idx; /* A general purpose loop counter */
  18498. int width; /* Width of the current field */
  18499. etByte flag_leftjustify; /* True if "-" flag is present */
  18500. etByte flag_plussign; /* True if "+" flag is present */
  18501. etByte flag_blanksign; /* True if " " flag is present */
  18502. etByte flag_alternateform; /* True if "#" flag is present */
  18503. etByte flag_altform2; /* True if "!" flag is present */
  18504. etByte flag_zeropad; /* True if field width constant starts with zero */
  18505. etByte flag_long; /* True if "l" flag is present */
  18506. etByte flag_longlong; /* True if the "ll" flag is present */
  18507. etByte done; /* Loop termination flag */
  18508. etByte xtype = 0; /* Conversion paradigm */
  18509. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  18510. sqlite_uint64 longvalue; /* Value for integer types */
  18511. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  18512. const et_info *infop; /* Pointer to the appropriate info structure */
  18513. char *zOut; /* Rendering buffer */
  18514. int nOut; /* Size of the rendering buffer */
  18515. char *zExtra; /* Malloced memory used by some conversion */
  18516. #ifndef SQLITE_OMIT_FLOATING_POINT
  18517. int exp, e2; /* exponent of real numbers */
  18518. int nsd; /* Number of significant digits returned */
  18519. double rounder; /* Used for rounding floating point values */
  18520. etByte flag_dp; /* True if decimal point should be shown */
  18521. etByte flag_rtz; /* True if trailing zeros should be removed */
  18522. #endif
  18523. char buf[etBUFSIZE]; /* Conversion buffer */
  18524. bufpt = 0;
  18525. for(; (c=(*fmt))!=0; ++fmt){
  18526. if( c!='%' ){
  18527. int amt;
  18528. bufpt = (char *)fmt;
  18529. amt = 1;
  18530. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  18531. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  18532. if( c==0 ) break;
  18533. }
  18534. if( (c=(*++fmt))==0 ){
  18535. sqlite3StrAccumAppend(pAccum, "%", 1);
  18536. break;
  18537. }
  18538. /* Find out what flags are present */
  18539. flag_leftjustify = flag_plussign = flag_blanksign =
  18540. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  18541. done = 0;
  18542. do{
  18543. switch( c ){
  18544. case '-': flag_leftjustify = 1; break;
  18545. case '+': flag_plussign = 1; break;
  18546. case ' ': flag_blanksign = 1; break;
  18547. case '#': flag_alternateform = 1; break;
  18548. case '!': flag_altform2 = 1; break;
  18549. case '0': flag_zeropad = 1; break;
  18550. default: done = 1; break;
  18551. }
  18552. }while( !done && (c=(*++fmt))!=0 );
  18553. /* Get the field width */
  18554. width = 0;
  18555. if( c=='*' ){
  18556. width = va_arg(ap,int);
  18557. if( width<0 ){
  18558. flag_leftjustify = 1;
  18559. width = -width;
  18560. }
  18561. c = *++fmt;
  18562. }else{
  18563. while( c>='0' && c<='9' ){
  18564. width = width*10 + c - '0';
  18565. c = *++fmt;
  18566. }
  18567. }
  18568. /* Get the precision */
  18569. if( c=='.' ){
  18570. precision = 0;
  18571. c = *++fmt;
  18572. if( c=='*' ){
  18573. precision = va_arg(ap,int);
  18574. if( precision<0 ) precision = -precision;
  18575. c = *++fmt;
  18576. }else{
  18577. while( c>='0' && c<='9' ){
  18578. precision = precision*10 + c - '0';
  18579. c = *++fmt;
  18580. }
  18581. }
  18582. }else{
  18583. precision = -1;
  18584. }
  18585. /* Get the conversion type modifier */
  18586. if( c=='l' ){
  18587. flag_long = 1;
  18588. c = *++fmt;
  18589. if( c=='l' ){
  18590. flag_longlong = 1;
  18591. c = *++fmt;
  18592. }else{
  18593. flag_longlong = 0;
  18594. }
  18595. }else{
  18596. flag_long = flag_longlong = 0;
  18597. }
  18598. /* Fetch the info entry for the field */
  18599. infop = &fmtinfo[0];
  18600. xtype = etINVALID;
  18601. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  18602. if( c==fmtinfo[idx].fmttype ){
  18603. infop = &fmtinfo[idx];
  18604. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  18605. xtype = infop->type;
  18606. }else{
  18607. return;
  18608. }
  18609. break;
  18610. }
  18611. }
  18612. zExtra = 0;
  18613. /*
  18614. ** At this point, variables are initialized as follows:
  18615. **
  18616. ** flag_alternateform TRUE if a '#' is present.
  18617. ** flag_altform2 TRUE if a '!' is present.
  18618. ** flag_plussign TRUE if a '+' is present.
  18619. ** flag_leftjustify TRUE if a '-' is present or if the
  18620. ** field width was negative.
  18621. ** flag_zeropad TRUE if the width began with 0.
  18622. ** flag_long TRUE if the letter 'l' (ell) prefixed
  18623. ** the conversion character.
  18624. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  18625. ** the conversion character.
  18626. ** flag_blanksign TRUE if a ' ' is present.
  18627. ** width The specified field width. This is
  18628. ** always non-negative. Zero is the default.
  18629. ** precision The specified precision. The default
  18630. ** is -1.
  18631. ** xtype The class of the conversion.
  18632. ** infop Pointer to the appropriate info struct.
  18633. */
  18634. switch( xtype ){
  18635. case etPOINTER:
  18636. flag_longlong = sizeof(char*)==sizeof(i64);
  18637. flag_long = sizeof(char*)==sizeof(long int);
  18638. /* Fall through into the next case */
  18639. case etORDINAL:
  18640. case etRADIX:
  18641. if( infop->flags & FLAG_SIGNED ){
  18642. i64 v;
  18643. if( flag_longlong ){
  18644. v = va_arg(ap,i64);
  18645. }else if( flag_long ){
  18646. v = va_arg(ap,long int);
  18647. }else{
  18648. v = va_arg(ap,int);
  18649. }
  18650. if( v<0 ){
  18651. if( v==SMALLEST_INT64 ){
  18652. longvalue = ((u64)1)<<63;
  18653. }else{
  18654. longvalue = -v;
  18655. }
  18656. prefix = '-';
  18657. }else{
  18658. longvalue = v;
  18659. if( flag_plussign ) prefix = '+';
  18660. else if( flag_blanksign ) prefix = ' ';
  18661. else prefix = 0;
  18662. }
  18663. }else{
  18664. if( flag_longlong ){
  18665. longvalue = va_arg(ap,u64);
  18666. }else if( flag_long ){
  18667. longvalue = va_arg(ap,unsigned long int);
  18668. }else{
  18669. longvalue = va_arg(ap,unsigned int);
  18670. }
  18671. prefix = 0;
  18672. }
  18673. if( longvalue==0 ) flag_alternateform = 0;
  18674. if( flag_zeropad && precision<width-(prefix!=0) ){
  18675. precision = width-(prefix!=0);
  18676. }
  18677. if( precision<etBUFSIZE-10 ){
  18678. nOut = etBUFSIZE;
  18679. zOut = buf;
  18680. }else{
  18681. nOut = precision + 10;
  18682. zOut = zExtra = sqlite3Malloc( nOut );
  18683. if( zOut==0 ){
  18684. pAccum->accError = STRACCUM_NOMEM;
  18685. return;
  18686. }
  18687. }
  18688. bufpt = &zOut[nOut-1];
  18689. if( xtype==etORDINAL ){
  18690. static const char zOrd[] = "thstndrd";
  18691. int x = (int)(longvalue % 10);
  18692. if( x>=4 || (longvalue/10)%10==1 ){
  18693. x = 0;
  18694. }
  18695. *(--bufpt) = zOrd[x*2+1];
  18696. *(--bufpt) = zOrd[x*2];
  18697. }
  18698. {
  18699. register const char *cset; /* Use registers for speed */
  18700. register int base;
  18701. cset = &aDigits[infop->charset];
  18702. base = infop->base;
  18703. do{ /* Convert to ascii */
  18704. *(--bufpt) = cset[longvalue%base];
  18705. longvalue = longvalue/base;
  18706. }while( longvalue>0 );
  18707. }
  18708. length = (int)(&zOut[nOut-1]-bufpt);
  18709. for(idx=precision-length; idx>0; idx--){
  18710. *(--bufpt) = '0'; /* Zero pad */
  18711. }
  18712. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  18713. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  18714. const char *pre;
  18715. char x;
  18716. pre = &aPrefix[infop->prefix];
  18717. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  18718. }
  18719. length = (int)(&zOut[nOut-1]-bufpt);
  18720. break;
  18721. case etFLOAT:
  18722. case etEXP:
  18723. case etGENERIC:
  18724. realvalue = va_arg(ap,double);
  18725. #ifdef SQLITE_OMIT_FLOATING_POINT
  18726. length = 0;
  18727. #else
  18728. if( precision<0 ) precision = 6; /* Set default precision */
  18729. if( realvalue<0.0 ){
  18730. realvalue = -realvalue;
  18731. prefix = '-';
  18732. }else{
  18733. if( flag_plussign ) prefix = '+';
  18734. else if( flag_blanksign ) prefix = ' ';
  18735. else prefix = 0;
  18736. }
  18737. if( xtype==etGENERIC && precision>0 ) precision--;
  18738. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  18739. if( xtype==etFLOAT ) realvalue += rounder;
  18740. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  18741. exp = 0;
  18742. if( sqlite3IsNaN((double)realvalue) ){
  18743. bufpt = "NaN";
  18744. length = 3;
  18745. break;
  18746. }
  18747. if( realvalue>0.0 ){
  18748. LONGDOUBLE_TYPE scale = 1.0;
  18749. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  18750. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  18751. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  18752. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  18753. realvalue /= scale;
  18754. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  18755. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  18756. if( exp>350 ){
  18757. if( prefix=='-' ){
  18758. bufpt = "-Inf";
  18759. }else if( prefix=='+' ){
  18760. bufpt = "+Inf";
  18761. }else{
  18762. bufpt = "Inf";
  18763. }
  18764. length = sqlite3Strlen30(bufpt);
  18765. break;
  18766. }
  18767. }
  18768. bufpt = buf;
  18769. /*
  18770. ** If the field type is etGENERIC, then convert to either etEXP
  18771. ** or etFLOAT, as appropriate.
  18772. */
  18773. if( xtype!=etFLOAT ){
  18774. realvalue += rounder;
  18775. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  18776. }
  18777. if( xtype==etGENERIC ){
  18778. flag_rtz = !flag_alternateform;
  18779. if( exp<-4 || exp>precision ){
  18780. xtype = etEXP;
  18781. }else{
  18782. precision = precision - exp;
  18783. xtype = etFLOAT;
  18784. }
  18785. }else{
  18786. flag_rtz = flag_altform2;
  18787. }
  18788. if( xtype==etEXP ){
  18789. e2 = 0;
  18790. }else{
  18791. e2 = exp;
  18792. }
  18793. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  18794. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  18795. if( bufpt==0 ){
  18796. pAccum->accError = STRACCUM_NOMEM;
  18797. return;
  18798. }
  18799. }
  18800. zOut = bufpt;
  18801. nsd = 16 + flag_altform2*10;
  18802. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  18803. /* The sign in front of the number */
  18804. if( prefix ){
  18805. *(bufpt++) = prefix;
  18806. }
  18807. /* Digits prior to the decimal point */
  18808. if( e2<0 ){
  18809. *(bufpt++) = '0';
  18810. }else{
  18811. for(; e2>=0; e2--){
  18812. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18813. }
  18814. }
  18815. /* The decimal point */
  18816. if( flag_dp ){
  18817. *(bufpt++) = '.';
  18818. }
  18819. /* "0" digits after the decimal point but before the first
  18820. ** significant digit of the number */
  18821. for(e2++; e2<0; precision--, e2++){
  18822. assert( precision>0 );
  18823. *(bufpt++) = '0';
  18824. }
  18825. /* Significant digits after the decimal point */
  18826. while( (precision--)>0 ){
  18827. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18828. }
  18829. /* Remove trailing zeros and the "." if no digits follow the "." */
  18830. if( flag_rtz && flag_dp ){
  18831. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  18832. assert( bufpt>zOut );
  18833. if( bufpt[-1]=='.' ){
  18834. if( flag_altform2 ){
  18835. *(bufpt++) = '0';
  18836. }else{
  18837. *(--bufpt) = 0;
  18838. }
  18839. }
  18840. }
  18841. /* Add the "eNNN" suffix */
  18842. if( xtype==etEXP ){
  18843. *(bufpt++) = aDigits[infop->charset];
  18844. if( exp<0 ){
  18845. *(bufpt++) = '-'; exp = -exp;
  18846. }else{
  18847. *(bufpt++) = '+';
  18848. }
  18849. if( exp>=100 ){
  18850. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  18851. exp %= 100;
  18852. }
  18853. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  18854. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  18855. }
  18856. *bufpt = 0;
  18857. /* The converted number is in buf[] and zero terminated. Output it.
  18858. ** Note that the number is in the usual order, not reversed as with
  18859. ** integer conversions. */
  18860. length = (int)(bufpt-zOut);
  18861. bufpt = zOut;
  18862. /* Special case: Add leading zeros if the flag_zeropad flag is
  18863. ** set and we are not left justified */
  18864. if( flag_zeropad && !flag_leftjustify && length < width){
  18865. int i;
  18866. int nPad = width - length;
  18867. for(i=width; i>=nPad; i--){
  18868. bufpt[i] = bufpt[i-nPad];
  18869. }
  18870. i = prefix!=0;
  18871. while( nPad-- ) bufpt[i++] = '0';
  18872. length = width;
  18873. }
  18874. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  18875. break;
  18876. case etSIZE:
  18877. *(va_arg(ap,int*)) = pAccum->nChar;
  18878. length = width = 0;
  18879. break;
  18880. case etPERCENT:
  18881. buf[0] = '%';
  18882. bufpt = buf;
  18883. length = 1;
  18884. break;
  18885. case etCHARX:
  18886. c = va_arg(ap,int);
  18887. buf[0] = (char)c;
  18888. if( precision>=0 ){
  18889. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  18890. length = precision;
  18891. }else{
  18892. length =1;
  18893. }
  18894. bufpt = buf;
  18895. break;
  18896. case etSTRING:
  18897. case etDYNSTRING:
  18898. bufpt = va_arg(ap,char*);
  18899. if( bufpt==0 ){
  18900. bufpt = "";
  18901. }else if( xtype==etDYNSTRING ){
  18902. zExtra = bufpt;
  18903. }
  18904. if( precision>=0 ){
  18905. for(length=0; length<precision && bufpt[length]; length++){}
  18906. }else{
  18907. length = sqlite3Strlen30(bufpt);
  18908. }
  18909. break;
  18910. case etSQLESCAPE:
  18911. case etSQLESCAPE2:
  18912. case etSQLESCAPE3: {
  18913. int i, j, k, n, isnull;
  18914. int needQuote;
  18915. char ch;
  18916. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  18917. char *escarg = va_arg(ap,char*);
  18918. isnull = escarg==0;
  18919. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  18920. k = precision;
  18921. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  18922. if( ch==q ) n++;
  18923. }
  18924. needQuote = !isnull && xtype==etSQLESCAPE2;
  18925. n += i + 1 + needQuote*2;
  18926. if( n>etBUFSIZE ){
  18927. bufpt = zExtra = sqlite3Malloc( n );
  18928. if( bufpt==0 ){
  18929. pAccum->accError = STRACCUM_NOMEM;
  18930. return;
  18931. }
  18932. }else{
  18933. bufpt = buf;
  18934. }
  18935. j = 0;
  18936. if( needQuote ) bufpt[j++] = q;
  18937. k = i;
  18938. for(i=0; i<k; i++){
  18939. bufpt[j++] = ch = escarg[i];
  18940. if( ch==q ) bufpt[j++] = ch;
  18941. }
  18942. if( needQuote ) bufpt[j++] = q;
  18943. bufpt[j] = 0;
  18944. length = j;
  18945. /* The precision in %q and %Q means how many input characters to
  18946. ** consume, not the length of the output...
  18947. ** if( precision>=0 && precision<length ) length = precision; */
  18948. break;
  18949. }
  18950. case etTOKEN: {
  18951. Token *pToken = va_arg(ap, Token*);
  18952. if( pToken ){
  18953. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  18954. }
  18955. length = width = 0;
  18956. break;
  18957. }
  18958. case etSRCLIST: {
  18959. SrcList *pSrc = va_arg(ap, SrcList*);
  18960. int k = va_arg(ap, int);
  18961. struct SrcList_item *pItem = &pSrc->a[k];
  18962. assert( k>=0 && k<pSrc->nSrc );
  18963. if( pItem->zDatabase ){
  18964. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  18965. sqlite3StrAccumAppend(pAccum, ".", 1);
  18966. }
  18967. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  18968. length = width = 0;
  18969. break;
  18970. }
  18971. default: {
  18972. assert( xtype==etINVALID );
  18973. return;
  18974. }
  18975. }/* End switch over the format type */
  18976. /*
  18977. ** The text of the conversion is pointed to by "bufpt" and is
  18978. ** "length" characters long. The field width is "width". Do
  18979. ** the output.
  18980. */
  18981. if( !flag_leftjustify ){
  18982. register int nspace;
  18983. nspace = width-length;
  18984. if( nspace>0 ){
  18985. sqlite3AppendSpace(pAccum, nspace);
  18986. }
  18987. }
  18988. if( length>0 ){
  18989. sqlite3StrAccumAppend(pAccum, bufpt, length);
  18990. }
  18991. if( flag_leftjustify ){
  18992. register int nspace;
  18993. nspace = width-length;
  18994. if( nspace>0 ){
  18995. sqlite3AppendSpace(pAccum, nspace);
  18996. }
  18997. }
  18998. sqlite3_free(zExtra);
  18999. }/* End for loop over the format string */
  19000. } /* End of function */
  19001. /*
  19002. ** Append N bytes of text from z to the StrAccum object.
  19003. */
  19004. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19005. assert( z!=0 || N==0 );
  19006. if( p->accError ){
  19007. testcase(p->accError==STRACCUM_TOOBIG);
  19008. testcase(p->accError==STRACCUM_NOMEM);
  19009. return;
  19010. }
  19011. assert( p->zText!=0 || p->nChar==0 );
  19012. if( N<=0 ){
  19013. if( N==0 || z[0]==0 ) return;
  19014. N = sqlite3Strlen30(z);
  19015. }
  19016. if( p->nChar+N >= p->nAlloc ){
  19017. char *zNew;
  19018. if( !p->useMalloc ){
  19019. p->accError = STRACCUM_TOOBIG;
  19020. N = p->nAlloc - p->nChar - 1;
  19021. if( N<=0 ){
  19022. return;
  19023. }
  19024. }else{
  19025. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19026. i64 szNew = p->nChar;
  19027. szNew += N + 1;
  19028. if( szNew > p->mxAlloc ){
  19029. sqlite3StrAccumReset(p);
  19030. p->accError = STRACCUM_TOOBIG;
  19031. return;
  19032. }else{
  19033. p->nAlloc = (int)szNew;
  19034. }
  19035. if( p->useMalloc==1 ){
  19036. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19037. }else{
  19038. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19039. }
  19040. if( zNew ){
  19041. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19042. p->zText = zNew;
  19043. }else{
  19044. p->accError = STRACCUM_NOMEM;
  19045. sqlite3StrAccumReset(p);
  19046. return;
  19047. }
  19048. }
  19049. }
  19050. assert( p->zText );
  19051. memcpy(&p->zText[p->nChar], z, N);
  19052. p->nChar += N;
  19053. }
  19054. /*
  19055. ** Finish off a string by making sure it is zero-terminated.
  19056. ** Return a pointer to the resulting string. Return a NULL
  19057. ** pointer if any kind of error was encountered.
  19058. */
  19059. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19060. if( p->zText ){
  19061. p->zText[p->nChar] = 0;
  19062. if( p->useMalloc && p->zText==p->zBase ){
  19063. if( p->useMalloc==1 ){
  19064. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19065. }else{
  19066. p->zText = sqlite3_malloc(p->nChar+1);
  19067. }
  19068. if( p->zText ){
  19069. memcpy(p->zText, p->zBase, p->nChar+1);
  19070. }else{
  19071. p->accError = STRACCUM_NOMEM;
  19072. }
  19073. }
  19074. }
  19075. return p->zText;
  19076. }
  19077. /*
  19078. ** Reset an StrAccum string. Reclaim all malloced memory.
  19079. */
  19080. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19081. if( p->zText!=p->zBase ){
  19082. if( p->useMalloc==1 ){
  19083. sqlite3DbFree(p->db, p->zText);
  19084. }else{
  19085. sqlite3_free(p->zText);
  19086. }
  19087. }
  19088. p->zText = 0;
  19089. }
  19090. /*
  19091. ** Initialize a string accumulator
  19092. */
  19093. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19094. p->zText = p->zBase = zBase;
  19095. p->db = 0;
  19096. p->nChar = 0;
  19097. p->nAlloc = n;
  19098. p->mxAlloc = mx;
  19099. p->useMalloc = 1;
  19100. p->accError = 0;
  19101. }
  19102. /*
  19103. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19104. ** %-conversion extensions.
  19105. */
  19106. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19107. char *z;
  19108. char zBase[SQLITE_PRINT_BUF_SIZE];
  19109. StrAccum acc;
  19110. assert( db!=0 );
  19111. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19112. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19113. acc.db = db;
  19114. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19115. z = sqlite3StrAccumFinish(&acc);
  19116. if( acc.accError==STRACCUM_NOMEM ){
  19117. db->mallocFailed = 1;
  19118. }
  19119. return z;
  19120. }
  19121. /*
  19122. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19123. ** %-conversion extensions.
  19124. */
  19125. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19126. va_list ap;
  19127. char *z;
  19128. va_start(ap, zFormat);
  19129. z = sqlite3VMPrintf(db, zFormat, ap);
  19130. va_end(ap);
  19131. return z;
  19132. }
  19133. /*
  19134. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19135. ** the string and before returnning. This routine is intended to be used
  19136. ** to modify an existing string. For example:
  19137. **
  19138. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19139. **
  19140. */
  19141. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19142. va_list ap;
  19143. char *z;
  19144. va_start(ap, zFormat);
  19145. z = sqlite3VMPrintf(db, zFormat, ap);
  19146. va_end(ap);
  19147. sqlite3DbFree(db, zStr);
  19148. return z;
  19149. }
  19150. /*
  19151. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19152. ** %-conversion extensions.
  19153. */
  19154. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19155. char *z;
  19156. char zBase[SQLITE_PRINT_BUF_SIZE];
  19157. StrAccum acc;
  19158. #ifndef SQLITE_OMIT_AUTOINIT
  19159. if( sqlite3_initialize() ) return 0;
  19160. #endif
  19161. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19162. acc.useMalloc = 2;
  19163. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19164. z = sqlite3StrAccumFinish(&acc);
  19165. return z;
  19166. }
  19167. /*
  19168. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19169. ** %-conversion extensions.
  19170. */
  19171. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19172. va_list ap;
  19173. char *z;
  19174. #ifndef SQLITE_OMIT_AUTOINIT
  19175. if( sqlite3_initialize() ) return 0;
  19176. #endif
  19177. va_start(ap, zFormat);
  19178. z = sqlite3_vmprintf(zFormat, ap);
  19179. va_end(ap);
  19180. return z;
  19181. }
  19182. /*
  19183. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19184. ** current locale settings. This is important for SQLite because we
  19185. ** are not able to use a "," as the decimal point in place of "." as
  19186. ** specified by some locales.
  19187. **
  19188. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19189. ** from the snprintf() standard. Unfortunately, it is too late to change
  19190. ** this without breaking compatibility, so we just have to live with the
  19191. ** mistake.
  19192. **
  19193. ** sqlite3_vsnprintf() is the varargs version.
  19194. */
  19195. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19196. StrAccum acc;
  19197. if( n<=0 ) return zBuf;
  19198. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19199. acc.useMalloc = 0;
  19200. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19201. return sqlite3StrAccumFinish(&acc);
  19202. }
  19203. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19204. char *z;
  19205. va_list ap;
  19206. va_start(ap,zFormat);
  19207. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19208. va_end(ap);
  19209. return z;
  19210. }
  19211. /*
  19212. ** This is the routine that actually formats the sqlite3_log() message.
  19213. ** We house it in a separate routine from sqlite3_log() to avoid using
  19214. ** stack space on small-stack systems when logging is disabled.
  19215. **
  19216. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19217. ** allocate memory because it might be called while the memory allocator
  19218. ** mutex is held.
  19219. */
  19220. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19221. StrAccum acc; /* String accumulator */
  19222. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19223. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19224. acc.useMalloc = 0;
  19225. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19226. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19227. sqlite3StrAccumFinish(&acc));
  19228. }
  19229. /*
  19230. ** Format and write a message to the log if logging is enabled.
  19231. */
  19232. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19233. va_list ap; /* Vararg list */
  19234. if( sqlite3GlobalConfig.xLog ){
  19235. va_start(ap, zFormat);
  19236. renderLogMsg(iErrCode, zFormat, ap);
  19237. va_end(ap);
  19238. }
  19239. }
  19240. #if defined(SQLITE_DEBUG)
  19241. /*
  19242. ** A version of printf() that understands %lld. Used for debugging.
  19243. ** The printf() built into some versions of windows does not understand %lld
  19244. ** and segfaults if you give it a long long int.
  19245. */
  19246. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19247. va_list ap;
  19248. StrAccum acc;
  19249. char zBuf[500];
  19250. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19251. acc.useMalloc = 0;
  19252. va_start(ap,zFormat);
  19253. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19254. va_end(ap);
  19255. sqlite3StrAccumFinish(&acc);
  19256. fprintf(stdout,"%s", zBuf);
  19257. fflush(stdout);
  19258. }
  19259. #endif
  19260. #ifndef SQLITE_OMIT_TRACE
  19261. /*
  19262. ** variable-argument wrapper around sqlite3VXPrintf().
  19263. */
  19264. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19265. va_list ap;
  19266. va_start(ap,zFormat);
  19267. sqlite3VXPrintf(p, 1, zFormat, ap);
  19268. va_end(ap);
  19269. }
  19270. #endif
  19271. /************** End of printf.c **********************************************/
  19272. /************** Begin file random.c ******************************************/
  19273. /*
  19274. ** 2001 September 15
  19275. **
  19276. ** The author disclaims copyright to this source code. In place of
  19277. ** a legal notice, here is a blessing:
  19278. **
  19279. ** May you do good and not evil.
  19280. ** May you find forgiveness for yourself and forgive others.
  19281. ** May you share freely, never taking more than you give.
  19282. **
  19283. *************************************************************************
  19284. ** This file contains code to implement a pseudo-random number
  19285. ** generator (PRNG) for SQLite.
  19286. **
  19287. ** Random numbers are used by some of the database backends in order
  19288. ** to generate random integer keys for tables or random filenames.
  19289. */
  19290. /* All threads share a single random number generator.
  19291. ** This structure is the current state of the generator.
  19292. */
  19293. static SQLITE_WSD struct sqlite3PrngType {
  19294. unsigned char isInit; /* True if initialized */
  19295. unsigned char i, j; /* State variables */
  19296. unsigned char s[256]; /* State variables */
  19297. } sqlite3Prng;
  19298. /*
  19299. ** Return N random bytes.
  19300. */
  19301. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19302. unsigned char t;
  19303. unsigned char *zBuf = pBuf;
  19304. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19305. ** state vector. If writable static data is unsupported on the target,
  19306. ** we have to locate the state vector at run-time. In the more common
  19307. ** case where writable static data is supported, wsdPrng can refer directly
  19308. ** to the "sqlite3Prng" state vector declared above.
  19309. */
  19310. #ifdef SQLITE_OMIT_WSD
  19311. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19312. # define wsdPrng p[0]
  19313. #else
  19314. # define wsdPrng sqlite3Prng
  19315. #endif
  19316. #if SQLITE_THREADSAFE
  19317. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19318. sqlite3_mutex_enter(mutex);
  19319. #endif
  19320. /* Initialize the state of the random number generator once,
  19321. ** the first time this routine is called. The seed value does
  19322. ** not need to contain a lot of randomness since we are not
  19323. ** trying to do secure encryption or anything like that...
  19324. **
  19325. ** Nothing in this file or anywhere else in SQLite does any kind of
  19326. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19327. ** number generator) not as an encryption device.
  19328. */
  19329. if( !wsdPrng.isInit ){
  19330. int i;
  19331. char k[256];
  19332. wsdPrng.j = 0;
  19333. wsdPrng.i = 0;
  19334. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19335. for(i=0; i<256; i++){
  19336. wsdPrng.s[i] = (u8)i;
  19337. }
  19338. for(i=0; i<256; i++){
  19339. wsdPrng.j += wsdPrng.s[i] + k[i];
  19340. t = wsdPrng.s[wsdPrng.j];
  19341. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19342. wsdPrng.s[i] = t;
  19343. }
  19344. wsdPrng.isInit = 1;
  19345. }
  19346. while( N-- ){
  19347. wsdPrng.i++;
  19348. t = wsdPrng.s[wsdPrng.i];
  19349. wsdPrng.j += t;
  19350. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19351. wsdPrng.s[wsdPrng.j] = t;
  19352. t += wsdPrng.s[wsdPrng.i];
  19353. *(zBuf++) = wsdPrng.s[t];
  19354. }
  19355. sqlite3_mutex_leave(mutex);
  19356. }
  19357. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19358. /*
  19359. ** For testing purposes, we sometimes want to preserve the state of
  19360. ** PRNG and restore the PRNG to its saved state at a later time, or
  19361. ** to reset the PRNG to its initial state. These routines accomplish
  19362. ** those tasks.
  19363. **
  19364. ** The sqlite3_test_control() interface calls these routines to
  19365. ** control the PRNG.
  19366. */
  19367. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19368. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19369. memcpy(
  19370. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19371. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19372. sizeof(sqlite3Prng)
  19373. );
  19374. }
  19375. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19376. memcpy(
  19377. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19378. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19379. sizeof(sqlite3Prng)
  19380. );
  19381. }
  19382. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19383. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19384. }
  19385. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19386. /************** End of random.c **********************************************/
  19387. /************** Begin file utf.c *********************************************/
  19388. /*
  19389. ** 2004 April 13
  19390. **
  19391. ** The author disclaims copyright to this source code. In place of
  19392. ** a legal notice, here is a blessing:
  19393. **
  19394. ** May you do good and not evil.
  19395. ** May you find forgiveness for yourself and forgive others.
  19396. ** May you share freely, never taking more than you give.
  19397. **
  19398. *************************************************************************
  19399. ** This file contains routines used to translate between UTF-8,
  19400. ** UTF-16, UTF-16BE, and UTF-16LE.
  19401. **
  19402. ** Notes on UTF-8:
  19403. **
  19404. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  19405. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  19406. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  19407. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  19408. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19409. **
  19410. **
  19411. ** Notes on UTF-16: (with wwww+1==uuuuu)
  19412. **
  19413. ** Word-0 Word-1 Value
  19414. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19415. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  19416. **
  19417. **
  19418. ** BOM or Byte Order Mark:
  19419. ** 0xff 0xfe little-endian utf-16 follows
  19420. ** 0xfe 0xff big-endian utf-16 follows
  19421. **
  19422. */
  19423. /* #include <assert.h> */
  19424. #ifndef SQLITE_AMALGAMATION
  19425. /*
  19426. ** The following constant value is used by the SQLITE_BIGENDIAN and
  19427. ** SQLITE_LITTLEENDIAN macros.
  19428. */
  19429. SQLITE_PRIVATE const int sqlite3one = 1;
  19430. #endif /* SQLITE_AMALGAMATION */
  19431. /*
  19432. ** This lookup table is used to help decode the first byte of
  19433. ** a multi-byte UTF8 character.
  19434. */
  19435. static const unsigned char sqlite3Utf8Trans1[] = {
  19436. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19437. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19438. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  19439. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  19440. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19441. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19442. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19443. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  19444. };
  19445. #define WRITE_UTF8(zOut, c) { \
  19446. if( c<0x00080 ){ \
  19447. *zOut++ = (u8)(c&0xFF); \
  19448. } \
  19449. else if( c<0x00800 ){ \
  19450. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  19451. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19452. } \
  19453. else if( c<0x10000 ){ \
  19454. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  19455. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19456. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19457. }else{ \
  19458. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  19459. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  19460. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19461. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19462. } \
  19463. }
  19464. #define WRITE_UTF16LE(zOut, c) { \
  19465. if( c<=0xFFFF ){ \
  19466. *zOut++ = (u8)(c&0x00FF); \
  19467. *zOut++ = (u8)((c>>8)&0x00FF); \
  19468. }else{ \
  19469. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19470. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19471. *zOut++ = (u8)(c&0x00FF); \
  19472. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19473. } \
  19474. }
  19475. #define WRITE_UTF16BE(zOut, c) { \
  19476. if( c<=0xFFFF ){ \
  19477. *zOut++ = (u8)((c>>8)&0x00FF); \
  19478. *zOut++ = (u8)(c&0x00FF); \
  19479. }else{ \
  19480. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19481. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19482. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19483. *zOut++ = (u8)(c&0x00FF); \
  19484. } \
  19485. }
  19486. #define READ_UTF16LE(zIn, TERM, c){ \
  19487. c = (*zIn++); \
  19488. c += ((*zIn++)<<8); \
  19489. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19490. int c2 = (*zIn++); \
  19491. c2 += ((*zIn++)<<8); \
  19492. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19493. } \
  19494. }
  19495. #define READ_UTF16BE(zIn, TERM, c){ \
  19496. c = ((*zIn++)<<8); \
  19497. c += (*zIn++); \
  19498. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19499. int c2 = ((*zIn++)<<8); \
  19500. c2 += (*zIn++); \
  19501. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19502. } \
  19503. }
  19504. /*
  19505. ** Translate a single UTF-8 character. Return the unicode value.
  19506. **
  19507. ** During translation, assume that the byte that zTerm points
  19508. ** is a 0x00.
  19509. **
  19510. ** Write a pointer to the next unread byte back into *pzNext.
  19511. **
  19512. ** Notes On Invalid UTF-8:
  19513. **
  19514. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  19515. ** be encoded as a multi-byte character. Any multi-byte character that
  19516. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  19517. **
  19518. ** * This routine never allows a UTF16 surrogate value to be encoded.
  19519. ** If a multi-byte character attempts to encode a value between
  19520. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  19521. **
  19522. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  19523. ** byte of a character are interpreted as single-byte characters
  19524. ** and rendered as themselves even though they are technically
  19525. ** invalid characters.
  19526. **
  19527. ** * This routine accepts an infinite number of different UTF8 encodings
  19528. ** for unicode values 0x80 and greater. It do not change over-length
  19529. ** encodings to 0xfffd as some systems recommend.
  19530. */
  19531. #define READ_UTF8(zIn, zTerm, c) \
  19532. c = *(zIn++); \
  19533. if( c>=0xc0 ){ \
  19534. c = sqlite3Utf8Trans1[c-0xc0]; \
  19535. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  19536. c = (c<<6) + (0x3f & *(zIn++)); \
  19537. } \
  19538. if( c<0x80 \
  19539. || (c&0xFFFFF800)==0xD800 \
  19540. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  19541. }
  19542. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  19543. const unsigned char **pz /* Pointer to string from which to read char */
  19544. ){
  19545. unsigned int c;
  19546. /* Same as READ_UTF8() above but without the zTerm parameter.
  19547. ** For this routine, we assume the UTF8 string is always zero-terminated.
  19548. */
  19549. c = *((*pz)++);
  19550. if( c>=0xc0 ){
  19551. c = sqlite3Utf8Trans1[c-0xc0];
  19552. while( (*(*pz) & 0xc0)==0x80 ){
  19553. c = (c<<6) + (0x3f & *((*pz)++));
  19554. }
  19555. if( c<0x80
  19556. || (c&0xFFFFF800)==0xD800
  19557. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  19558. }
  19559. return c;
  19560. }
  19561. /*
  19562. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  19563. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  19564. */
  19565. /* #define TRANSLATE_TRACE 1 */
  19566. #ifndef SQLITE_OMIT_UTF16
  19567. /*
  19568. ** This routine transforms the internal text encoding used by pMem to
  19569. ** desiredEnc. It is an error if the string is already of the desired
  19570. ** encoding, or if *pMem does not contain a string value.
  19571. */
  19572. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  19573. int len; /* Maximum length of output string in bytes */
  19574. unsigned char *zOut; /* Output buffer */
  19575. unsigned char *zIn; /* Input iterator */
  19576. unsigned char *zTerm; /* End of input */
  19577. unsigned char *z; /* Output iterator */
  19578. unsigned int c;
  19579. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  19580. assert( pMem->flags&MEM_Str );
  19581. assert( pMem->enc!=desiredEnc );
  19582. assert( pMem->enc!=0 );
  19583. assert( pMem->n>=0 );
  19584. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19585. {
  19586. char zBuf[100];
  19587. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19588. fprintf(stderr, "INPUT: %s\n", zBuf);
  19589. }
  19590. #endif
  19591. /* If the translation is between UTF-16 little and big endian, then
  19592. ** all that is required is to swap the byte order. This case is handled
  19593. ** differently from the others.
  19594. */
  19595. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  19596. u8 temp;
  19597. int rc;
  19598. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19599. if( rc!=SQLITE_OK ){
  19600. assert( rc==SQLITE_NOMEM );
  19601. return SQLITE_NOMEM;
  19602. }
  19603. zIn = (u8*)pMem->z;
  19604. zTerm = &zIn[pMem->n&~1];
  19605. while( zIn<zTerm ){
  19606. temp = *zIn;
  19607. *zIn = *(zIn+1);
  19608. zIn++;
  19609. *zIn++ = temp;
  19610. }
  19611. pMem->enc = desiredEnc;
  19612. goto translate_out;
  19613. }
  19614. /* Set len to the maximum number of bytes required in the output buffer. */
  19615. if( desiredEnc==SQLITE_UTF8 ){
  19616. /* When converting from UTF-16, the maximum growth results from
  19617. ** translating a 2-byte character to a 4-byte UTF-8 character.
  19618. ** A single byte is required for the output string
  19619. ** nul-terminator.
  19620. */
  19621. pMem->n &= ~1;
  19622. len = pMem->n * 2 + 1;
  19623. }else{
  19624. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  19625. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  19626. ** character. Two bytes are required in the output buffer for the
  19627. ** nul-terminator.
  19628. */
  19629. len = pMem->n * 2 + 2;
  19630. }
  19631. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  19632. ** byte past the end.
  19633. **
  19634. ** Variable zOut is set to point at the output buffer, space obtained
  19635. ** from sqlite3_malloc().
  19636. */
  19637. zIn = (u8*)pMem->z;
  19638. zTerm = &zIn[pMem->n];
  19639. zOut = sqlite3DbMallocRaw(pMem->db, len);
  19640. if( !zOut ){
  19641. return SQLITE_NOMEM;
  19642. }
  19643. z = zOut;
  19644. if( pMem->enc==SQLITE_UTF8 ){
  19645. if( desiredEnc==SQLITE_UTF16LE ){
  19646. /* UTF-8 -> UTF-16 Little-endian */
  19647. while( zIn<zTerm ){
  19648. READ_UTF8(zIn, zTerm, c);
  19649. WRITE_UTF16LE(z, c);
  19650. }
  19651. }else{
  19652. assert( desiredEnc==SQLITE_UTF16BE );
  19653. /* UTF-8 -> UTF-16 Big-endian */
  19654. while( zIn<zTerm ){
  19655. READ_UTF8(zIn, zTerm, c);
  19656. WRITE_UTF16BE(z, c);
  19657. }
  19658. }
  19659. pMem->n = (int)(z - zOut);
  19660. *z++ = 0;
  19661. }else{
  19662. assert( desiredEnc==SQLITE_UTF8 );
  19663. if( pMem->enc==SQLITE_UTF16LE ){
  19664. /* UTF-16 Little-endian -> UTF-8 */
  19665. while( zIn<zTerm ){
  19666. READ_UTF16LE(zIn, zIn<zTerm, c);
  19667. WRITE_UTF8(z, c);
  19668. }
  19669. }else{
  19670. /* UTF-16 Big-endian -> UTF-8 */
  19671. while( zIn<zTerm ){
  19672. READ_UTF16BE(zIn, zIn<zTerm, c);
  19673. WRITE_UTF8(z, c);
  19674. }
  19675. }
  19676. pMem->n = (int)(z - zOut);
  19677. }
  19678. *z = 0;
  19679. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  19680. sqlite3VdbeMemRelease(pMem);
  19681. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  19682. pMem->enc = desiredEnc;
  19683. pMem->flags |= (MEM_Term|MEM_Dyn);
  19684. pMem->z = (char*)zOut;
  19685. pMem->zMalloc = pMem->z;
  19686. translate_out:
  19687. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19688. {
  19689. char zBuf[100];
  19690. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19691. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  19692. }
  19693. #endif
  19694. return SQLITE_OK;
  19695. }
  19696. /*
  19697. ** This routine checks for a byte-order mark at the beginning of the
  19698. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  19699. ** the encoding of the Mem adjusted. This routine does not do any
  19700. ** byte-swapping, it just sets Mem.enc appropriately.
  19701. **
  19702. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  19703. ** changed by this function.
  19704. */
  19705. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  19706. int rc = SQLITE_OK;
  19707. u8 bom = 0;
  19708. assert( pMem->n>=0 );
  19709. if( pMem->n>1 ){
  19710. u8 b1 = *(u8 *)pMem->z;
  19711. u8 b2 = *(((u8 *)pMem->z) + 1);
  19712. if( b1==0xFE && b2==0xFF ){
  19713. bom = SQLITE_UTF16BE;
  19714. }
  19715. if( b1==0xFF && b2==0xFE ){
  19716. bom = SQLITE_UTF16LE;
  19717. }
  19718. }
  19719. if( bom ){
  19720. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19721. if( rc==SQLITE_OK ){
  19722. pMem->n -= 2;
  19723. memmove(pMem->z, &pMem->z[2], pMem->n);
  19724. pMem->z[pMem->n] = '\0';
  19725. pMem->z[pMem->n+1] = '\0';
  19726. pMem->flags |= MEM_Term;
  19727. pMem->enc = bom;
  19728. }
  19729. }
  19730. return rc;
  19731. }
  19732. #endif /* SQLITE_OMIT_UTF16 */
  19733. /*
  19734. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  19735. ** return the number of unicode characters in pZ up to (but not including)
  19736. ** the first 0x00 byte. If nByte is not less than zero, return the
  19737. ** number of unicode characters in the first nByte of pZ (or up to
  19738. ** the first 0x00, whichever comes first).
  19739. */
  19740. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  19741. int r = 0;
  19742. const u8 *z = (const u8*)zIn;
  19743. const u8 *zTerm;
  19744. if( nByte>=0 ){
  19745. zTerm = &z[nByte];
  19746. }else{
  19747. zTerm = (const u8*)(-1);
  19748. }
  19749. assert( z<=zTerm );
  19750. while( *z!=0 && z<zTerm ){
  19751. SQLITE_SKIP_UTF8(z);
  19752. r++;
  19753. }
  19754. return r;
  19755. }
  19756. /* This test function is not currently used by the automated test-suite.
  19757. ** Hence it is only available in debug builds.
  19758. */
  19759. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  19760. /*
  19761. ** Translate UTF-8 to UTF-8.
  19762. **
  19763. ** This has the effect of making sure that the string is well-formed
  19764. ** UTF-8. Miscoded characters are removed.
  19765. **
  19766. ** The translation is done in-place and aborted if the output
  19767. ** overruns the input.
  19768. */
  19769. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  19770. unsigned char *zOut = zIn;
  19771. unsigned char *zStart = zIn;
  19772. u32 c;
  19773. while( zIn[0] && zOut<=zIn ){
  19774. c = sqlite3Utf8Read((const u8**)&zIn);
  19775. if( c!=0xfffd ){
  19776. WRITE_UTF8(zOut, c);
  19777. }
  19778. }
  19779. *zOut = 0;
  19780. return (int)(zOut - zStart);
  19781. }
  19782. #endif
  19783. #ifndef SQLITE_OMIT_UTF16
  19784. /*
  19785. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  19786. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  19787. ** be freed by the calling function.
  19788. **
  19789. ** NULL is returned if there is an allocation error.
  19790. */
  19791. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  19792. Mem m;
  19793. memset(&m, 0, sizeof(m));
  19794. m.db = db;
  19795. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  19796. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  19797. if( db->mallocFailed ){
  19798. sqlite3VdbeMemRelease(&m);
  19799. m.z = 0;
  19800. }
  19801. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  19802. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  19803. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  19804. assert( m.z || db->mallocFailed );
  19805. return m.z;
  19806. }
  19807. /*
  19808. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  19809. ** Return the number of bytes in the first nChar unicode characters
  19810. ** in pZ. nChar must be non-negative.
  19811. */
  19812. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  19813. int c;
  19814. unsigned char const *z = zIn;
  19815. int n = 0;
  19816. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  19817. while( n<nChar ){
  19818. READ_UTF16BE(z, 1, c);
  19819. n++;
  19820. }
  19821. }else{
  19822. while( n<nChar ){
  19823. READ_UTF16LE(z, 1, c);
  19824. n++;
  19825. }
  19826. }
  19827. return (int)(z-(unsigned char const *)zIn);
  19828. }
  19829. #if defined(SQLITE_TEST)
  19830. /*
  19831. ** This routine is called from the TCL test function "translate_selftest".
  19832. ** It checks that the primitives for serializing and deserializing
  19833. ** characters in each encoding are inverses of each other.
  19834. */
  19835. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  19836. unsigned int i, t;
  19837. unsigned char zBuf[20];
  19838. unsigned char *z;
  19839. int n;
  19840. unsigned int c;
  19841. for(i=0; i<0x00110000; i++){
  19842. z = zBuf;
  19843. WRITE_UTF8(z, i);
  19844. n = (int)(z-zBuf);
  19845. assert( n>0 && n<=4 );
  19846. z[0] = 0;
  19847. z = zBuf;
  19848. c = sqlite3Utf8Read((const u8**)&z);
  19849. t = i;
  19850. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  19851. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  19852. assert( c==t );
  19853. assert( (z-zBuf)==n );
  19854. }
  19855. for(i=0; i<0x00110000; i++){
  19856. if( i>=0xD800 && i<0xE000 ) continue;
  19857. z = zBuf;
  19858. WRITE_UTF16LE(z, i);
  19859. n = (int)(z-zBuf);
  19860. assert( n>0 && n<=4 );
  19861. z[0] = 0;
  19862. z = zBuf;
  19863. READ_UTF16LE(z, 1, c);
  19864. assert( c==i );
  19865. assert( (z-zBuf)==n );
  19866. }
  19867. for(i=0; i<0x00110000; i++){
  19868. if( i>=0xD800 && i<0xE000 ) continue;
  19869. z = zBuf;
  19870. WRITE_UTF16BE(z, i);
  19871. n = (int)(z-zBuf);
  19872. assert( n>0 && n<=4 );
  19873. z[0] = 0;
  19874. z = zBuf;
  19875. READ_UTF16BE(z, 1, c);
  19876. assert( c==i );
  19877. assert( (z-zBuf)==n );
  19878. }
  19879. }
  19880. #endif /* SQLITE_TEST */
  19881. #endif /* SQLITE_OMIT_UTF16 */
  19882. /************** End of utf.c *************************************************/
  19883. /************** Begin file util.c ********************************************/
  19884. /*
  19885. ** 2001 September 15
  19886. **
  19887. ** The author disclaims copyright to this source code. In place of
  19888. ** a legal notice, here is a blessing:
  19889. **
  19890. ** May you do good and not evil.
  19891. ** May you find forgiveness for yourself and forgive others.
  19892. ** May you share freely, never taking more than you give.
  19893. **
  19894. *************************************************************************
  19895. ** Utility functions used throughout sqlite.
  19896. **
  19897. ** This file contains functions for allocating memory, comparing
  19898. ** strings, and stuff like that.
  19899. **
  19900. */
  19901. /* #include <stdarg.h> */
  19902. #ifdef SQLITE_HAVE_ISNAN
  19903. # include <math.h>
  19904. #endif
  19905. /*
  19906. ** Routine needed to support the testcase() macro.
  19907. */
  19908. #ifdef SQLITE_COVERAGE_TEST
  19909. SQLITE_PRIVATE void sqlite3Coverage(int x){
  19910. static unsigned dummy = 0;
  19911. dummy += (unsigned)x;
  19912. }
  19913. #endif
  19914. #ifndef SQLITE_OMIT_FLOATING_POINT
  19915. /*
  19916. ** Return true if the floating point value is Not a Number (NaN).
  19917. **
  19918. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  19919. ** Otherwise, we have our own implementation that works on most systems.
  19920. */
  19921. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  19922. int rc; /* The value return */
  19923. #if !defined(SQLITE_HAVE_ISNAN)
  19924. /*
  19925. ** Systems that support the isnan() library function should probably
  19926. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  19927. ** found that many systems do not have a working isnan() function so
  19928. ** this implementation is provided as an alternative.
  19929. **
  19930. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  19931. ** On the other hand, the use of -ffast-math comes with the following
  19932. ** warning:
  19933. **
  19934. ** This option [-ffast-math] should never be turned on by any
  19935. ** -O option since it can result in incorrect output for programs
  19936. ** which depend on an exact implementation of IEEE or ISO
  19937. ** rules/specifications for math functions.
  19938. **
  19939. ** Under MSVC, this NaN test may fail if compiled with a floating-
  19940. ** point precision mode other than /fp:precise. From the MSDN
  19941. ** documentation:
  19942. **
  19943. ** The compiler [with /fp:precise] will properly handle comparisons
  19944. ** involving NaN. For example, x != x evaluates to true if x is NaN
  19945. ** ...
  19946. */
  19947. #ifdef __FAST_MATH__
  19948. # error SQLite will not work correctly with the -ffast-math option of GCC.
  19949. #endif
  19950. volatile double y = x;
  19951. volatile double z = y;
  19952. rc = (y!=z);
  19953. #else /* if defined(SQLITE_HAVE_ISNAN) */
  19954. rc = isnan(x);
  19955. #endif /* SQLITE_HAVE_ISNAN */
  19956. testcase( rc );
  19957. return rc;
  19958. }
  19959. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19960. /*
  19961. ** Compute a string length that is limited to what can be stored in
  19962. ** lower 30 bits of a 32-bit signed integer.
  19963. **
  19964. ** The value returned will never be negative. Nor will it ever be greater
  19965. ** than the actual length of the string. For very long strings (greater
  19966. ** than 1GiB) the value returned might be less than the true string length.
  19967. */
  19968. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  19969. const char *z2 = z;
  19970. if( z==0 ) return 0;
  19971. while( *z2 ){ z2++; }
  19972. return 0x3fffffff & (int)(z2 - z);
  19973. }
  19974. /*
  19975. ** Set the most recent error code and error string for the sqlite
  19976. ** handle "db". The error code is set to "err_code".
  19977. **
  19978. ** If it is not NULL, string zFormat specifies the format of the
  19979. ** error string in the style of the printf functions: The following
  19980. ** format characters are allowed:
  19981. **
  19982. ** %s Insert a string
  19983. ** %z A string that should be freed after use
  19984. ** %d Insert an integer
  19985. ** %T Insert a token
  19986. ** %S Insert the first element of a SrcList
  19987. **
  19988. ** zFormat and any string tokens that follow it are assumed to be
  19989. ** encoded in UTF-8.
  19990. **
  19991. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  19992. ** should be called with err_code set to SQLITE_OK and zFormat set
  19993. ** to NULL.
  19994. */
  19995. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  19996. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  19997. db->errCode = err_code;
  19998. if( zFormat ){
  19999. char *z;
  20000. va_list ap;
  20001. va_start(ap, zFormat);
  20002. z = sqlite3VMPrintf(db, zFormat, ap);
  20003. va_end(ap);
  20004. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20005. }else{
  20006. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20007. }
  20008. }
  20009. }
  20010. /*
  20011. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20012. ** The following formatting characters are allowed:
  20013. **
  20014. ** %s Insert a string
  20015. ** %z A string that should be freed after use
  20016. ** %d Insert an integer
  20017. ** %T Insert a token
  20018. ** %S Insert the first element of a SrcList
  20019. **
  20020. ** This function should be used to report any error that occurs whilst
  20021. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20022. ** last thing the sqlite3_prepare() function does is copy the error
  20023. ** stored by this function into the database handle using sqlite3Error().
  20024. ** Function sqlite3Error() should be used during statement execution
  20025. ** (sqlite3_step() etc.).
  20026. */
  20027. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20028. char *zMsg;
  20029. va_list ap;
  20030. sqlite3 *db = pParse->db;
  20031. va_start(ap, zFormat);
  20032. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20033. va_end(ap);
  20034. if( db->suppressErr ){
  20035. sqlite3DbFree(db, zMsg);
  20036. }else{
  20037. pParse->nErr++;
  20038. sqlite3DbFree(db, pParse->zErrMsg);
  20039. pParse->zErrMsg = zMsg;
  20040. pParse->rc = SQLITE_ERROR;
  20041. }
  20042. }
  20043. /*
  20044. ** Convert an SQL-style quoted string into a normal string by removing
  20045. ** the quote characters. The conversion is done in-place. If the
  20046. ** input does not begin with a quote character, then this routine
  20047. ** is a no-op.
  20048. **
  20049. ** The input string must be zero-terminated. A new zero-terminator
  20050. ** is added to the dequoted string.
  20051. **
  20052. ** The return value is -1 if no dequoting occurs or the length of the
  20053. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20054. ** occur.
  20055. **
  20056. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20057. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20058. ** "a-b-c".
  20059. */
  20060. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20061. char quote;
  20062. int i, j;
  20063. if( z==0 ) return -1;
  20064. quote = z[0];
  20065. switch( quote ){
  20066. case '\'': break;
  20067. case '"': break;
  20068. case '`': break; /* For MySQL compatibility */
  20069. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20070. default: return -1;
  20071. }
  20072. for(i=1, j=0;; i++){
  20073. assert( z[i] );
  20074. if( z[i]==quote ){
  20075. if( z[i+1]==quote ){
  20076. z[j++] = quote;
  20077. i++;
  20078. }else{
  20079. break;
  20080. }
  20081. }else{
  20082. z[j++] = z[i];
  20083. }
  20084. }
  20085. z[j] = 0;
  20086. return j;
  20087. }
  20088. /* Convenient short-hand */
  20089. #define UpperToLower sqlite3UpperToLower
  20090. /*
  20091. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20092. ** there is no consistency, we will define our own.
  20093. **
  20094. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20095. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20096. ** the contents of two buffers containing UTF-8 strings in a
  20097. ** case-independent fashion, using the same definition of "case
  20098. ** independence" that SQLite uses internally when comparing identifiers.
  20099. */
  20100. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20101. register unsigned char *a, *b;
  20102. a = (unsigned char *)zLeft;
  20103. b = (unsigned char *)zRight;
  20104. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20105. return UpperToLower[*a] - UpperToLower[*b];
  20106. }
  20107. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20108. register unsigned char *a, *b;
  20109. a = (unsigned char *)zLeft;
  20110. b = (unsigned char *)zRight;
  20111. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20112. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20113. }
  20114. /*
  20115. ** The string z[] is an text representation of a real number.
  20116. ** Convert this string to a double and write it into *pResult.
  20117. **
  20118. ** The string z[] is length bytes in length (bytes, not characters) and
  20119. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20120. **
  20121. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20122. ** if the string is empty or contains extraneous text. Valid numbers
  20123. ** are in one of these formats:
  20124. **
  20125. ** [+-]digits[E[+-]digits]
  20126. ** [+-]digits.[digits][E[+-]digits]
  20127. ** [+-].digits[E[+-]digits]
  20128. **
  20129. ** Leading and trailing whitespace is ignored for the purpose of determining
  20130. ** validity.
  20131. **
  20132. ** If some prefix of the input string is a valid number, this routine
  20133. ** returns FALSE but it still converts the prefix and writes the result
  20134. ** into *pResult.
  20135. */
  20136. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20137. #ifndef SQLITE_OMIT_FLOATING_POINT
  20138. int incr;
  20139. const char *zEnd = z + length;
  20140. /* sign * significand * (10 ^ (esign * exponent)) */
  20141. int sign = 1; /* sign of significand */
  20142. i64 s = 0; /* significand */
  20143. int d = 0; /* adjust exponent for shifting decimal point */
  20144. int esign = 1; /* sign of exponent */
  20145. int e = 0; /* exponent */
  20146. int eValid = 1; /* True exponent is either not used or is well-formed */
  20147. double result;
  20148. int nDigits = 0;
  20149. int nonNum = 0;
  20150. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20151. *pResult = 0.0; /* Default return value, in case of an error */
  20152. if( enc==SQLITE_UTF8 ){
  20153. incr = 1;
  20154. }else{
  20155. int i;
  20156. incr = 2;
  20157. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20158. for(i=3-enc; i<length && z[i]==0; i+=2){}
  20159. nonNum = i<length;
  20160. zEnd = z+i+enc-3;
  20161. z += (enc&1);
  20162. }
  20163. /* skip leading spaces */
  20164. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20165. if( z>=zEnd ) return 0;
  20166. /* get sign of significand */
  20167. if( *z=='-' ){
  20168. sign = -1;
  20169. z+=incr;
  20170. }else if( *z=='+' ){
  20171. z+=incr;
  20172. }
  20173. /* skip leading zeroes */
  20174. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20175. /* copy max significant digits to significand */
  20176. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20177. s = s*10 + (*z - '0');
  20178. z+=incr, nDigits++;
  20179. }
  20180. /* skip non-significant significand digits
  20181. ** (increase exponent by d to shift decimal left) */
  20182. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20183. if( z>=zEnd ) goto do_atof_calc;
  20184. /* if decimal point is present */
  20185. if( *z=='.' ){
  20186. z+=incr;
  20187. /* copy digits from after decimal to significand
  20188. ** (decrease exponent by d to shift decimal right) */
  20189. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20190. s = s*10 + (*z - '0');
  20191. z+=incr, nDigits++, d--;
  20192. }
  20193. /* skip non-significant digits */
  20194. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20195. }
  20196. if( z>=zEnd ) goto do_atof_calc;
  20197. /* if exponent is present */
  20198. if( *z=='e' || *z=='E' ){
  20199. z+=incr;
  20200. eValid = 0;
  20201. if( z>=zEnd ) goto do_atof_calc;
  20202. /* get sign of exponent */
  20203. if( *z=='-' ){
  20204. esign = -1;
  20205. z+=incr;
  20206. }else if( *z=='+' ){
  20207. z+=incr;
  20208. }
  20209. /* copy digits to exponent */
  20210. while( z<zEnd && sqlite3Isdigit(*z) ){
  20211. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20212. z+=incr;
  20213. eValid = 1;
  20214. }
  20215. }
  20216. /* skip trailing spaces */
  20217. if( nDigits && eValid ){
  20218. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20219. }
  20220. do_atof_calc:
  20221. /* adjust exponent by d, and update sign */
  20222. e = (e*esign) + d;
  20223. if( e<0 ) {
  20224. esign = -1;
  20225. e *= -1;
  20226. } else {
  20227. esign = 1;
  20228. }
  20229. /* if 0 significand */
  20230. if( !s ) {
  20231. /* In the IEEE 754 standard, zero is signed.
  20232. ** Add the sign if we've seen at least one digit */
  20233. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20234. } else {
  20235. /* attempt to reduce exponent */
  20236. if( esign>0 ){
  20237. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20238. }else{
  20239. while( !(s%10) && e>0 ) e--,s/=10;
  20240. }
  20241. /* adjust the sign of significand */
  20242. s = sign<0 ? -s : s;
  20243. /* if exponent, scale significand as appropriate
  20244. ** and store in result. */
  20245. if( e ){
  20246. LONGDOUBLE_TYPE scale = 1.0;
  20247. /* attempt to handle extremely small/large numbers better */
  20248. if( e>307 && e<342 ){
  20249. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20250. if( esign<0 ){
  20251. result = s / scale;
  20252. result /= 1.0e+308;
  20253. }else{
  20254. result = s * scale;
  20255. result *= 1.0e+308;
  20256. }
  20257. }else if( e>=342 ){
  20258. if( esign<0 ){
  20259. result = 0.0*s;
  20260. }else{
  20261. result = 1e308*1e308*s; /* Infinity */
  20262. }
  20263. }else{
  20264. /* 1.0e+22 is the largest power of 10 than can be
  20265. ** represented exactly. */
  20266. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20267. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20268. if( esign<0 ){
  20269. result = s / scale;
  20270. }else{
  20271. result = s * scale;
  20272. }
  20273. }
  20274. } else {
  20275. result = (double)s;
  20276. }
  20277. }
  20278. /* store the result */
  20279. *pResult = result;
  20280. /* return true if number and no extra non-whitespace chracters after */
  20281. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  20282. #else
  20283. return !sqlite3Atoi64(z, pResult, length, enc);
  20284. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20285. }
  20286. /*
  20287. ** Compare the 19-character string zNum against the text representation
  20288. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20289. ** if zNum is less than, equal to, or greater than the string.
  20290. ** Note that zNum must contain exactly 19 characters.
  20291. **
  20292. ** Unlike memcmp() this routine is guaranteed to return the difference
  20293. ** in the values of the last digit if the only difference is in the
  20294. ** last digit. So, for example,
  20295. **
  20296. ** compare2pow63("9223372036854775800", 1)
  20297. **
  20298. ** will return -8.
  20299. */
  20300. static int compare2pow63(const char *zNum, int incr){
  20301. int c = 0;
  20302. int i;
  20303. /* 012345678901234567 */
  20304. const char *pow63 = "922337203685477580";
  20305. for(i=0; c==0 && i<18; i++){
  20306. c = (zNum[i*incr]-pow63[i])*10;
  20307. }
  20308. if( c==0 ){
  20309. c = zNum[18*incr] - '8';
  20310. testcase( c==(-1) );
  20311. testcase( c==0 );
  20312. testcase( c==(+1) );
  20313. }
  20314. return c;
  20315. }
  20316. /*
  20317. ** Convert zNum to a 64-bit signed integer.
  20318. **
  20319. ** If the zNum value is representable as a 64-bit twos-complement
  20320. ** integer, then write that value into *pNum and return 0.
  20321. **
  20322. ** If zNum is exactly 9223372036854665808, return 2. This special
  20323. ** case is broken out because while 9223372036854665808 cannot be a
  20324. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20325. **
  20326. ** If zNum is too big for a 64-bit integer and is not
  20327. ** 9223372036854665808 or if zNum contains any non-numeric text,
  20328. ** then return 1.
  20329. **
  20330. ** length is the number of bytes in the string (bytes, not characters).
  20331. ** The string is not necessarily zero-terminated. The encoding is
  20332. ** given by enc.
  20333. */
  20334. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20335. int incr;
  20336. u64 u = 0;
  20337. int neg = 0; /* assume positive */
  20338. int i;
  20339. int c = 0;
  20340. int nonNum = 0;
  20341. const char *zStart;
  20342. const char *zEnd = zNum + length;
  20343. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20344. if( enc==SQLITE_UTF8 ){
  20345. incr = 1;
  20346. }else{
  20347. incr = 2;
  20348. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20349. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  20350. nonNum = i<length;
  20351. zEnd = zNum+i+enc-3;
  20352. zNum += (enc&1);
  20353. }
  20354. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20355. if( zNum<zEnd ){
  20356. if( *zNum=='-' ){
  20357. neg = 1;
  20358. zNum+=incr;
  20359. }else if( *zNum=='+' ){
  20360. zNum+=incr;
  20361. }
  20362. }
  20363. zStart = zNum;
  20364. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20365. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20366. u = u*10 + c - '0';
  20367. }
  20368. if( u>LARGEST_INT64 ){
  20369. *pNum = SMALLEST_INT64;
  20370. }else if( neg ){
  20371. *pNum = -(i64)u;
  20372. }else{
  20373. *pNum = (i64)u;
  20374. }
  20375. testcase( i==18 );
  20376. testcase( i==19 );
  20377. testcase( i==20 );
  20378. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  20379. /* zNum is empty or contains non-numeric text or is longer
  20380. ** than 19 digits (thus guaranteeing that it is too large) */
  20381. return 1;
  20382. }else if( i<19*incr ){
  20383. /* Less than 19 digits, so we know that it fits in 64 bits */
  20384. assert( u<=LARGEST_INT64 );
  20385. return 0;
  20386. }else{
  20387. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20388. c = compare2pow63(zNum, incr);
  20389. if( c<0 ){
  20390. /* zNum is less than 9223372036854775808 so it fits */
  20391. assert( u<=LARGEST_INT64 );
  20392. return 0;
  20393. }else if( c>0 ){
  20394. /* zNum is greater than 9223372036854775808 so it overflows */
  20395. return 1;
  20396. }else{
  20397. /* zNum is exactly 9223372036854775808. Fits if negative. The
  20398. ** special case 2 overflow if positive */
  20399. assert( u-1==LARGEST_INT64 );
  20400. assert( (*pNum)==SMALLEST_INT64 );
  20401. return neg ? 0 : 2;
  20402. }
  20403. }
  20404. }
  20405. /*
  20406. ** If zNum represents an integer that will fit in 32-bits, then set
  20407. ** *pValue to that integer and return true. Otherwise return false.
  20408. **
  20409. ** Any non-numeric characters that following zNum are ignored.
  20410. ** This is different from sqlite3Atoi64() which requires the
  20411. ** input number to be zero-terminated.
  20412. */
  20413. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  20414. sqlite_int64 v = 0;
  20415. int i, c;
  20416. int neg = 0;
  20417. if( zNum[0]=='-' ){
  20418. neg = 1;
  20419. zNum++;
  20420. }else if( zNum[0]=='+' ){
  20421. zNum++;
  20422. }
  20423. while( zNum[0]=='0' ) zNum++;
  20424. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  20425. v = v*10 + c;
  20426. }
  20427. /* The longest decimal representation of a 32 bit integer is 10 digits:
  20428. **
  20429. ** 1234567890
  20430. ** 2^31 -> 2147483648
  20431. */
  20432. testcase( i==10 );
  20433. if( i>10 ){
  20434. return 0;
  20435. }
  20436. testcase( v-neg==2147483647 );
  20437. if( v-neg>2147483647 ){
  20438. return 0;
  20439. }
  20440. if( neg ){
  20441. v = -v;
  20442. }
  20443. *pValue = (int)v;
  20444. return 1;
  20445. }
  20446. /*
  20447. ** Return a 32-bit integer value extracted from a string. If the
  20448. ** string is not an integer, just return 0.
  20449. */
  20450. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  20451. int x = 0;
  20452. if( z ) sqlite3GetInt32(z, &x);
  20453. return x;
  20454. }
  20455. /*
  20456. ** The variable-length integer encoding is as follows:
  20457. **
  20458. ** KEY:
  20459. ** A = 0xxxxxxx 7 bits of data and one flag bit
  20460. ** B = 1xxxxxxx 7 bits of data and one flag bit
  20461. ** C = xxxxxxxx 8 bits of data
  20462. **
  20463. ** 7 bits - A
  20464. ** 14 bits - BA
  20465. ** 21 bits - BBA
  20466. ** 28 bits - BBBA
  20467. ** 35 bits - BBBBA
  20468. ** 42 bits - BBBBBA
  20469. ** 49 bits - BBBBBBA
  20470. ** 56 bits - BBBBBBBA
  20471. ** 64 bits - BBBBBBBBC
  20472. */
  20473. /*
  20474. ** Write a 64-bit variable-length integer to memory starting at p[0].
  20475. ** The length of data write will be between 1 and 9 bytes. The number
  20476. ** of bytes written is returned.
  20477. **
  20478. ** A variable-length integer consists of the lower 7 bits of each byte
  20479. ** for all bytes that have the 8th bit set and one byte with the 8th
  20480. ** bit clear. Except, if we get to the 9th byte, it stores the full
  20481. ** 8 bits and is the last byte.
  20482. */
  20483. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  20484. int i, j, n;
  20485. u8 buf[10];
  20486. if( v & (((u64)0xff000000)<<32) ){
  20487. p[8] = (u8)v;
  20488. v >>= 8;
  20489. for(i=7; i>=0; i--){
  20490. p[i] = (u8)((v & 0x7f) | 0x80);
  20491. v >>= 7;
  20492. }
  20493. return 9;
  20494. }
  20495. n = 0;
  20496. do{
  20497. buf[n++] = (u8)((v & 0x7f) | 0x80);
  20498. v >>= 7;
  20499. }while( v!=0 );
  20500. buf[0] &= 0x7f;
  20501. assert( n<=9 );
  20502. for(i=0, j=n-1; j>=0; j--, i++){
  20503. p[i] = buf[j];
  20504. }
  20505. return n;
  20506. }
  20507. /*
  20508. ** This routine is a faster version of sqlite3PutVarint() that only
  20509. ** works for 32-bit positive integers and which is optimized for
  20510. ** the common case of small integers. A MACRO version, putVarint32,
  20511. ** is provided which inlines the single-byte case. All code should use
  20512. ** the MACRO version as this function assumes the single-byte case has
  20513. ** already been handled.
  20514. */
  20515. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  20516. #ifndef putVarint32
  20517. if( (v & ~0x7f)==0 ){
  20518. p[0] = v;
  20519. return 1;
  20520. }
  20521. #endif
  20522. if( (v & ~0x3fff)==0 ){
  20523. p[0] = (u8)((v>>7) | 0x80);
  20524. p[1] = (u8)(v & 0x7f);
  20525. return 2;
  20526. }
  20527. return sqlite3PutVarint(p, v);
  20528. }
  20529. /*
  20530. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  20531. ** are defined here rather than simply putting the constant expressions
  20532. ** inline in order to work around bugs in the RVT compiler.
  20533. **
  20534. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  20535. **
  20536. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  20537. */
  20538. #define SLOT_2_0 0x001fc07f
  20539. #define SLOT_4_2_0 0xf01fc07f
  20540. /*
  20541. ** Read a 64-bit variable-length integer from memory starting at p[0].
  20542. ** Return the number of bytes read. The value is stored in *v.
  20543. */
  20544. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  20545. u32 a,b,s;
  20546. a = *p;
  20547. /* a: p0 (unmasked) */
  20548. if (!(a&0x80))
  20549. {
  20550. *v = a;
  20551. return 1;
  20552. }
  20553. p++;
  20554. b = *p;
  20555. /* b: p1 (unmasked) */
  20556. if (!(b&0x80))
  20557. {
  20558. a &= 0x7f;
  20559. a = a<<7;
  20560. a |= b;
  20561. *v = a;
  20562. return 2;
  20563. }
  20564. /* Verify that constants are precomputed correctly */
  20565. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  20566. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  20567. p++;
  20568. a = a<<14;
  20569. a |= *p;
  20570. /* a: p0<<14 | p2 (unmasked) */
  20571. if (!(a&0x80))
  20572. {
  20573. a &= SLOT_2_0;
  20574. b &= 0x7f;
  20575. b = b<<7;
  20576. a |= b;
  20577. *v = a;
  20578. return 3;
  20579. }
  20580. /* CSE1 from below */
  20581. a &= SLOT_2_0;
  20582. p++;
  20583. b = b<<14;
  20584. b |= *p;
  20585. /* b: p1<<14 | p3 (unmasked) */
  20586. if (!(b&0x80))
  20587. {
  20588. b &= SLOT_2_0;
  20589. /* moved CSE1 up */
  20590. /* a &= (0x7f<<14)|(0x7f); */
  20591. a = a<<7;
  20592. a |= b;
  20593. *v = a;
  20594. return 4;
  20595. }
  20596. /* a: p0<<14 | p2 (masked) */
  20597. /* b: p1<<14 | p3 (unmasked) */
  20598. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20599. /* moved CSE1 up */
  20600. /* a &= (0x7f<<14)|(0x7f); */
  20601. b &= SLOT_2_0;
  20602. s = a;
  20603. /* s: p0<<14 | p2 (masked) */
  20604. p++;
  20605. a = a<<14;
  20606. a |= *p;
  20607. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20608. if (!(a&0x80))
  20609. {
  20610. /* we can skip these cause they were (effectively) done above in calc'ing s */
  20611. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20612. /* b &= (0x7f<<14)|(0x7f); */
  20613. b = b<<7;
  20614. a |= b;
  20615. s = s>>18;
  20616. *v = ((u64)s)<<32 | a;
  20617. return 5;
  20618. }
  20619. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20620. s = s<<7;
  20621. s |= b;
  20622. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20623. p++;
  20624. b = b<<14;
  20625. b |= *p;
  20626. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  20627. if (!(b&0x80))
  20628. {
  20629. /* we can skip this cause it was (effectively) done above in calc'ing s */
  20630. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20631. a &= SLOT_2_0;
  20632. a = a<<7;
  20633. a |= b;
  20634. s = s>>18;
  20635. *v = ((u64)s)<<32 | a;
  20636. return 6;
  20637. }
  20638. p++;
  20639. a = a<<14;
  20640. a |= *p;
  20641. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  20642. if (!(a&0x80))
  20643. {
  20644. a &= SLOT_4_2_0;
  20645. b &= SLOT_2_0;
  20646. b = b<<7;
  20647. a |= b;
  20648. s = s>>11;
  20649. *v = ((u64)s)<<32 | a;
  20650. return 7;
  20651. }
  20652. /* CSE2 from below */
  20653. a &= SLOT_2_0;
  20654. p++;
  20655. b = b<<14;
  20656. b |= *p;
  20657. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  20658. if (!(b&0x80))
  20659. {
  20660. b &= SLOT_4_2_0;
  20661. /* moved CSE2 up */
  20662. /* a &= (0x7f<<14)|(0x7f); */
  20663. a = a<<7;
  20664. a |= b;
  20665. s = s>>4;
  20666. *v = ((u64)s)<<32 | a;
  20667. return 8;
  20668. }
  20669. p++;
  20670. a = a<<15;
  20671. a |= *p;
  20672. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  20673. /* moved CSE2 up */
  20674. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  20675. b &= SLOT_2_0;
  20676. b = b<<8;
  20677. a |= b;
  20678. s = s<<4;
  20679. b = p[-4];
  20680. b &= 0x7f;
  20681. b = b>>3;
  20682. s |= b;
  20683. *v = ((u64)s)<<32 | a;
  20684. return 9;
  20685. }
  20686. /*
  20687. ** Read a 32-bit variable-length integer from memory starting at p[0].
  20688. ** Return the number of bytes read. The value is stored in *v.
  20689. **
  20690. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  20691. ** integer, then set *v to 0xffffffff.
  20692. **
  20693. ** A MACRO version, getVarint32, is provided which inlines the
  20694. ** single-byte case. All code should use the MACRO version as
  20695. ** this function assumes the single-byte case has already been handled.
  20696. */
  20697. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  20698. u32 a,b;
  20699. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  20700. ** by the getVarin32() macro */
  20701. a = *p;
  20702. /* a: p0 (unmasked) */
  20703. #ifndef getVarint32
  20704. if (!(a&0x80))
  20705. {
  20706. /* Values between 0 and 127 */
  20707. *v = a;
  20708. return 1;
  20709. }
  20710. #endif
  20711. /* The 2-byte case */
  20712. p++;
  20713. b = *p;
  20714. /* b: p1 (unmasked) */
  20715. if (!(b&0x80))
  20716. {
  20717. /* Values between 128 and 16383 */
  20718. a &= 0x7f;
  20719. a = a<<7;
  20720. *v = a | b;
  20721. return 2;
  20722. }
  20723. /* The 3-byte case */
  20724. p++;
  20725. a = a<<14;
  20726. a |= *p;
  20727. /* a: p0<<14 | p2 (unmasked) */
  20728. if (!(a&0x80))
  20729. {
  20730. /* Values between 16384 and 2097151 */
  20731. a &= (0x7f<<14)|(0x7f);
  20732. b &= 0x7f;
  20733. b = b<<7;
  20734. *v = a | b;
  20735. return 3;
  20736. }
  20737. /* A 32-bit varint is used to store size information in btrees.
  20738. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  20739. ** A 3-byte varint is sufficient, for example, to record the size
  20740. ** of a 1048569-byte BLOB or string.
  20741. **
  20742. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  20743. ** rare larger cases can be handled by the slower 64-bit varint
  20744. ** routine.
  20745. */
  20746. #if 1
  20747. {
  20748. u64 v64;
  20749. u8 n;
  20750. p -= 2;
  20751. n = sqlite3GetVarint(p, &v64);
  20752. assert( n>3 && n<=9 );
  20753. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  20754. *v = 0xffffffff;
  20755. }else{
  20756. *v = (u32)v64;
  20757. }
  20758. return n;
  20759. }
  20760. #else
  20761. /* For following code (kept for historical record only) shows an
  20762. ** unrolling for the 3- and 4-byte varint cases. This code is
  20763. ** slightly faster, but it is also larger and much harder to test.
  20764. */
  20765. p++;
  20766. b = b<<14;
  20767. b |= *p;
  20768. /* b: p1<<14 | p3 (unmasked) */
  20769. if (!(b&0x80))
  20770. {
  20771. /* Values between 2097152 and 268435455 */
  20772. b &= (0x7f<<14)|(0x7f);
  20773. a &= (0x7f<<14)|(0x7f);
  20774. a = a<<7;
  20775. *v = a | b;
  20776. return 4;
  20777. }
  20778. p++;
  20779. a = a<<14;
  20780. a |= *p;
  20781. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20782. if (!(a&0x80))
  20783. {
  20784. /* Values between 268435456 and 34359738367 */
  20785. a &= SLOT_4_2_0;
  20786. b &= SLOT_4_2_0;
  20787. b = b<<7;
  20788. *v = a | b;
  20789. return 5;
  20790. }
  20791. /* We can only reach this point when reading a corrupt database
  20792. ** file. In that case we are not in any hurry. Use the (relatively
  20793. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  20794. ** value. */
  20795. {
  20796. u64 v64;
  20797. u8 n;
  20798. p -= 4;
  20799. n = sqlite3GetVarint(p, &v64);
  20800. assert( n>5 && n<=9 );
  20801. *v = (u32)v64;
  20802. return n;
  20803. }
  20804. #endif
  20805. }
  20806. /*
  20807. ** Return the number of bytes that will be needed to store the given
  20808. ** 64-bit integer.
  20809. */
  20810. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  20811. int i = 0;
  20812. do{
  20813. i++;
  20814. v >>= 7;
  20815. }while( v!=0 && ALWAYS(i<9) );
  20816. return i;
  20817. }
  20818. /*
  20819. ** Read or write a four-byte big-endian integer value.
  20820. */
  20821. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  20822. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  20823. }
  20824. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  20825. p[0] = (u8)(v>>24);
  20826. p[1] = (u8)(v>>16);
  20827. p[2] = (u8)(v>>8);
  20828. p[3] = (u8)v;
  20829. }
  20830. /*
  20831. ** Translate a single byte of Hex into an integer.
  20832. ** This routine only works if h really is a valid hexadecimal
  20833. ** character: 0..9a..fA..F
  20834. */
  20835. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  20836. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  20837. #ifdef SQLITE_ASCII
  20838. h += 9*(1&(h>>6));
  20839. #endif
  20840. #ifdef SQLITE_EBCDIC
  20841. h += 9*(1&~(h>>4));
  20842. #endif
  20843. return (u8)(h & 0xf);
  20844. }
  20845. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  20846. /*
  20847. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  20848. ** value. Return a pointer to its binary value. Space to hold the
  20849. ** binary value has been obtained from malloc and must be freed by
  20850. ** the calling routine.
  20851. */
  20852. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  20853. char *zBlob;
  20854. int i;
  20855. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  20856. n--;
  20857. if( zBlob ){
  20858. for(i=0; i<n; i+=2){
  20859. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  20860. }
  20861. zBlob[i/2] = 0;
  20862. }
  20863. return zBlob;
  20864. }
  20865. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  20866. /*
  20867. ** Log an error that is an API call on a connection pointer that should
  20868. ** not have been used. The "type" of connection pointer is given as the
  20869. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  20870. */
  20871. static void logBadConnection(const char *zType){
  20872. sqlite3_log(SQLITE_MISUSE,
  20873. "API call with %s database connection pointer",
  20874. zType
  20875. );
  20876. }
  20877. /*
  20878. ** Check to make sure we have a valid db pointer. This test is not
  20879. ** foolproof but it does provide some measure of protection against
  20880. ** misuse of the interface such as passing in db pointers that are
  20881. ** NULL or which have been previously closed. If this routine returns
  20882. ** 1 it means that the db pointer is valid and 0 if it should not be
  20883. ** dereferenced for any reason. The calling function should invoke
  20884. ** SQLITE_MISUSE immediately.
  20885. **
  20886. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  20887. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  20888. ** open properly and is not fit for general use but which can be
  20889. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  20890. */
  20891. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  20892. u32 magic;
  20893. if( db==0 ){
  20894. logBadConnection("NULL");
  20895. return 0;
  20896. }
  20897. magic = db->magic;
  20898. if( magic!=SQLITE_MAGIC_OPEN ){
  20899. if( sqlite3SafetyCheckSickOrOk(db) ){
  20900. testcase( sqlite3GlobalConfig.xLog!=0 );
  20901. logBadConnection("unopened");
  20902. }
  20903. return 0;
  20904. }else{
  20905. return 1;
  20906. }
  20907. }
  20908. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  20909. u32 magic;
  20910. magic = db->magic;
  20911. if( magic!=SQLITE_MAGIC_SICK &&
  20912. magic!=SQLITE_MAGIC_OPEN &&
  20913. magic!=SQLITE_MAGIC_BUSY ){
  20914. testcase( sqlite3GlobalConfig.xLog!=0 );
  20915. logBadConnection("invalid");
  20916. return 0;
  20917. }else{
  20918. return 1;
  20919. }
  20920. }
  20921. /*
  20922. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  20923. ** the other 64-bit signed integer at *pA and store the result in *pA.
  20924. ** Return 0 on success. Or if the operation would have resulted in an
  20925. ** overflow, leave *pA unchanged and return 1.
  20926. */
  20927. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  20928. i64 iA = *pA;
  20929. testcase( iA==0 ); testcase( iA==1 );
  20930. testcase( iB==-1 ); testcase( iB==0 );
  20931. if( iB>=0 ){
  20932. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  20933. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  20934. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  20935. *pA += iB;
  20936. }else{
  20937. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  20938. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  20939. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  20940. *pA += iB;
  20941. }
  20942. return 0;
  20943. }
  20944. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  20945. testcase( iB==SMALLEST_INT64+1 );
  20946. if( iB==SMALLEST_INT64 ){
  20947. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  20948. if( (*pA)>=0 ) return 1;
  20949. *pA -= iB;
  20950. return 0;
  20951. }else{
  20952. return sqlite3AddInt64(pA, -iB);
  20953. }
  20954. }
  20955. #define TWOPOWER32 (((i64)1)<<32)
  20956. #define TWOPOWER31 (((i64)1)<<31)
  20957. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  20958. i64 iA = *pA;
  20959. i64 iA1, iA0, iB1, iB0, r;
  20960. iA1 = iA/TWOPOWER32;
  20961. iA0 = iA % TWOPOWER32;
  20962. iB1 = iB/TWOPOWER32;
  20963. iB0 = iB % TWOPOWER32;
  20964. if( iA1*iB1 != 0 ) return 1;
  20965. assert( iA1*iB0==0 || iA0*iB1==0 );
  20966. r = iA1*iB0 + iA0*iB1;
  20967. testcase( r==(-TWOPOWER31)-1 );
  20968. testcase( r==(-TWOPOWER31) );
  20969. testcase( r==TWOPOWER31 );
  20970. testcase( r==TWOPOWER31-1 );
  20971. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  20972. r *= TWOPOWER32;
  20973. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  20974. *pA = r;
  20975. return 0;
  20976. }
  20977. /*
  20978. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  20979. ** if the integer has a value of -2147483648, return +2147483647
  20980. */
  20981. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  20982. if( x>=0 ) return x;
  20983. if( x==(int)0x80000000 ) return 0x7fffffff;
  20984. return -x;
  20985. }
  20986. #ifdef SQLITE_ENABLE_8_3_NAMES
  20987. /*
  20988. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  20989. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  20990. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  20991. ** three characters, then shorten the suffix on z[] to be the last three
  20992. ** characters of the original suffix.
  20993. **
  20994. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  20995. ** do the suffix shortening regardless of URI parameter.
  20996. **
  20997. ** Examples:
  20998. **
  20999. ** test.db-journal => test.nal
  21000. ** test.db-wal => test.wal
  21001. ** test.db-shm => test.shm
  21002. ** test.db-mj7f3319fa => test.9fa
  21003. */
  21004. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21005. #if SQLITE_ENABLE_8_3_NAMES<2
  21006. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21007. #endif
  21008. {
  21009. int i, sz;
  21010. sz = sqlite3Strlen30(z);
  21011. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21012. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21013. }
  21014. }
  21015. #endif
  21016. /*
  21017. ** Find (an approximate) sum of two LogEst values. This computation is
  21018. ** not a simple "+" operator because LogEst is stored as a logarithmic
  21019. ** value.
  21020. **
  21021. */
  21022. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  21023. static const unsigned char x[] = {
  21024. 10, 10, /* 0,1 */
  21025. 9, 9, /* 2,3 */
  21026. 8, 8, /* 4,5 */
  21027. 7, 7, 7, /* 6,7,8 */
  21028. 6, 6, 6, /* 9,10,11 */
  21029. 5, 5, 5, /* 12-14 */
  21030. 4, 4, 4, 4, /* 15-18 */
  21031. 3, 3, 3, 3, 3, 3, /* 19-24 */
  21032. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  21033. };
  21034. if( a>=b ){
  21035. if( a>b+49 ) return a;
  21036. if( a>b+31 ) return a+1;
  21037. return a+x[a-b];
  21038. }else{
  21039. if( b>a+49 ) return b;
  21040. if( b>a+31 ) return b+1;
  21041. return b+x[b-a];
  21042. }
  21043. }
  21044. /*
  21045. ** Convert an integer into a LogEst. In other words, compute a
  21046. ** good approximatation for 10*log2(x).
  21047. */
  21048. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  21049. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  21050. LogEst y = 40;
  21051. if( x<8 ){
  21052. if( x<2 ) return 0;
  21053. while( x<8 ){ y -= 10; x <<= 1; }
  21054. }else{
  21055. while( x>255 ){ y += 40; x >>= 4; }
  21056. while( x>15 ){ y += 10; x >>= 1; }
  21057. }
  21058. return a[x&7] + y - 10;
  21059. }
  21060. #ifndef SQLITE_OMIT_VIRTUALTABLE
  21061. /*
  21062. ** Convert a double into a LogEst
  21063. ** In other words, compute an approximation for 10*log2(x).
  21064. */
  21065. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  21066. u64 a;
  21067. LogEst e;
  21068. assert( sizeof(x)==8 && sizeof(a)==8 );
  21069. if( x<=1 ) return 0;
  21070. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  21071. memcpy(&a, &x, 8);
  21072. e = (a>>52) - 1022;
  21073. return e*10;
  21074. }
  21075. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  21076. /*
  21077. ** Convert a LogEst into an integer.
  21078. */
  21079. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  21080. u64 n;
  21081. if( x<10 ) return 1;
  21082. n = x%10;
  21083. x /= 10;
  21084. if( n>=5 ) n -= 2;
  21085. else if( n>=1 ) n -= 1;
  21086. if( x>=3 ) return (n+8)<<(x-3);
  21087. return (n+8)>>(3-x);
  21088. }
  21089. /************** End of util.c ************************************************/
  21090. /************** Begin file hash.c ********************************************/
  21091. /*
  21092. ** 2001 September 22
  21093. **
  21094. ** The author disclaims copyright to this source code. In place of
  21095. ** a legal notice, here is a blessing:
  21096. **
  21097. ** May you do good and not evil.
  21098. ** May you find forgiveness for yourself and forgive others.
  21099. ** May you share freely, never taking more than you give.
  21100. **
  21101. *************************************************************************
  21102. ** This is the implementation of generic hash-tables
  21103. ** used in SQLite.
  21104. */
  21105. /* #include <assert.h> */
  21106. /* Turn bulk memory into a hash table object by initializing the
  21107. ** fields of the Hash structure.
  21108. **
  21109. ** "pNew" is a pointer to the hash table that is to be initialized.
  21110. */
  21111. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21112. assert( pNew!=0 );
  21113. pNew->first = 0;
  21114. pNew->count = 0;
  21115. pNew->htsize = 0;
  21116. pNew->ht = 0;
  21117. }
  21118. /* Remove all entries from a hash table. Reclaim all memory.
  21119. ** Call this routine to delete a hash table or to reset a hash table
  21120. ** to the empty state.
  21121. */
  21122. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21123. HashElem *elem; /* For looping over all elements of the table */
  21124. assert( pH!=0 );
  21125. elem = pH->first;
  21126. pH->first = 0;
  21127. sqlite3_free(pH->ht);
  21128. pH->ht = 0;
  21129. pH->htsize = 0;
  21130. while( elem ){
  21131. HashElem *next_elem = elem->next;
  21132. sqlite3_free(elem);
  21133. elem = next_elem;
  21134. }
  21135. pH->count = 0;
  21136. }
  21137. /*
  21138. ** The hashing function.
  21139. */
  21140. static unsigned int strHash(const char *z, int nKey){
  21141. int h = 0;
  21142. assert( nKey>=0 );
  21143. while( nKey > 0 ){
  21144. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21145. nKey--;
  21146. }
  21147. return h;
  21148. }
  21149. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21150. ** insert pNew into the pEntry hash bucket.
  21151. */
  21152. static void insertElement(
  21153. Hash *pH, /* The complete hash table */
  21154. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21155. HashElem *pNew /* The element to be inserted */
  21156. ){
  21157. HashElem *pHead; /* First element already in pEntry */
  21158. if( pEntry ){
  21159. pHead = pEntry->count ? pEntry->chain : 0;
  21160. pEntry->count++;
  21161. pEntry->chain = pNew;
  21162. }else{
  21163. pHead = 0;
  21164. }
  21165. if( pHead ){
  21166. pNew->next = pHead;
  21167. pNew->prev = pHead->prev;
  21168. if( pHead->prev ){ pHead->prev->next = pNew; }
  21169. else { pH->first = pNew; }
  21170. pHead->prev = pNew;
  21171. }else{
  21172. pNew->next = pH->first;
  21173. if( pH->first ){ pH->first->prev = pNew; }
  21174. pNew->prev = 0;
  21175. pH->first = pNew;
  21176. }
  21177. }
  21178. /* Resize the hash table so that it cantains "new_size" buckets.
  21179. **
  21180. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21181. ** if the new size is the same as the prior size.
  21182. ** Return TRUE if the resize occurs and false if not.
  21183. */
  21184. static int rehash(Hash *pH, unsigned int new_size){
  21185. struct _ht *new_ht; /* The new hash table */
  21186. HashElem *elem, *next_elem; /* For looping over existing elements */
  21187. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21188. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21189. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21190. }
  21191. if( new_size==pH->htsize ) return 0;
  21192. #endif
  21193. /* The inability to allocates space for a larger hash table is
  21194. ** a performance hit but it is not a fatal error. So mark the
  21195. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21196. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21197. ** only zeroes the requested number of bytes whereas this module will
  21198. ** use the actual amount of space allocated for the hash table (which
  21199. ** may be larger than the requested amount).
  21200. */
  21201. sqlite3BeginBenignMalloc();
  21202. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21203. sqlite3EndBenignMalloc();
  21204. if( new_ht==0 ) return 0;
  21205. sqlite3_free(pH->ht);
  21206. pH->ht = new_ht;
  21207. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21208. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21209. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21210. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21211. next_elem = elem->next;
  21212. insertElement(pH, &new_ht[h], elem);
  21213. }
  21214. return 1;
  21215. }
  21216. /* This function (for internal use only) locates an element in an
  21217. ** hash table that matches the given key. The hash for this key has
  21218. ** already been computed and is passed as the 4th parameter.
  21219. */
  21220. static HashElem *findElementGivenHash(
  21221. const Hash *pH, /* The pH to be searched */
  21222. const char *pKey, /* The key we are searching for */
  21223. int nKey, /* Bytes in key (not counting zero terminator) */
  21224. unsigned int h /* The hash for this key. */
  21225. ){
  21226. HashElem *elem; /* Used to loop thru the element list */
  21227. int count; /* Number of elements left to test */
  21228. if( pH->ht ){
  21229. struct _ht *pEntry = &pH->ht[h];
  21230. elem = pEntry->chain;
  21231. count = pEntry->count;
  21232. }else{
  21233. elem = pH->first;
  21234. count = pH->count;
  21235. }
  21236. while( count-- && ALWAYS(elem) ){
  21237. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21238. return elem;
  21239. }
  21240. elem = elem->next;
  21241. }
  21242. return 0;
  21243. }
  21244. /* Remove a single entry from the hash table given a pointer to that
  21245. ** element and a hash on the element's key.
  21246. */
  21247. static void removeElementGivenHash(
  21248. Hash *pH, /* The pH containing "elem" */
  21249. HashElem* elem, /* The element to be removed from the pH */
  21250. unsigned int h /* Hash value for the element */
  21251. ){
  21252. struct _ht *pEntry;
  21253. if( elem->prev ){
  21254. elem->prev->next = elem->next;
  21255. }else{
  21256. pH->first = elem->next;
  21257. }
  21258. if( elem->next ){
  21259. elem->next->prev = elem->prev;
  21260. }
  21261. if( pH->ht ){
  21262. pEntry = &pH->ht[h];
  21263. if( pEntry->chain==elem ){
  21264. pEntry->chain = elem->next;
  21265. }
  21266. pEntry->count--;
  21267. assert( pEntry->count>=0 );
  21268. }
  21269. sqlite3_free( elem );
  21270. pH->count--;
  21271. if( pH->count==0 ){
  21272. assert( pH->first==0 );
  21273. assert( pH->count==0 );
  21274. sqlite3HashClear(pH);
  21275. }
  21276. }
  21277. /* Attempt to locate an element of the hash table pH with a key
  21278. ** that matches pKey,nKey. Return the data for this element if it is
  21279. ** found, or NULL if there is no match.
  21280. */
  21281. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21282. HashElem *elem; /* The element that matches key */
  21283. unsigned int h; /* A hash on key */
  21284. assert( pH!=0 );
  21285. assert( pKey!=0 );
  21286. assert( nKey>=0 );
  21287. if( pH->ht ){
  21288. h = strHash(pKey, nKey) % pH->htsize;
  21289. }else{
  21290. h = 0;
  21291. }
  21292. elem = findElementGivenHash(pH, pKey, nKey, h);
  21293. return elem ? elem->data : 0;
  21294. }
  21295. /* Insert an element into the hash table pH. The key is pKey,nKey
  21296. ** and the data is "data".
  21297. **
  21298. ** If no element exists with a matching key, then a new
  21299. ** element is created and NULL is returned.
  21300. **
  21301. ** If another element already exists with the same key, then the
  21302. ** new data replaces the old data and the old data is returned.
  21303. ** The key is not copied in this instance. If a malloc fails, then
  21304. ** the new data is returned and the hash table is unchanged.
  21305. **
  21306. ** If the "data" parameter to this function is NULL, then the
  21307. ** element corresponding to "key" is removed from the hash table.
  21308. */
  21309. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21310. unsigned int h; /* the hash of the key modulo hash table size */
  21311. HashElem *elem; /* Used to loop thru the element list */
  21312. HashElem *new_elem; /* New element added to the pH */
  21313. assert( pH!=0 );
  21314. assert( pKey!=0 );
  21315. assert( nKey>=0 );
  21316. if( pH->htsize ){
  21317. h = strHash(pKey, nKey) % pH->htsize;
  21318. }else{
  21319. h = 0;
  21320. }
  21321. elem = findElementGivenHash(pH,pKey,nKey,h);
  21322. if( elem ){
  21323. void *old_data = elem->data;
  21324. if( data==0 ){
  21325. removeElementGivenHash(pH,elem,h);
  21326. }else{
  21327. elem->data = data;
  21328. elem->pKey = pKey;
  21329. assert(nKey==elem->nKey);
  21330. }
  21331. return old_data;
  21332. }
  21333. if( data==0 ) return 0;
  21334. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21335. if( new_elem==0 ) return data;
  21336. new_elem->pKey = pKey;
  21337. new_elem->nKey = nKey;
  21338. new_elem->data = data;
  21339. pH->count++;
  21340. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21341. if( rehash(pH, pH->count*2) ){
  21342. assert( pH->htsize>0 );
  21343. h = strHash(pKey, nKey) % pH->htsize;
  21344. }
  21345. }
  21346. if( pH->ht ){
  21347. insertElement(pH, &pH->ht[h], new_elem);
  21348. }else{
  21349. insertElement(pH, 0, new_elem);
  21350. }
  21351. return 0;
  21352. }
  21353. /************** End of hash.c ************************************************/
  21354. /************** Begin file opcodes.c *****************************************/
  21355. /* Automatically generated. Do not edit */
  21356. /* See the mkopcodec.awk script for details. */
  21357. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21358. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21359. static const char *const azName[] = { "?",
  21360. /* 1 */ "Function",
  21361. /* 2 */ "Savepoint",
  21362. /* 3 */ "AutoCommit",
  21363. /* 4 */ "Transaction",
  21364. /* 5 */ "SorterNext",
  21365. /* 6 */ "Prev",
  21366. /* 7 */ "Next",
  21367. /* 8 */ "AggStep",
  21368. /* 9 */ "Checkpoint",
  21369. /* 10 */ "JournalMode",
  21370. /* 11 */ "Vacuum",
  21371. /* 12 */ "VFilter",
  21372. /* 13 */ "VUpdate",
  21373. /* 14 */ "Goto",
  21374. /* 15 */ "Gosub",
  21375. /* 16 */ "Return",
  21376. /* 17 */ "Yield",
  21377. /* 18 */ "HaltIfNull",
  21378. /* 19 */ "Not",
  21379. /* 20 */ "Halt",
  21380. /* 21 */ "Integer",
  21381. /* 22 */ "Int64",
  21382. /* 23 */ "String",
  21383. /* 24 */ "Null",
  21384. /* 25 */ "Blob",
  21385. /* 26 */ "Variable",
  21386. /* 27 */ "Move",
  21387. /* 28 */ "Copy",
  21388. /* 29 */ "SCopy",
  21389. /* 30 */ "ResultRow",
  21390. /* 31 */ "CollSeq",
  21391. /* 32 */ "AddImm",
  21392. /* 33 */ "MustBeInt",
  21393. /* 34 */ "RealAffinity",
  21394. /* 35 */ "Permutation",
  21395. /* 36 */ "Compare",
  21396. /* 37 */ "Jump",
  21397. /* 38 */ "Once",
  21398. /* 39 */ "If",
  21399. /* 40 */ "IfNot",
  21400. /* 41 */ "Column",
  21401. /* 42 */ "Affinity",
  21402. /* 43 */ "MakeRecord",
  21403. /* 44 */ "Count",
  21404. /* 45 */ "ReadCookie",
  21405. /* 46 */ "SetCookie",
  21406. /* 47 */ "VerifyCookie",
  21407. /* 48 */ "OpenRead",
  21408. /* 49 */ "OpenWrite",
  21409. /* 50 */ "OpenAutoindex",
  21410. /* 51 */ "OpenEphemeral",
  21411. /* 52 */ "SorterOpen",
  21412. /* 53 */ "OpenPseudo",
  21413. /* 54 */ "Close",
  21414. /* 55 */ "SeekLt",
  21415. /* 56 */ "SeekLe",
  21416. /* 57 */ "SeekGe",
  21417. /* 58 */ "SeekGt",
  21418. /* 59 */ "Seek",
  21419. /* 60 */ "NotFound",
  21420. /* 61 */ "Found",
  21421. /* 62 */ "IsUnique",
  21422. /* 63 */ "NotExists",
  21423. /* 64 */ "Sequence",
  21424. /* 65 */ "NewRowid",
  21425. /* 66 */ "Insert",
  21426. /* 67 */ "InsertInt",
  21427. /* 68 */ "Or",
  21428. /* 69 */ "And",
  21429. /* 70 */ "Delete",
  21430. /* 71 */ "ResetCount",
  21431. /* 72 */ "SorterCompare",
  21432. /* 73 */ "IsNull",
  21433. /* 74 */ "NotNull",
  21434. /* 75 */ "Ne",
  21435. /* 76 */ "Eq",
  21436. /* 77 */ "Gt",
  21437. /* 78 */ "Le",
  21438. /* 79 */ "Lt",
  21439. /* 80 */ "Ge",
  21440. /* 81 */ "SorterData",
  21441. /* 82 */ "BitAnd",
  21442. /* 83 */ "BitOr",
  21443. /* 84 */ "ShiftLeft",
  21444. /* 85 */ "ShiftRight",
  21445. /* 86 */ "Add",
  21446. /* 87 */ "Subtract",
  21447. /* 88 */ "Multiply",
  21448. /* 89 */ "Divide",
  21449. /* 90 */ "Remainder",
  21450. /* 91 */ "Concat",
  21451. /* 92 */ "RowKey",
  21452. /* 93 */ "BitNot",
  21453. /* 94 */ "String8",
  21454. /* 95 */ "RowData",
  21455. /* 96 */ "Rowid",
  21456. /* 97 */ "NullRow",
  21457. /* 98 */ "Last",
  21458. /* 99 */ "SorterSort",
  21459. /* 100 */ "Sort",
  21460. /* 101 */ "Rewind",
  21461. /* 102 */ "SorterInsert",
  21462. /* 103 */ "IdxInsert",
  21463. /* 104 */ "IdxDelete",
  21464. /* 105 */ "IdxRowid",
  21465. /* 106 */ "IdxLT",
  21466. /* 107 */ "IdxGE",
  21467. /* 108 */ "Destroy",
  21468. /* 109 */ "Clear",
  21469. /* 110 */ "CreateIndex",
  21470. /* 111 */ "CreateTable",
  21471. /* 112 */ "ParseSchema",
  21472. /* 113 */ "LoadAnalysis",
  21473. /* 114 */ "DropTable",
  21474. /* 115 */ "DropIndex",
  21475. /* 116 */ "DropTrigger",
  21476. /* 117 */ "IntegrityCk",
  21477. /* 118 */ "RowSetAdd",
  21478. /* 119 */ "RowSetRead",
  21479. /* 120 */ "RowSetTest",
  21480. /* 121 */ "Program",
  21481. /* 122 */ "Param",
  21482. /* 123 */ "FkCounter",
  21483. /* 124 */ "FkIfZero",
  21484. /* 125 */ "MemMax",
  21485. /* 126 */ "IfPos",
  21486. /* 127 */ "IfNeg",
  21487. /* 128 */ "IfZero",
  21488. /* 129 */ "AggFinal",
  21489. /* 130 */ "Real",
  21490. /* 131 */ "IncrVacuum",
  21491. /* 132 */ "Expire",
  21492. /* 133 */ "TableLock",
  21493. /* 134 */ "VBegin",
  21494. /* 135 */ "VCreate",
  21495. /* 136 */ "VDestroy",
  21496. /* 137 */ "VOpen",
  21497. /* 138 */ "VColumn",
  21498. /* 139 */ "VNext",
  21499. /* 140 */ "VRename",
  21500. /* 141 */ "ToText",
  21501. /* 142 */ "ToBlob",
  21502. /* 143 */ "ToNumeric",
  21503. /* 144 */ "ToInt",
  21504. /* 145 */ "ToReal",
  21505. /* 146 */ "Pagecount",
  21506. /* 147 */ "MaxPgcnt",
  21507. /* 148 */ "Trace",
  21508. /* 149 */ "Noop",
  21509. /* 150 */ "Explain",
  21510. };
  21511. return azName[i];
  21512. }
  21513. #endif
  21514. /************** End of opcodes.c *********************************************/
  21515. /************** Begin file os_rtthread.c *************************************/
  21516. /*
  21517. ** 2004 May 22
  21518. **
  21519. ** The author disclaims copyright to this source code. In place of
  21520. ** a legal notice, here is a blessing:
  21521. **
  21522. ** May you do good and not evil.
  21523. ** May you find forgiveness for yourself and forgive others.
  21524. ** May you share freely, never taking more than you give.
  21525. **
  21526. ******************************************************************************
  21527. **
  21528. ** This file contains code that is specific to Windows.
  21529. */
  21530. #if SQLITE_OS_RTTHREAD /* This file is used for rt-thread only */
  21531. /* #include <rtthread.h> */
  21532. #include <dfs_posix.h>
  21533. /*
  21534. ** Include code that is common to all os_*.c files
  21535. */
  21536. /************** Include os_common.h in the middle of os_rtthread.c ***********/
  21537. /************** Begin file os_common.h ***************************************/
  21538. /*
  21539. ** 2004 May 22
  21540. **
  21541. ** The author disclaims copyright to this source code. In place of
  21542. ** a legal notice, here is a blessing:
  21543. **
  21544. ** May you do good and not evil.
  21545. ** May you find forgiveness for yourself and forgive others.
  21546. ** May you share freely, never taking more than you give.
  21547. **
  21548. ******************************************************************************
  21549. **
  21550. ** This file contains macros and a little bit of code that is common to
  21551. ** all of the platform-specific files (os_*.c) and is #included into those
  21552. ** files.
  21553. **
  21554. ** This file should be #included by the os_*.c files only. It is not a
  21555. ** general purpose header file.
  21556. */
  21557. #ifndef _OS_COMMON_H_
  21558. #define _OS_COMMON_H_
  21559. /*
  21560. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  21561. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  21562. ** switch. The following code should catch this problem at compile-time.
  21563. */
  21564. #ifdef MEMORY_DEBUG
  21565. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  21566. #endif
  21567. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  21568. # ifndef SQLITE_DEBUG_OS_TRACE
  21569. # define SQLITE_DEBUG_OS_TRACE 0
  21570. # endif
  21571. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  21572. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  21573. #else
  21574. # define OSTRACE(X)
  21575. #endif
  21576. /*
  21577. ** Macros for performance tracing. Normally turned off. Only works
  21578. ** on i486 hardware.
  21579. */
  21580. #ifdef SQLITE_PERFORMANCE_TRACE
  21581. /*
  21582. ** hwtime.h contains inline assembler code for implementing
  21583. ** high-performance timing routines.
  21584. */
  21585. /************** Include hwtime.h in the middle of os_common.h ****************/
  21586. /************** Begin file hwtime.h ******************************************/
  21587. /*
  21588. ** 2008 May 27
  21589. **
  21590. ** The author disclaims copyright to this source code. In place of
  21591. ** a legal notice, here is a blessing:
  21592. **
  21593. ** May you do good and not evil.
  21594. ** May you find forgiveness for yourself and forgive others.
  21595. ** May you share freely, never taking more than you give.
  21596. **
  21597. ******************************************************************************
  21598. **
  21599. ** This file contains inline asm code for retrieving "high-performance"
  21600. ** counters for x86 class CPUs.
  21601. */
  21602. #ifndef _HWTIME_H_
  21603. #define _HWTIME_H_
  21604. /*
  21605. ** The following routine only works on pentium-class (or newer) processors.
  21606. ** It uses the RDTSC opcode to read the cycle count value out of the
  21607. ** processor and returns that value. This can be used for high-res
  21608. ** profiling.
  21609. */
  21610. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  21611. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  21612. #if defined(__GNUC__)
  21613. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21614. unsigned int lo, hi;
  21615. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  21616. return (sqlite_uint64)hi << 32 | lo;
  21617. }
  21618. #elif defined(_MSC_VER)
  21619. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  21620. __asm {
  21621. rdtsc
  21622. ret ; return value at EDX:EAX
  21623. }
  21624. }
  21625. #endif
  21626. #elif (defined(__GNUC__) && defined(__x86_64__))
  21627. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21628. unsigned long val;
  21629. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  21630. return val;
  21631. }
  21632. #elif (defined(__GNUC__) && defined(__ppc__))
  21633. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21634. unsigned long long retval;
  21635. unsigned long junk;
  21636. __asm__ __volatile__ ("\n\
  21637. 1: mftbu %1\n\
  21638. mftb %L0\n\
  21639. mftbu %0\n\
  21640. cmpw %0,%1\n\
  21641. bne 1b"
  21642. : "=r" (retval), "=r" (junk));
  21643. return retval;
  21644. }
  21645. #else
  21646. #error Need implementation of sqlite3Hwtime() for your platform.
  21647. /*
  21648. ** To compile without implementing sqlite3Hwtime() for your platform,
  21649. ** you can remove the above #error and use the following
  21650. ** stub function. You will lose timing support for many
  21651. ** of the debugging and testing utilities, but it should at
  21652. ** least compile and run.
  21653. */
  21654. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  21655. #endif
  21656. #endif /* !defined(_HWTIME_H_) */
  21657. /************** End of hwtime.h **********************************************/
  21658. /************** Continuing where we left off in os_common.h ******************/
  21659. static sqlite_uint64 g_start;
  21660. static sqlite_uint64 g_elapsed;
  21661. #define TIMER_START g_start=sqlite3Hwtime()
  21662. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  21663. #define TIMER_ELAPSED g_elapsed
  21664. #else
  21665. #define TIMER_START
  21666. #define TIMER_END
  21667. #define TIMER_ELAPSED ((sqlite_uint64)0)
  21668. #endif
  21669. /*
  21670. ** If we compile with the SQLITE_TEST macro set, then the following block
  21671. ** of code will give us the ability to simulate a disk I/O error. This
  21672. ** is used for testing the I/O recovery logic.
  21673. */
  21674. #ifdef SQLITE_TEST
  21675. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21676. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21677. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21678. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21679. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21680. SQLITE_API int sqlite3_diskfull_pending = 0;
  21681. SQLITE_API int sqlite3_diskfull = 0;
  21682. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  21683. #define SimulateIOError(CODE) \
  21684. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  21685. || sqlite3_io_error_pending-- == 1 ) \
  21686. { local_ioerr(); CODE; }
  21687. static void local_ioerr(){
  21688. IOTRACE(("IOERR\n"));
  21689. sqlite3_io_error_hit++;
  21690. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  21691. }
  21692. #define SimulateDiskfullError(CODE) \
  21693. if( sqlite3_diskfull_pending ){ \
  21694. if( sqlite3_diskfull_pending == 1 ){ \
  21695. local_ioerr(); \
  21696. sqlite3_diskfull = 1; \
  21697. sqlite3_io_error_hit = 1; \
  21698. CODE; \
  21699. }else{ \
  21700. sqlite3_diskfull_pending--; \
  21701. } \
  21702. }
  21703. #else
  21704. #define SimulateIOErrorBenign(X)
  21705. #define SimulateIOError(A)
  21706. #define SimulateDiskfullError(A)
  21707. #endif
  21708. /*
  21709. ** When testing, keep a count of the number of open files.
  21710. */
  21711. #ifdef SQLITE_TEST
  21712. SQLITE_API int sqlite3_open_file_count = 0;
  21713. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  21714. #else
  21715. #define OpenCounter(X)
  21716. #endif
  21717. #endif /* !defined(_OS_COMMON_H_) */
  21718. /************** End of os_common.h *******************************************/
  21719. /************** Continuing where we left off in os_rtthread.c ****************/
  21720. #ifndef RT_USING_NEWLIB
  21721. #ifndef EINTR
  21722. #define EINTR 4 /* Interrupted system call */
  21723. #endif
  21724. #ifndef ENOLCK
  21725. #define ENOLCK 46 /* No record locks available */
  21726. #endif
  21727. #ifndef EACCES
  21728. #define EACCES 13 /* Permission denied */
  21729. #endif
  21730. #ifndef EPERM
  21731. #define EPERM 1 /* Operation not permitted */
  21732. #endif
  21733. #ifndef ETIMEDOUT
  21734. #define ETIMEDOUT 145 /* Connection timed out */
  21735. #endif
  21736. #ifndef ENOTCONN
  21737. #define ENOTCONN 134 /* Transport endpoint is not connected */
  21738. #endif
  21739. #if defined(__GNUC__) || defined(__ADSPBLACKFIN__)
  21740. int _gettimeofday(struct timeval *tp, void *ignore) __attribute__((weak));
  21741. int _gettimeofday(struct timeval *tp, void *ignore)
  21742. #elif defined(__CC_ARM)
  21743. __weak int _gettimeofday(struct timeval *tp, void *ignore)
  21744. #elif defined(__IAR_SYSTEMS_ICC__)
  21745. #if __VER__ > 540
  21746. __weak
  21747. #endif
  21748. int _gettimeofday(struct timeval *tp, void *ignore)
  21749. #else
  21750. int _gettimeofday(struct timeval *tp, void *ignore)
  21751. #endif
  21752. {
  21753. return 0;
  21754. }
  21755. #endif /* RT_USING_NEWLIB */
  21756. /*
  21757. ** Compiling and using WAL mode requires several APIs that are not
  21758. ** available in rt-thread.
  21759. */
  21760. #if !defined(SQLITE_OMIT_WAL)
  21761. # error "WAL mode requires not support from the rt-thread, compile\
  21762. with SQLITE_OMIT_WAL."
  21763. #endif
  21764. /*
  21765. ** Are most of the rtthread ANSI APIs available (i.e. with certain exceptions
  21766. ** based on the sub-platform)?
  21767. */
  21768. #if !defined(SQLITE_RTTHREAD_NO_ANSI)
  21769. # warning "please ensure rtthread ANSI APIs is available, otherwise compile with\
  21770. SQLITE_RTTHREAD_NO_ANSI"
  21771. # define SQLITE_RTTHREAD_HAS_ANSI
  21772. #endif
  21773. /*
  21774. ** Are most of the rtthread Unicode APIs available (i.e. with certain exceptions
  21775. ** based on the sub-platform)?
  21776. */
  21777. #if !defined(SQLITE_RTTHREAD_NO_WIDE)
  21778. # error "rtthread not support Unicode APIs"
  21779. # define SQLITE_RTTHREAD_HAS_WIDE
  21780. #endif
  21781. /*
  21782. ** Make sure at least one set of rtthread APIs is available.
  21783. */
  21784. #if !defined(SQLITE_RTTHREAD_HAS_ANSI) && !defined(SQLITE_RTTHREAD_HAS_WIDE)
  21785. # error "At least one of SQLITE_RTTHREAD_HAS_ANSI and SQLITE_RTTHREAD_HAS_WIDE\
  21786. must be defined."
  21787. #endif
  21788. /*
  21789. ** Maximum pathname length (in chars) for rtthread. This should normally be
  21790. ** MAX_PATH.
  21791. */
  21792. #ifndef SQLITE_RTTHREAD_MAX_PATH_CHARS
  21793. # warning "default Maximum pathname length be 255, otherwise compile with\
  21794. SQLITE_RTTHREAD_MAX_PATH_CHARS=?"
  21795. # define SQLITE_RTTHREAD_MAX_PATH_CHARS (255)
  21796. #endif
  21797. /*
  21798. ** Maximum supported path-length.
  21799. */
  21800. #define MAX_PATHNAME 512
  21801. /*
  21802. ** Returns non-zero if the character should be treated as a directory
  21803. ** separator.
  21804. */
  21805. #ifndef rtthreadIsDirSep
  21806. # define rtthreadIsDirSep(a) ((a) == '/')
  21807. #endif
  21808. /*
  21809. ** This macro is used when a local variable is set to a value that is
  21810. ** [sometimes] not used by the code (e.g. via conditional compilation).
  21811. */
  21812. #ifndef UNUSED_VARIABLE_VALUE
  21813. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  21814. #endif
  21815. /*
  21816. ** Returns the string that should be used as the directory separator.
  21817. */
  21818. #ifndef rtthreadGetDirDep
  21819. # define rtthreadGetDirDep() "/"
  21820. #endif
  21821. /*
  21822. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  21823. ** portability layer.
  21824. */
  21825. typedef struct rtthreadFile rtthreadFile;
  21826. struct rtthreadFile {
  21827. sqlite3_io_methods const *pMethod; /* Always the first entry */
  21828. sqlite3_vfs *pVfs; /* The VFS that created this rtthreadFile */
  21829. int h; /* The file descriptor */
  21830. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  21831. unsigned char eFileLock; /* The type of lock held on this fd */
  21832. int lastErrno; /* The unix errno from last I/O error */
  21833. void *lockingContext; /* Locking style specific state */
  21834. const char *zPath; /* Name of the file */
  21835. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  21836. #if SQLITE_ENABLE_LOCKING_STYLE
  21837. int openFlags; /* The flags specified at open() */
  21838. #endif
  21839. #if SQLITE_ENABLE_LOCKING_STYLE
  21840. unsigned fsFlags; /* cached details from statfs() */
  21841. #endif
  21842. #ifdef SQLITE_DEBUG
  21843. /* The next group of variables are used to track whether or not the
  21844. ** transaction counter in bytes 24-27 of database files are updated
  21845. ** whenever any part of the database changes. An assertion fault will
  21846. ** occur if a file is updated without also updating the transaction
  21847. ** counter. This test is made to avoid new problems similar to the
  21848. ** one described by ticket #3584.
  21849. */
  21850. unsigned char transCntrChng; /* True if the transaction counter changed */
  21851. unsigned char dbUpdate; /* True if any part of database file changed */
  21852. unsigned char inNormalWrite; /* True if in a normal write operation */
  21853. #endif
  21854. #ifdef SQLITE_TEST
  21855. /* In test mode, increase the size of this structure a bit so that
  21856. ** it is larger than the struct CrashFile defined in test6.c.
  21857. */
  21858. char aPadding[32];
  21859. #endif
  21860. };
  21861. /*
  21862. ** Allowed values for the rtthreadFile.ctrlFlags bitmask:
  21863. */
  21864. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  21865. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  21866. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  21867. #ifndef SQLITE_DISABLE_DIRSYNC
  21868. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  21869. #else
  21870. # define UNIXFILE_DIRSYNC 0x00
  21871. #endif
  21872. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  21873. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  21874. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  21875. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  21876. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  21877. /*
  21878. ** The following variable is (normally) set once and never changes
  21879. ** thereafter. It records whether the operating system is Win9x
  21880. ** or WinNT.
  21881. **
  21882. ** 0: Operating system unknown.
  21883. ** 1: Operating system is rtthread.
  21884. **
  21885. ** In order to facilitate testing on a rtthread system, the test fixture
  21886. ** can manually set this value to 1 to emulate Win98 behavior.
  21887. */
  21888. #ifdef SQLITE_TEST
  21889. SQLITE_API int sqlite3_os_type = 0;
  21890. #elif !SQLITE_OS_RTTHREAD && \
  21891. defined(SQLITE_RTTHREAD_HAS_ANSI) && defined(SQLITE_RTTHREAD_HAS_WIDE)
  21892. static int sqlite3_os_type = 0;
  21893. #endif
  21894. #ifndef SYSCALL
  21895. # define SYSCALL sqlite3_syscall_ptr
  21896. #endif
  21897. /* #include <dfs_posix.h> */
  21898. static int _Access(const char *pathname, int mode)
  21899. {
  21900. int fd;
  21901. fd = open(pathname, O_RDONLY, mode);
  21902. if (fd >= 0)
  21903. {
  21904. close(fd);
  21905. return 0;
  21906. }
  21907. return -1;
  21908. }
  21909. /*
  21910. ** Invoke open(). Do so multiple times, until it either succeeds or
  21911. ** fails for some reason other than EINTR.
  21912. **
  21913. ** If the file creation mode "m" is 0 then set it to the default for
  21914. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  21915. ** 0644) as modified by the system umask. If m is not 0, then
  21916. ** make the file creation mode be exactly m ignoring the umask.
  21917. **
  21918. ** The m parameter will be non-zero only when creating -wal, -journal,
  21919. ** and -shm files. We want those files to have *exactly* the same
  21920. ** permissions as their original database, unadulterated by the umask.
  21921. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  21922. ** transaction crashes and leaves behind hot journals, then any
  21923. ** process that is able to write to the database will also be able to
  21924. ** recover the hot journals.
  21925. */
  21926. static int robust_open(const char *z, int f, mode_t m);
  21927. /*
  21928. ** Open a file descriptor to the directory containing file zFilename.
  21929. ** If successful, *pFd is set to the opened file descriptor and
  21930. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  21931. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  21932. ** value.
  21933. **
  21934. ** The directory file descriptor is used for only one thing - to
  21935. ** fsync() a directory to make sure file creation and deletion events
  21936. ** are flushed to disk. Such fsyncs are not needed on newer
  21937. ** journaling filesystems, but are required on older filesystems.
  21938. **
  21939. ** This routine can be overridden using the xSetSysCall interface.
  21940. ** The ability to override this routine was added in support of the
  21941. ** chromium sandbox. Opening a directory is a security risk (we are
  21942. ** told) so making it overrideable allows the chromium sandbox to
  21943. ** replace this routine with a harmless no-op. To make this routine
  21944. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  21945. ** *pFd set to a negative number.
  21946. **
  21947. ** If SQLITE_OK is returned, the caller is responsible for closing
  21948. ** the file descriptor *pFd using close().
  21949. */
  21950. static int openDirectory(const char *zFilename, int *pFd);
  21951. /*
  21952. ** Many system calls are accessed through pointer-to-functions so that
  21953. ** they may be overridden at runtime to facilitate fault injection during
  21954. ** testing and sandboxing. The following array holds the names and pointers
  21955. ** to all overrideable system calls.
  21956. */
  21957. static struct rtthread_syscall {
  21958. const char *zName; /* Name of the system call */
  21959. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  21960. sqlite3_syscall_ptr pDefault; /* Default value */
  21961. } aSyscall[] = {
  21962. {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0},
  21963. #define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent)
  21964. { "open", (sqlite3_syscall_ptr)open, 0 },
  21965. #define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent)
  21966. { "close", (sqlite3_syscall_ptr)close, 0 },
  21967. #define osClose ((int(*)(int))aSyscall[2].pCurrent)
  21968. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  21969. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  21970. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  21971. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  21972. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  21973. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  21974. { "read", (sqlite3_syscall_ptr)read, 0 },
  21975. #define osRead ((int(*)(int,void*,size_t))aSyscall[6].pCurrent)
  21976. { "write", (sqlite3_syscall_ptr)write, 0 },
  21977. #define osWrite ((int(*)(int,const void*,size_t))aSyscall[7].pCurrent)
  21978. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  21979. #define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent)
  21980. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  21981. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent)
  21982. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  21983. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent)
  21984. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  21985. #define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent)
  21986. {"access", (sqlite3_syscall_ptr)_Access, 0 },
  21987. #define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent)
  21988. }; /* End of the overrideable system calls */
  21989. /*
  21990. **
  21991. ** This function - unixLogError_x(), is only ever called via the macro
  21992. ** unixLogError().
  21993. **
  21994. ** It is invoked after an error occurs in an OS function and errno has been
  21995. ** set. It logs a message using sqlite3_log() containing the current value of
  21996. ** errno and, if possible, the human-readable equivalent from strerror() or
  21997. ** strerror_r().
  21998. **
  21999. ** The first argument passed to the macro should be the error code that
  22000. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  22001. ** The two subsequent arguments should be the name of the OS function that
  22002. ** failed (e.g. "unlink", "open") and the associated file-system path,
  22003. ** if any.
  22004. */
  22005. #define rtthreadLogError(a,b,c) rtthreadLogErrorAtLine(a,b,c,__LINE__)
  22006. static int rtthreadLogErrorAtLine(
  22007. int errcode, /* SQLite error code */
  22008. const char *zFunc, /* Name of OS function that failed */
  22009. const char *zPath, /* File path associated with error */
  22010. int iLine /* Source line number where error occurred */
  22011. ){
  22012. char *zErr; /* Message from strerror() or equivalent */
  22013. int iErrno = errno; /* Saved syscall error number */
  22014. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  22015. ** the strerror() function to obtain the human-readable error message
  22016. ** equivalent to errno. Otherwise, use strerror_r().
  22017. */
  22018. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  22019. char aErr[80];
  22020. memset(aErr, 0, sizeof(aErr));
  22021. zErr = aErr;
  22022. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  22023. ** assume that the system provides the GNU version of strerror_r() that
  22024. ** returns a pointer to a buffer containing the error message. That pointer
  22025. ** may point to aErr[], or it may point to some static storage somewhere.
  22026. ** Otherwise, assume that the system provides the POSIX version of
  22027. ** strerror_r(), which always writes an error message into aErr[].
  22028. **
  22029. ** If the code incorrectly assumes that it is the POSIX version that is
  22030. ** available, the error message will often be an empty string. Not a
  22031. ** huge problem. Incorrectly concluding that the GNU version is available
  22032. ** could lead to a segfault though.
  22033. */
  22034. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  22035. zErr =
  22036. # endif
  22037. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  22038. #elif SQLITE_THREADSAFE
  22039. /* This is a threadsafe build, but strerror_r() is not available. */
  22040. zErr = "";
  22041. #else
  22042. /* Non-threadsafe build, use strerror(). */
  22043. zErr = strerror(iErrno);
  22044. #endif
  22045. if( zPath==0 ) zPath = "";
  22046. sqlite3_log(errcode,
  22047. "os_rtthread.c:%d: (%d) %s(%s) - %s",
  22048. iLine, iErrno, zFunc, zPath, zErr
  22049. );
  22050. return errcode;
  22051. }
  22052. /*
  22053. ** Do not accept any file descriptor less than this value, in order to avoid
  22054. ** opening database file using file descriptors that are commonly used for
  22055. ** standard input, output, and error.
  22056. */
  22057. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  22058. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  22059. #endif
  22060. /*
  22061. ** Invoke open(). Do so multiple times, until it either succeeds or
  22062. ** fails for some reason other than EINTR.
  22063. **
  22064. ** If the file creation mode "m" is 0 then set it to the default for
  22065. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22066. ** 0644) as modified by the system umask. If m is not 0, then
  22067. ** make the file creation mode be exactly m ignoring the umask.
  22068. **
  22069. ** The m parameter will be non-zero only when creating -wal, -journal,
  22070. ** and -shm files. We want those files to have *exactly* the same
  22071. ** permissions as their original database, unadulterated by the umask.
  22072. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22073. ** transaction crashes and leaves behind hot journals, then any
  22074. ** process that is able to write to the database will also be able to
  22075. ** recover the hot journals.
  22076. */
  22077. static int robust_open(const char *z, int f, mode_t m){
  22078. int fd;
  22079. mode_t m2 = m ;
  22080. while(1){
  22081. #if defined(O_CLOEXEC)
  22082. fd = osOpen(z,f|O_CLOEXEC,m2);
  22083. #else
  22084. fd = osOpen(z,f,m2);
  22085. #endif
  22086. if( fd<0 ){
  22087. if( errno==EINTR ) continue;
  22088. break;
  22089. }
  22090. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  22091. osClose(fd);
  22092. sqlite3_log(SQLITE_WARNING,
  22093. "attempt to open \"%s\" as file descriptor %d", z, fd);
  22094. fd = -1;
  22095. if( osOpen("/000111sql.test111000", f, m)<0 ) break;
  22096. }
  22097. return fd;
  22098. }
  22099. /*
  22100. ** Open a file descriptor to the directory containing file zFilename.
  22101. ** If successful, *pFd is set to the opened file descriptor and
  22102. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  22103. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  22104. ** value.
  22105. **
  22106. ** The directory file descriptor is used for only one thing - to
  22107. ** fsync() a directory to make sure file creation and deletion events
  22108. ** are flushed to disk. Such fsyncs are not needed on newer
  22109. ** journaling filesystems, but are required on older filesystems.
  22110. **
  22111. ** This routine can be overridden using the xSetSysCall interface.
  22112. ** The ability to override this routine was added in support of the
  22113. ** chromium sandbox. Opening a directory is a security risk (we are
  22114. ** told) so making it overrideable allows the chromium sandbox to
  22115. ** replace this routine with a harmless no-op. To make this routine
  22116. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  22117. ** *pFd set to a negative number.
  22118. **
  22119. ** If SQLITE_OK is returned, the caller is responsible for closing
  22120. ** the file descriptor *pFd using close().
  22121. */
  22122. static int openDirectory(const char *zFilename, int *pFd){
  22123. int ii;
  22124. int fd = -1;
  22125. char zDirname[MAX_PATHNAME+1];
  22126. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  22127. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  22128. if( ii>0 ){
  22129. zDirname[ii] = '\0';
  22130. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  22131. if( fd>=0 ){
  22132. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  22133. }
  22134. }
  22135. *pFd = fd;
  22136. return (fd>=0?SQLITE_OK:rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  22137. }
  22138. /*
  22139. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22140. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  22141. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22142. ** system call named zName.
  22143. */
  22144. static int rtthreadSetSystemCall(
  22145. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22146. const char *zName, /* Name of system call to override */
  22147. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22148. ){
  22149. unsigned int i;
  22150. int rc = SQLITE_NOTFOUND;
  22151. UNUSED_PARAMETER(pNotUsed);
  22152. if( zName==0 ){
  22153. /* If no zName is given, restore all system calls to their default
  22154. ** settings and return NULL
  22155. */
  22156. rc = SQLITE_OK;
  22157. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22158. if( aSyscall[i].pDefault ){
  22159. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22160. }
  22161. }
  22162. }else{
  22163. /* If zName is specified, operate on only the one system call
  22164. ** specified.
  22165. */
  22166. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22167. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22168. if( aSyscall[i].pDefault==0 ){
  22169. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22170. }
  22171. rc = SQLITE_OK;
  22172. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22173. aSyscall[i].pCurrent = pNewFunc;
  22174. break;
  22175. }
  22176. }
  22177. }
  22178. return rc;
  22179. }
  22180. /*
  22181. ** Return the value of a system call. Return NULL if zName is not a
  22182. ** recognized system call name. NULL is also returned if the system call
  22183. ** is currently undefined.
  22184. */
  22185. static sqlite3_syscall_ptr rtthreadGetSystemCall(
  22186. sqlite3_vfs *pNotUsed,
  22187. const char *zName
  22188. ){
  22189. unsigned int i;
  22190. UNUSED_PARAMETER(pNotUsed);
  22191. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22192. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22193. }
  22194. return 0;
  22195. }
  22196. /*
  22197. ** Return the name of the first system call after zName. If zName==NULL
  22198. ** then return the name of the first system call. Return NULL if zName
  22199. ** is the last system call or if zName is not the name of a valid
  22200. ** system call.
  22201. */
  22202. static const char* rtthreadNextSystemCall(sqlite3_vfs *p, const char *zName){
  22203. int i = -1;
  22204. UNUSED_PARAMETER(p);
  22205. if( zName ){
  22206. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22207. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22208. }
  22209. }
  22210. for(i++; i<ArraySize(aSyscall); i++){
  22211. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22212. }
  22213. return 0;
  22214. }
  22215. /*
  22216. ** The following routine suspends the current thread for at least ms
  22217. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  22218. */
  22219. SQLITE_API void sqlite3_rtthread_sleep(int milliseconds){
  22220. rt_tick_t sleep_tick;
  22221. if (milliseconds <= 0)
  22222. return;
  22223. sleep_tick = rt_tick_from_millisecond(milliseconds);
  22224. osSleep(sleep_tick);
  22225. }
  22226. /*
  22227. ** Helper functions to obtain and relinquish the global mutex. The
  22228. ** global mutex is used to protect the unixInodeInfo and
  22229. ** vxworksFileId objects used by this file, all of which may be
  22230. ** shared by multiple threads.
  22231. **
  22232. ** Function unixMutexHeld() is used to assert() that the global mutex
  22233. ** is held when required. This function is only used as part of assert()
  22234. ** statements. e.g.
  22235. **
  22236. ** unixEnterMutex()
  22237. ** assert( unixMutexHeld() );
  22238. ** unixEnterLeave()
  22239. */
  22240. static void rtthreadEnterMutex(void){
  22241. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22242. }
  22243. static void rtthreadLeaveMutex(void){
  22244. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22245. }
  22246. #ifdef SQLITE_DEBUG
  22247. static int rtthreadMutexHeld(void) {
  22248. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22249. }
  22250. #endif
  22251. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22252. /*
  22253. ** Helper function for printing out trace information from debugging
  22254. ** binaries. This returns the string represetation of the supplied
  22255. ** integer lock-type.
  22256. */
  22257. static const char *azFileLock(int eFileLock){
  22258. switch( eFileLock ){
  22259. case NO_LOCK: return "NONE";
  22260. case SHARED_LOCK: return "SHARED";
  22261. case RESERVED_LOCK: return "RESERVED";
  22262. case PENDING_LOCK: return "PENDING";
  22263. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22264. }
  22265. return "ERROR";
  22266. }
  22267. #endif
  22268. /*
  22269. ** This routine translates a standard POSIX errno code into something
  22270. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22271. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22272. ** and a variety of "please close the file descriptor NOW" errors into
  22273. ** SQLITE_IOERR
  22274. **
  22275. ** Errors during initialization of locks, or file system support for locks,
  22276. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22277. */
  22278. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22279. switch (posixError) {
  22280. #if 0
  22281. /* At one point this code was not commented out. In theory, this branch
  22282. ** should never be hit, as this function should only be called after
  22283. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22284. ** the value of errno as the first argument. Since a system call has failed,
  22285. ** errno should be non-zero.
  22286. **
  22287. ** Despite this, if errno really is zero, we still don't want to return
  22288. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22289. ** propagated back to the caller. Commenting this branch out means errno==0
  22290. ** will be handled by the "default:" case below.
  22291. */
  22292. case 0:
  22293. return SQLITE_OK;
  22294. #endif
  22295. case DFS_STATUS_EAGAIN:
  22296. case ETIMEDOUT:
  22297. case DFS_STATUS_EBUSY:
  22298. case EINTR:
  22299. case ENOLCK:
  22300. /* random NFS retry error, unless during file system support
  22301. * introspection, in which it actually means what it says */
  22302. return SQLITE_BUSY;
  22303. case EACCES:
  22304. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  22305. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  22306. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  22307. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  22308. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  22309. return SQLITE_BUSY;
  22310. }
  22311. /* else fall through */
  22312. case EPERM:
  22313. return SQLITE_PERM;
  22314. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  22315. ** this module never makes such a call. And the code in SQLite itself
  22316. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  22317. ** this case is also commented out. If the system does set errno to EDEADLK,
  22318. ** the default SQLITE_IOERR_XXX code will be returned. */
  22319. #if 0
  22320. case EDEADLK:
  22321. return SQLITE_IOERR_BLOCKED;
  22322. #endif
  22323. #if EOPNOTSUPP!=ENOTSUP
  22324. case EOPNOTSUPP:
  22325. /* something went terribly awry, unless during file system support
  22326. * introspection, in which it actually means what it says */
  22327. #endif
  22328. #ifdef ENOTSUP
  22329. case ENOTSUP:
  22330. /* invalid fd, unless during file system support introspection, in which
  22331. * it actually means what it says */
  22332. #endif
  22333. case DFS_STATUS_EIO:
  22334. case DFS_STATUS_EBADF:
  22335. case DFS_STATUS_EINVAL:
  22336. case ENOTCONN:
  22337. case DFS_STATUS_ENODEV:
  22338. case DFS_STATUS_ENXIO:
  22339. case DFS_STATUS_ENOENT:
  22340. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  22341. case ESTALE:
  22342. #endif
  22343. case DFS_STATUS_ENOSYS:
  22344. /* these should force the client to close the file and reconnect */
  22345. default:
  22346. return sqliteIOErr;
  22347. }
  22348. }
  22349. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22350. int rc;
  22351. rc = -1;
  22352. return rc;
  22353. }
  22354. /*
  22355. ** Close a file descriptor.
  22356. **
  22357. ** We assume that close() almost always works, since it is only in a
  22358. ** very sick application or on a very sick platform that it might fail.
  22359. ** If it does fail, simply leak the file descriptor, but do log the
  22360. ** error.
  22361. **
  22362. ** Note that it is not safe to retry close() after EINTR since the
  22363. ** file descriptor might have already been reused by another thread.
  22364. ** So we don't even try to recover from an EINTR. Just log the error
  22365. ** and move on.
  22366. */
  22367. static void robust_close(rtthreadFile *pFile, int h, int lineno){
  22368. if( osClose(h) ){
  22369. rtthreadLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  22370. pFile ? pFile->zPath : 0, lineno);
  22371. }
  22372. }
  22373. /*
  22374. ** Check a rtthreadFile that is a database. Verify the following:
  22375. **
  22376. ** (1) There is exactly one hard link on the file
  22377. ** (2) The file is not a symbolic link
  22378. ** (3) The file has not been renamed or unlinked
  22379. **
  22380. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  22381. */
  22382. static void verifyDbFile(rtthreadFile *pFile){
  22383. struct stat buf;
  22384. int rc;
  22385. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  22386. /* One or more of the following warnings have already been issued. Do not
  22387. ** repeat them so as not to clutter the error log */
  22388. return;
  22389. }
  22390. rc = osFstat(pFile->h, &buf);
  22391. if( rc!=0 ){
  22392. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  22393. pFile->ctrlFlags |= UNIXFILE_WARNED;
  22394. return;
  22395. }
  22396. #warning " struct \"stat\" has no field \"st_nlink\""
  22397. #ifndef RT_USING_SQLITE
  22398. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  22399. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  22400. pFile->ctrlFlags |= UNIXFILE_WARNED;
  22401. return;
  22402. }
  22403. #endif
  22404. }
  22405. /*
  22406. ** This function performs the parts of the "close file" operation
  22407. ** common to all locking schemes. It closes the directory and file
  22408. ** handles, if they are valid, and sets all fields of the rtthreadFile
  22409. ** structure to 0.
  22410. **
  22411. ** It is *not* necessary to hold the mutex when this routine is called,
  22412. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  22413. ** vxworksReleaseFileId() routine.
  22414. */
  22415. static int closeRtthreadFile(sqlite3_file *id){
  22416. rtthreadFile *pFile = (rtthreadFile*)id;
  22417. if( pFile->h>=0 ){
  22418. robust_close(pFile, pFile->h, __LINE__);
  22419. pFile->h = -1;
  22420. }
  22421. OSTRACE(("CLOSE %-3d\n", pFile->h));
  22422. OpenCounter(-1);
  22423. memset(pFile, 0, sizeof(rtthreadFile));
  22424. return SQLITE_OK;
  22425. }
  22426. /************** End of the posix advisory lock implementation *****************
  22427. ******************************************************************************/
  22428. /******************************************************************************
  22429. ****************************** No-op Locking **********************************
  22430. **
  22431. ** Of the various locking implementations available, this is by far the
  22432. ** simplest: locking is ignored. No attempt is made to lock the database
  22433. ** file for reading or writing.
  22434. **
  22435. ** This locking mode is appropriate for use on read-only databases
  22436. ** (ex: databases that are burned into CD-ROM, for example.) It can
  22437. ** also be used if the application employs some external mechanism to
  22438. ** prevent simultaneous access of the same database by two or more
  22439. ** database connections. But there is a serious risk of database
  22440. ** corruption if this locking mode is used in situations where multiple
  22441. ** database connections are accessing the same database file at the same
  22442. ** time and one or more of those connections are writing.
  22443. */
  22444. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  22445. UNUSED_PARAMETER(NotUsed);
  22446. *pResOut = 0;
  22447. return SQLITE_OK;
  22448. }
  22449. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  22450. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  22451. return SQLITE_OK;
  22452. }
  22453. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  22454. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  22455. return SQLITE_OK;
  22456. }
  22457. /*
  22458. ** Close the file.
  22459. */
  22460. static int nolockClose(sqlite3_file *id) {
  22461. return closeRtthreadFile(id);
  22462. }
  22463. /******************* End of the no-op lock implementation *********************
  22464. ******************************************************************************/
  22465. /******************************************************************************
  22466. ************************* Begin dot-file Locking ******************************
  22467. **
  22468. ** The dotfile locking implementation uses the existence of separate lock
  22469. ** files (really a directory) to control access to the database. This works
  22470. ** on just about every filesystem imaginable. But there are serious downsides:
  22471. **
  22472. ** (1) There is zero concurrency. A single reader blocks all other
  22473. ** connections from reading or writing the database.
  22474. **
  22475. ** (2) An application crash or power loss can leave stale lock files
  22476. ** sitting around that need to be cleared manually.
  22477. **
  22478. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  22479. ** other locking strategy is available.
  22480. **
  22481. ** Dotfile locking works by creating a subdirectory in the same directory as
  22482. ** the database and with the same name but with a ".lock" extension added.
  22483. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  22484. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  22485. */
  22486. /*
  22487. ** The file suffix added to the data base filename in order to create the
  22488. ** lock directory.
  22489. */
  22490. #define DOTLOCK_SUFFIX ".lock"
  22491. /*
  22492. ** Only set the lastErrno if the error code is a real error and not
  22493. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  22494. */
  22495. #define IS_LOCK_ERROR(x) (((x) != SQLITE_OK) && ((x) != SQLITE_BUSY))
  22496. /*
  22497. ** This routine checks if there is a RESERVED lock held on the specified
  22498. ** file by this or any other process. If such a lock is held, set *pResOut
  22499. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22500. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22501. **
  22502. ** In dotfile locking, either a lock exists or it does not. So in this
  22503. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  22504. ** is held on the file and false if the file is unlocked.
  22505. */
  22506. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  22507. int rc = SQLITE_OK;
  22508. int reserved = 0;
  22509. rtthreadFile *pFile = (rtthreadFile*)id;
  22510. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22511. assert( pFile );
  22512. /* Check if a thread in this process holds such a lock */
  22513. if( pFile->eFileLock>SHARED_LOCK ){
  22514. /* Either this connection or some other connection in the same process
  22515. ** holds a lock on the file. No need to check further. */
  22516. reserved = 1;
  22517. }else{
  22518. /* The lock is held if and only if the lockfile exists */
  22519. const char *zLockFile = (const char*)pFile->lockingContext;
  22520. reserved = 0;
  22521. }
  22522. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  22523. *pResOut = reserved;
  22524. return rc;
  22525. }
  22526. /*
  22527. ** Lock the file with the lock specified by parameter eFileLock - one
  22528. ** of the following:
  22529. **
  22530. ** (1) SHARED_LOCK
  22531. ** (2) RESERVED_LOCK
  22532. ** (3) PENDING_LOCK
  22533. ** (4) EXCLUSIVE_LOCK
  22534. **
  22535. ** Sometimes when requesting one lock state, additional lock states
  22536. ** are inserted in between. The locking might fail on one of the later
  22537. ** transitions leaving the lock state different from what it started but
  22538. ** still short of its goal. The following chart shows the allowed
  22539. ** transitions and the inserted intermediate states:
  22540. **
  22541. ** UNLOCKED -> SHARED
  22542. ** SHARED -> RESERVED
  22543. ** SHARED -> (PENDING) -> EXCLUSIVE
  22544. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22545. ** PENDING -> EXCLUSIVE
  22546. **
  22547. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22548. ** routine to lower a locking level.
  22549. **
  22550. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  22551. ** But we track the other locking levels internally.
  22552. */
  22553. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  22554. rtthreadFile *pFile = (rtthreadFile*)id;
  22555. char *zLockFile = (char *)pFile->lockingContext;
  22556. int rc = SQLITE_OK;
  22557. /* If we have any lock, then the lock file already exists. All we have
  22558. ** to do is adjust our internal record of the lock level.
  22559. */
  22560. if( pFile->eFileLock > NO_LOCK ){
  22561. pFile->eFileLock = eFileLock;
  22562. return SQLITE_OK;
  22563. }
  22564. /* grab an exclusive lock */
  22565. rc = osMkdir(zLockFile, 0777);
  22566. if( rc<0 ){
  22567. /* failed to open/create the lock directory */
  22568. int tErrno = errno;
  22569. if( DFS_STATUS_EEXIST == tErrno ){
  22570. rc = SQLITE_BUSY;
  22571. } else {
  22572. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22573. if( IS_LOCK_ERROR(rc) ){
  22574. pFile->lastErrno = tErrno;
  22575. }
  22576. }
  22577. return rc;
  22578. }
  22579. /* got it, set the type and return ok */
  22580. pFile->eFileLock = eFileLock;
  22581. return rc;
  22582. }
  22583. /*
  22584. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  22585. ** must be either NO_LOCK or SHARED_LOCK.
  22586. **
  22587. ** If the locking level of the file descriptor is already at or below
  22588. ** the requested locking level, this routine is a no-op.
  22589. **
  22590. ** When the locking level reaches NO_LOCK, delete the lock file.
  22591. */
  22592. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  22593. rtthreadFile *pFile = (rtthreadFile*)id;
  22594. char *zLockFile = (char *)pFile->lockingContext;
  22595. int rc;
  22596. assert( pFile );
  22597. OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock,
  22598. pFile->eFileLock, rt_thread_self()->name ));
  22599. assert( eFileLock<=SHARED_LOCK );
  22600. /* no-op if possible */
  22601. if( pFile->eFileLock==eFileLock ){
  22602. return SQLITE_OK;
  22603. }
  22604. /* To downgrade to shared, simply update our internal notion of the
  22605. ** lock state. No need to mess with the file on disk.
  22606. */
  22607. if( eFileLock==SHARED_LOCK ){
  22608. pFile->eFileLock = SHARED_LOCK;
  22609. return SQLITE_OK;
  22610. }
  22611. /* To fully unlock the database, delete the lock file */
  22612. assert( eFileLock==NO_LOCK );
  22613. rc = osRmdir(zLockFile);
  22614. if( rc<0 && errno==DFS_STATUS_ENOTDIR ) rc = osUnlink(zLockFile);
  22615. if( rc<0 ){
  22616. int tErrno = errno;
  22617. rc = 0;
  22618. if( DFS_STATUS_ENOENT != tErrno ){
  22619. rc = SQLITE_IOERR_UNLOCK;
  22620. }
  22621. if( IS_LOCK_ERROR(rc) ){
  22622. pFile->lastErrno = tErrno;
  22623. }
  22624. return rc;
  22625. }
  22626. pFile->eFileLock = NO_LOCK;
  22627. return SQLITE_OK;
  22628. }
  22629. /*
  22630. ** Close a file. Make sure the lock has been released before closing.
  22631. */
  22632. static int dotlockClose(sqlite3_file *id) {
  22633. int rc = SQLITE_OK;
  22634. if( id ){
  22635. rtthreadFile *pFile = (rtthreadFile*)id;
  22636. dotlockUnlock(id, NO_LOCK);
  22637. sqlite3_free(pFile->lockingContext);
  22638. rc = closeRtthreadFile(id);
  22639. }
  22640. return rc;
  22641. }
  22642. /****************** End of the dot-file lock implementation *******************
  22643. ******************************************************************************/
  22644. /******************************************************************************
  22645. ************************** Begin flock Locking ********************************
  22646. **
  22647. ** Use the flock() system call to do file locking.
  22648. **
  22649. ** flock() locking is like dot-file locking in that the various
  22650. ** fine-grain locking levels supported by SQLite are collapsed into
  22651. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  22652. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  22653. ** still works when you do this, but concurrency is reduced since
  22654. ** only a single process can be reading the database at a time.
  22655. **
  22656. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  22657. ** compiling for VXWORKS.
  22658. */
  22659. #if SQLITE_ENABLE_LOCKING_STYLE
  22660. #warning "rtthread file lock not available"
  22661. /*
  22662. ** Retry flock() calls that fail with EINTR
  22663. */
  22664. static int robust_flock(int fd, int op){
  22665. int rc = 0;
  22666. return rc;
  22667. }
  22668. /*
  22669. ** This routine checks if there is a RESERVED lock held on the specified
  22670. ** file by this or any other process. If such a lock is held, set *pResOut
  22671. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  22672. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  22673. */
  22674. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  22675. int rc = SQLITE_OK;
  22676. int reserved = 0;
  22677. rtthreadFile *pFile = (rtthreadFile*)id;
  22678. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  22679. assert( pFile );
  22680. /* Check if a thread in this process holds such a lock */
  22681. if( pFile->eFileLock>SHARED_LOCK ){
  22682. reserved = 1;
  22683. }
  22684. /* Otherwise see if some other process holds it. */
  22685. if( !reserved ){
  22686. /* attempt to get the lock */
  22687. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  22688. if( !lrc ){
  22689. /* got the lock, unlock it */
  22690. lrc = robust_flock(pFile->h, LOCK_UN);
  22691. if ( lrc ) {
  22692. int tErrno = errno;
  22693. /* unlock failed with an error */
  22694. lrc = SQLITE_IOERR_UNLOCK;
  22695. if( IS_LOCK_ERROR(lrc) ){
  22696. pFile->lastErrno = tErrno;
  22697. rc = lrc;
  22698. }
  22699. }
  22700. } else {
  22701. int tErrno = errno;
  22702. reserved = 1;
  22703. /* someone else might have it reserved */
  22704. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22705. if( IS_LOCK_ERROR(lrc) ){
  22706. pFile->lastErrno = tErrno;
  22707. rc = lrc;
  22708. }
  22709. }
  22710. }
  22711. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  22712. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22713. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  22714. rc = SQLITE_OK;
  22715. reserved=1;
  22716. }
  22717. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22718. *pResOut = reserved;
  22719. return rc;
  22720. }
  22721. /*
  22722. ** Lock the file with the lock specified by parameter eFileLock - one
  22723. ** of the following:
  22724. **
  22725. ** (1) SHARED_LOCK
  22726. ** (2) RESERVED_LOCK
  22727. ** (3) PENDING_LOCK
  22728. ** (4) EXCLUSIVE_LOCK
  22729. **
  22730. ** Sometimes when requesting one lock state, additional lock states
  22731. ** are inserted in between. The locking might fail on one of the later
  22732. ** transitions leaving the lock state different from what it started but
  22733. ** still short of its goal. The following chart shows the allowed
  22734. ** transitions and the inserted intermediate states:
  22735. **
  22736. ** UNLOCKED -> SHARED
  22737. ** SHARED -> RESERVED
  22738. ** SHARED -> (PENDING) -> EXCLUSIVE
  22739. ** RESERVED -> (PENDING) -> EXCLUSIVE
  22740. ** PENDING -> EXCLUSIVE
  22741. **
  22742. ** flock() only really support EXCLUSIVE locks. We track intermediate
  22743. ** lock states in the sqlite3_file structure, but all locks SHARED or
  22744. ** above are really EXCLUSIVE locks and exclude all other processes from
  22745. ** access the file.
  22746. **
  22747. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  22748. ** routine to lower a locking level.
  22749. */
  22750. static int flockLock(sqlite3_file *id, int eFileLock) {
  22751. int rc = SQLITE_OK;
  22752. rtthreadFile *pFile = (rtthreadFile*)id;
  22753. assert( pFile );
  22754. /* if we already have a lock, it is exclusive.
  22755. ** Just adjust level and punt on outta here. */
  22756. if (pFile->eFileLock > NO_LOCK) {
  22757. pFile->eFileLock = eFileLock;
  22758. return SQLITE_OK;
  22759. }
  22760. /* grab an exclusive lock */
  22761. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  22762. int tErrno = errno;
  22763. /* didn't get, must be busy */
  22764. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  22765. if( IS_LOCK_ERROR(rc) ){
  22766. pFile->lastErrno = tErrno;
  22767. }
  22768. } else {
  22769. /* got it, set the type and return ok */
  22770. pFile->eFileLock = eFileLock;
  22771. }
  22772. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  22773. rc==SQLITE_OK ? "ok" : "failed"));
  22774. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22775. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  22776. rc = SQLITE_BUSY;
  22777. }
  22778. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22779. return rc;
  22780. }
  22781. /*
  22782. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  22783. ** must be either NO_LOCK or SHARED_LOCK.
  22784. **
  22785. ** If the locking level of the file descriptor is already at or below
  22786. ** the requested locking level, this routine is a no-op.
  22787. */
  22788. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  22789. rtthreadFile *pFile = (rtthreadFile*)id;
  22790. assert( pFile );
  22791. OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock,
  22792. pFile->eFileLock, rt_thread_self()->name));
  22793. assert( eFileLock<=SHARED_LOCK );
  22794. /* no-op if possible */
  22795. if( pFile->eFileLock==eFileLock ){
  22796. return SQLITE_OK;
  22797. }
  22798. /* shared can just be set because we always have an exclusive */
  22799. if (eFileLock==SHARED_LOCK) {
  22800. pFile->eFileLock = eFileLock;
  22801. return SQLITE_OK;
  22802. }
  22803. /* no, really, unlock. */
  22804. if( robust_flock(pFile->h, LOCK_UN) ){
  22805. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  22806. return SQLITE_OK;
  22807. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  22808. return SQLITE_IOERR_UNLOCK;
  22809. }else{
  22810. pFile->eFileLock = NO_LOCK;
  22811. return SQLITE_OK;
  22812. }
  22813. }
  22814. /*
  22815. ** Close a file.
  22816. */
  22817. static int flockClose(sqlite3_file *id) {
  22818. int rc = SQLITE_OK;
  22819. if( id ){
  22820. flockUnlock(id, NO_LOCK);
  22821. rc = closeRtthreadFile(id);
  22822. }
  22823. return rc;
  22824. }
  22825. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  22826. /******************* End of the flock lock implementation *********************
  22827. ******************************************************************************/
  22828. /******************************************************************************
  22829. **************** Non-locking sqlite3_file methods *****************************
  22830. **
  22831. ** The next division contains implementations for all methods of the
  22832. ** sqlite3_file object other than the locking methods. The locking
  22833. ** methods were defined in divisions above (one locking method per
  22834. ** division). Those methods that are common to all locking modes
  22835. ** are gather together into this division.
  22836. */
  22837. /*
  22838. ** Seek to the offset passed as the second argument, then read cnt
  22839. ** bytes into pBuf. Return the number of bytes actually read.
  22840. **
  22841. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  22842. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  22843. ** one system to another. Since SQLite does not define USE_PREAD
  22844. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  22845. ** See tickets #2741 and #2681.
  22846. **
  22847. ** To avoid stomping the errno value on a failed read the lastErrno value
  22848. ** is set before returning.
  22849. */
  22850. static int seekAndRead(rtthreadFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  22851. int got;
  22852. int prior = 0;
  22853. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  22854. i64 newOffset;
  22855. #endif
  22856. TIMER_START;
  22857. assert( cnt==(cnt&0x1ffff) );
  22858. assert( id->h>2 );
  22859. cnt &= 0x1ffff;
  22860. do{
  22861. #if defined(USE_PREAD)
  22862. #error "rtthread pread not support"
  22863. got = osPread(id->h, pBuf, cnt, offset);
  22864. SimulateIOError( got = -1 );
  22865. #elif defined(USE_PREAD64)
  22866. #error "rtthread pread64 not support"
  22867. got = osPread64(id->h, pBuf, cnt, offset);
  22868. SimulateIOError( got = -1 );
  22869. #else
  22870. newOffset = lseek(id->h, offset, SEEK_SET);
  22871. SimulateIOError( newOffset-- );
  22872. if( newOffset!=offset ){
  22873. if( newOffset == -1 ){
  22874. ((rtthreadFile*)id)->lastErrno = errno;
  22875. }else{
  22876. ((rtthreadFile*)id)->lastErrno = 0;
  22877. }
  22878. return -1;
  22879. }
  22880. got = osRead(id->h, pBuf, cnt);
  22881. #endif
  22882. if( got==cnt ) break;
  22883. if( got<0 ){
  22884. if( errno==EINTR ){ got = 1; continue; }
  22885. prior = 0;
  22886. ((rtthreadFile*)id)->lastErrno = errno;
  22887. break;
  22888. }else if( got>0 ){
  22889. cnt -= got;
  22890. offset += got;
  22891. prior += got;
  22892. pBuf = (void*)(got + (char*)pBuf);
  22893. }
  22894. }while( got>0 );
  22895. TIMER_END;
  22896. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  22897. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  22898. return got+prior;
  22899. }
  22900. /*
  22901. ** Read data from a file into a buffer. Return SQLITE_OK if all
  22902. ** bytes were read successfully and SQLITE_IOERR if anything goes
  22903. ** wrong.
  22904. */
  22905. static int rtthreadRead(
  22906. sqlite3_file *id,
  22907. void *pBuf,
  22908. int amt,
  22909. sqlite3_int64 offset
  22910. ){
  22911. rtthreadFile *pFile = (rtthreadFile *)id;
  22912. int got;
  22913. assert( id );
  22914. assert( offset>=0 );
  22915. assert( amt>0 );
  22916. got = seekAndRead(pFile, offset, pBuf, amt);
  22917. if( got==amt ){
  22918. return SQLITE_OK;
  22919. }else if( got<0 ){
  22920. /* lastErrno set by seekAndRead */
  22921. return SQLITE_IOERR_READ;
  22922. }else{
  22923. pFile->lastErrno = 0; /* not a system error */
  22924. /* Unread parts of the buffer must be zero-filled */
  22925. memset(&((char*)pBuf)[got], 0, amt-got);
  22926. return SQLITE_IOERR_SHORT_READ;
  22927. }
  22928. }
  22929. /*
  22930. ** Attempt to seek the file-descriptor passed as the first argument to
  22931. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  22932. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  22933. ** return the actual number of bytes written (which may be less than
  22934. ** nBuf).
  22935. */
  22936. static int seekAndWriteFd(
  22937. int fd, /* File descriptor to write to */
  22938. i64 iOff, /* File offset to begin writing at */
  22939. const void *pBuf, /* Copy data from this buffer to the file */
  22940. int nBuf, /* Size of buffer pBuf in bytes */
  22941. int *piErrno /* OUT: Error number if error occurs */
  22942. ){
  22943. int rc = 0; /* Value returned by system call */
  22944. assert( nBuf==(nBuf&0x1ffff) );
  22945. assert( fd>2 );
  22946. nBuf &= 0x1ffff;
  22947. TIMER_START;
  22948. #if defined(USE_PREAD)
  22949. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  22950. #elif defined(USE_PREAD64)
  22951. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  22952. #else
  22953. do{
  22954. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  22955. SimulateIOError( iSeek-- );
  22956. if( iSeek!=iOff ){
  22957. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  22958. return -1;
  22959. }
  22960. rc = osWrite(fd, pBuf, nBuf);
  22961. }while( rc<0 && errno==EINTR );
  22962. #endif
  22963. TIMER_END;
  22964. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  22965. if( rc<0 && piErrno ) *piErrno = errno;
  22966. return rc;
  22967. }
  22968. /*
  22969. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  22970. ** Return the number of bytes actually read. Update the offset.
  22971. **
  22972. ** To avoid stomping the errno value on a failed write the lastErrno value
  22973. ** is set before returning.
  22974. */
  22975. static int seekAndWrite(rtthreadFile *id, i64 offset, const void *pBuf, int cnt){
  22976. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  22977. }
  22978. /*
  22979. ** Write data from a buffer into a file. Return SQLITE_OK on success
  22980. ** or some other error code on failure.
  22981. */
  22982. static int rtthreadWrite(
  22983. sqlite3_file *id,
  22984. const void *pBuf,
  22985. int amt,
  22986. sqlite3_int64 offset
  22987. ){
  22988. rtthreadFile *pFile = (rtthreadFile*)id;
  22989. int wrote = 0;
  22990. assert( id );
  22991. assert( amt>0 );
  22992. #ifdef SQLITE_DEBUG
  22993. /* If we are doing a normal write to a database file (as opposed to
  22994. ** doing a hot-journal rollback or a write to some file other than a
  22995. ** normal database file) then record the fact that the database
  22996. ** has changed. If the transaction counter is modified, record that
  22997. ** fact too.
  22998. */
  22999. if( pFile->inNormalWrite ){
  23000. pFile->dbUpdate = 1; /* The database has been modified */
  23001. if( offset<=24 && offset+amt>=27 ){
  23002. int rc;
  23003. char oldCntr[4];
  23004. SimulateIOErrorBenign(1);
  23005. rc = seekAndRead(pFile, 24, oldCntr, 4);
  23006. SimulateIOErrorBenign(0);
  23007. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  23008. pFile->transCntrChng = 1; /* The transaction counter has changed */
  23009. }
  23010. }
  23011. }
  23012. #endif
  23013. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  23014. amt -= wrote;
  23015. offset += wrote;
  23016. pBuf = &((char*)pBuf)[wrote];
  23017. }
  23018. SimulateIOError(( wrote=(-1), amt=1 ));
  23019. SimulateDiskfullError(( wrote=0, amt=1 ));
  23020. if( amt>0 ){
  23021. if( wrote<0 && pFile->lastErrno!=DFS_STATUS_ENOSPC ){
  23022. /* lastErrno set by seekAndWrite */
  23023. return SQLITE_IOERR_WRITE;
  23024. }else{
  23025. pFile->lastErrno = 0; /* not a system error */
  23026. return SQLITE_FULL;
  23027. }
  23028. }
  23029. return SQLITE_OK;
  23030. }
  23031. #ifdef SQLITE_TEST
  23032. /*
  23033. ** Count the number of fullsyncs and normal syncs. This is used to test
  23034. ** that syncs and fullsyncs are occurring at the right times.
  23035. */
  23036. SQLITE_API int sqlite3_sync_count = 0;
  23037. SQLITE_API int sqlite3_fullsync_count = 0;
  23038. #endif
  23039. /*
  23040. ** We do not trust systems to provide a working fdatasync(). Some do.
  23041. ** Others do no. To be safe, we will stick with the (slightly slower)
  23042. ** fsync(). If you know that your system does support fdatasync() correctly,
  23043. ** then simply compile with -Dfdatasync=fdatasync
  23044. */
  23045. #if !defined(fdatasync)
  23046. #include "dfs.h"
  23047. #include "dfs_file.h"
  23048. int fdatasync(fd)
  23049. {
  23050. struct dfs_fd *dfs_fd;
  23051. dfs_fd = fd_get(fd);
  23052. return dfs_file_flush(dfs_fd);
  23053. }
  23054. #endif
  23055. /*
  23056. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  23057. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  23058. ** only available on Mac OS X. But that could change.
  23059. */
  23060. #ifdef F_FULLFSYNC
  23061. # define HAVE_FULLFSYNC 0
  23062. #endif
  23063. /*
  23064. ** The fsync() system call does not work as advertised on many
  23065. ** unix systems. The following procedure is an attempt to make
  23066. ** it work better.
  23067. **
  23068. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  23069. ** for testing when we want to run through the test suite quickly.
  23070. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  23071. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  23072. ** or power failure will likely corrupt the database file.
  23073. **
  23074. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  23075. ** The idea behind dataOnly is that it should only write the file content
  23076. ** to disk, not the inode. We only set dataOnly if the file size is
  23077. ** unchanged since the file size is part of the inode. However,
  23078. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  23079. ** file size has changed. The only real difference between fdatasync()
  23080. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  23081. ** inode if the mtime or owner or other inode attributes have changed.
  23082. ** We only care about the file size, not the other file attributes, so
  23083. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  23084. ** So, we always use fdatasync() if it is available, regardless of
  23085. ** the value of the dataOnly flag.
  23086. */
  23087. static int full_fsync(int fd, int fullSync, int dataOnly){
  23088. int rc;
  23089. /* The following "ifdef/elif/else/" block has the same structure as
  23090. ** the one below. It is replicated here solely to avoid cluttering
  23091. ** up the real code with the UNUSED_PARAMETER() macros.
  23092. */
  23093. #ifdef SQLITE_NO_SYNC
  23094. UNUSED_PARAMETER(fd);
  23095. UNUSED_PARAMETER(fullSync);
  23096. UNUSED_PARAMETER(dataOnly);
  23097. #elif HAVE_FULLFSYNC
  23098. UNUSED_PARAMETER(dataOnly);
  23099. #else
  23100. UNUSED_PARAMETER(fullSync);
  23101. UNUSED_PARAMETER(dataOnly);
  23102. #endif
  23103. /* Record the number of times that we do a normal fsync() and
  23104. ** FULLSYNC. This is used during testing to verify that this procedure
  23105. ** gets called with the correct arguments.
  23106. */
  23107. #ifdef SQLITE_TEST
  23108. if( fullSync ) sqlite3_fullsync_count++;
  23109. sqlite3_sync_count++;
  23110. #endif
  23111. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  23112. ** no-op
  23113. */
  23114. #ifdef SQLITE_NO_SYNC
  23115. rc = SQLITE_OK;
  23116. #elif HAVE_FULLFSYNC
  23117. #error "rtthread not support FULLFSYNC"
  23118. #else
  23119. rc = fdatasync(fd);
  23120. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  23121. return rc;
  23122. }
  23123. /*
  23124. ** Make sure all writes to a particular file are committed to disk.
  23125. **
  23126. ** If dataOnly==0 then both the file itself and its metadata (file
  23127. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  23128. ** file data is synced.
  23129. **
  23130. ** Under Rtthread, also make sure that the directory entry for the file
  23131. ** has been created by fsync-ing the directory that contains the file.
  23132. ** If we do not do this and we encounter a power failure, the directory
  23133. ** entry for the journal might not exist after we reboot. The next
  23134. ** SQLite to access the file will not know that the journal exists (because
  23135. ** the directory entry for the journal was never created) and the transaction
  23136. ** will not roll back - possibly leading to database corruption.
  23137. */
  23138. static int rtthreadSync(sqlite3_file *id, int flags){
  23139. int rc;
  23140. rtthreadFile *pFile = (rtthreadFile*)id;
  23141. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  23142. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  23143. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  23144. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  23145. || (flags&0x0F)==SQLITE_SYNC_FULL
  23146. );
  23147. /* Rtthread cannot, but some systems may return SQLITE_FULL from here. This
  23148. ** line is to test that doing so does not cause any problems.
  23149. */
  23150. SimulateDiskfullError( return SQLITE_FULL );
  23151. assert( pFile );
  23152. OSTRACE(("SYNC %-3d\n", pFile->h));
  23153. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  23154. SimulateIOError( rc=1 );
  23155. if( rc ){
  23156. pFile->lastErrno = errno;
  23157. return rtthreadLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  23158. }
  23159. /* Also fsync the directory containing the file if the DIRSYNC flag
  23160. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  23161. ** are unable to fsync a directory, so ignore errors on the fsync.
  23162. */
  23163. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  23164. int dirfd;
  23165. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  23166. HAVE_FULLFSYNC, isFullsync));
  23167. rc = osOpenDirectory(pFile->zPath, &dirfd);
  23168. if( rc==SQLITE_OK && dirfd>=0 ){
  23169. full_fsync(dirfd, 0, 0);
  23170. robust_close(pFile, dirfd, __LINE__);
  23171. }else if( rc==SQLITE_CANTOPEN ){
  23172. rc = SQLITE_OK;
  23173. }
  23174. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  23175. }
  23176. return rc;
  23177. }
  23178. /*
  23179. ** Truncate an open file to a specified size
  23180. */
  23181. static int rtthreadTruncate(sqlite3_file *id, i64 nByte){
  23182. rtthreadFile *pFile = (rtthreadFile *)id;
  23183. int rc;
  23184. assert( pFile );
  23185. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  23186. /* If the user has configured a chunk-size for this file, truncate the
  23187. ** file so that it consists of an integer number of chunks (i.e. the
  23188. ** actual file size after the operation may be larger than the requested
  23189. ** size).
  23190. */
  23191. if( pFile->szChunk>0 ){
  23192. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  23193. }
  23194. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  23195. if( rc ){
  23196. pFile->lastErrno = errno;
  23197. return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  23198. }else{
  23199. #ifdef SQLITE_DEBUG
  23200. /* If we are doing a normal write to a database file (as opposed to
  23201. ** doing a hot-journal rollback or a write to some file other than a
  23202. ** normal database file) and we truncate the file to zero length,
  23203. ** that effectively updates the change counter. This might happen
  23204. ** when restoring a database using the backup API from a zero-length
  23205. ** source.
  23206. */
  23207. if( pFile->inNormalWrite && nByte==0 ){
  23208. pFile->transCntrChng = 1;
  23209. }
  23210. #endif
  23211. return SQLITE_OK;
  23212. }
  23213. }
  23214. /*
  23215. ** Determine the current size of a file in bytes
  23216. */
  23217. static int rtthreadFileSize(sqlite3_file *id, i64 *pSize){
  23218. int rc;
  23219. struct stat buf;
  23220. assert( id );
  23221. rc = osFstat(((rtthreadFile*)id)->h, &buf);
  23222. SimulateIOError( rc=1 );
  23223. if( rc!=0 ){
  23224. ((rtthreadFile*)id)->lastErrno = errno;
  23225. return SQLITE_IOERR_FSTAT;
  23226. }
  23227. *pSize = buf.st_size;
  23228. /* When opening a zero-size database, the findInodeInfo() procedure
  23229. ** writes a single byte into that file in order to work around a bug
  23230. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  23231. ** layers, we need to report this file size as zero even though it is
  23232. ** really 1. Ticket #3260.
  23233. */
  23234. if( *pSize==1 ) *pSize = 0;
  23235. return SQLITE_OK;
  23236. }
  23237. /*
  23238. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  23239. ** file-control operation. Enlarge the database to nBytes in size
  23240. ** (rounded up to the next chunk-size). If the database is already
  23241. ** nBytes or larger, this routine is a no-op.
  23242. */
  23243. static int fcntlSizeHint(rtthreadFile *pFile, i64 nByte){
  23244. if( pFile->szChunk>0 ){
  23245. i64 nSize; /* Required file size */
  23246. struct stat buf; /* Used to hold return values of fstat() */
  23247. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  23248. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  23249. if( nSize>(i64)buf.st_size ){
  23250. /* If the OS does not have posix_fallocate(), fake it. First use
  23251. ** ftruncate() to set the file size, then write a single byte to
  23252. ** the last byte in each block within the extended region. This
  23253. ** is the same technique used by glibc to implement posix_fallocate()
  23254. ** on systems that do not have a real fallocate() system call.
  23255. */
  23256. int nBlk = buf.st_blksize; /* File-system block size */
  23257. i64 iWrite; /* Next offset to write to */
  23258. if( robust_ftruncate(pFile->h, nSize) ){
  23259. pFile->lastErrno = errno;
  23260. return rtthreadLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  23261. }
  23262. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  23263. while( iWrite<nSize ){
  23264. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  23265. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  23266. iWrite += nBlk;
  23267. }
  23268. }
  23269. }
  23270. return SQLITE_OK;
  23271. }
  23272. /*
  23273. ** If *pArg is inititially negative then this is a query. Set *pArg to
  23274. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  23275. **
  23276. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  23277. */
  23278. static void rtthreadModeBit(rtthreadFile *pFile, unsigned char mask, int *pArg){
  23279. if( *pArg<0 ){
  23280. *pArg = (pFile->ctrlFlags & mask)!=0;
  23281. }else if( (*pArg)==0 ){
  23282. pFile->ctrlFlags &= ~mask;
  23283. }else{
  23284. pFile->ctrlFlags |= mask;
  23285. }
  23286. }
  23287. /* Forward declaration */
  23288. static int rtthreadGetTempname(int nBuf, char *zBuf);
  23289. /*
  23290. ** Information and control of an open file handle.
  23291. */
  23292. static int rtthreadFileControl(sqlite3_file *id, int op, void *pArg){
  23293. rtthreadFile *pFile = (rtthreadFile*)id;
  23294. switch( op ){
  23295. case SQLITE_FCNTL_LOCKSTATE: {
  23296. *(int*)pArg = pFile->eFileLock;
  23297. return SQLITE_OK;
  23298. }
  23299. case SQLITE_LAST_ERRNO: {
  23300. *(int*)pArg = pFile->lastErrno;
  23301. return SQLITE_OK;
  23302. }
  23303. case SQLITE_FCNTL_CHUNK_SIZE: {
  23304. pFile->szChunk = *(int *)pArg;
  23305. return SQLITE_OK;
  23306. }
  23307. case SQLITE_FCNTL_SIZE_HINT: {
  23308. int rc;
  23309. SimulateIOErrorBenign(1);
  23310. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  23311. SimulateIOErrorBenign(0);
  23312. return rc;
  23313. }
  23314. case SQLITE_FCNTL_PERSIST_WAL: {
  23315. rtthreadModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  23316. return SQLITE_OK;
  23317. }
  23318. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  23319. rtthreadModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  23320. return SQLITE_OK;
  23321. }
  23322. case SQLITE_FCNTL_VFSNAME: {
  23323. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  23324. return SQLITE_OK;
  23325. }
  23326. case SQLITE_FCNTL_TEMPFILENAME: {
  23327. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  23328. if( zTFile ){
  23329. rtthreadGetTempname(pFile->pVfs->mxPathname, zTFile);
  23330. *(char**)pArg = zTFile;
  23331. }
  23332. return SQLITE_OK;
  23333. }
  23334. #ifdef SQLITE_DEBUG
  23335. /* The pager calls this method to signal that it has done
  23336. ** a rollback and that the database is therefore unchanged and
  23337. ** it hence it is OK for the transaction change counter to be
  23338. ** unchanged.
  23339. */
  23340. case SQLITE_FCNTL_DB_UNCHANGED: {
  23341. ((rtthreadFile*)id)->dbUpdate = 0;
  23342. return SQLITE_OK;
  23343. }
  23344. #endif
  23345. }
  23346. return SQLITE_NOTFOUND;
  23347. }
  23348. /*
  23349. ** Return the sector size in bytes of the underlying block device for
  23350. ** the specified file. This is almost always 512 bytes, but may be
  23351. ** larger for some devices.
  23352. **
  23353. ** SQLite code assumes this function cannot fail. It also assumes that
  23354. ** if two files are created in the same file-system directory (i.e.
  23355. ** a database and its journal file) that the sector size will be the
  23356. ** same for both.
  23357. */
  23358. static int rtthreadSectorSize(sqlite3_file *NotUsed){
  23359. UNUSED_PARAMETER(NotUsed);
  23360. return SQLITE_DEFAULT_SECTOR_SIZE;
  23361. }
  23362. /*
  23363. ** Return the device characteristics for the file.
  23364. **
  23365. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  23366. ** However, that choice is contraversial since technically the underlying
  23367. ** file system does not always provide powersafe overwrites. (In other
  23368. ** words, after a power-loss event, parts of the file that were never
  23369. ** written might end up being altered.) However, non-PSOW behavior is very,
  23370. ** very rare. And asserting PSOW makes a large reduction in the amount
  23371. ** of required I/O for journaling, since a lot of padding is eliminated.
  23372. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  23373. ** available to turn it off and URI query parameter available to turn it off.
  23374. */
  23375. static int rtthreadDeviceCharacteristics(sqlite3_file *id){
  23376. rtthreadFile *p = (rtthreadFile*)id;
  23377. int rc = 0;
  23378. if( p->ctrlFlags & UNIXFILE_PSOW ){
  23379. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  23380. }
  23381. return rc;
  23382. }
  23383. #ifndef SQLITE_OMIT_WAL
  23384. # error "WAL mode requires not support from the rt-thread, compile\
  23385. with SQLITE_OMIT_WAL."
  23386. #else
  23387. # define rtthreadShmMap 0
  23388. # define rtthreadShmLock 0
  23389. # define rtthreadShmBarrier 0
  23390. # define rtthreadShmUnmap 0
  23391. #endif /* #ifndef SQLITE_OMIT_WAL */
  23392. #if SQLITE_MAX_MMAP_SIZE>0
  23393. #error "rtthread not spportt mmap"
  23394. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  23395. /*
  23396. ** If possible, return a pointer to a mapping of file fd starting at offset
  23397. ** iOff. The mapping must be valid for at least nAmt bytes.
  23398. **
  23399. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  23400. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  23401. ** Finally, if an error does occur, return an SQLite error code. The final
  23402. ** value of *pp is undefined in this case.
  23403. **
  23404. ** If this function does return a pointer, the caller must eventually
  23405. ** release the reference by calling unixUnfetch().
  23406. */
  23407. static int rtthreadFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  23408. *pp = 0;
  23409. return SQLITE_OK;
  23410. }
  23411. /*
  23412. ** If the third argument is non-NULL, then this function releases a
  23413. ** reference obtained by an earlier call to unixFetch(). The second
  23414. ** argument passed to this function must be the same as the corresponding
  23415. ** argument that was passed to the unixFetch() invocation.
  23416. **
  23417. ** Or, if the third argument is NULL, then this function is being called
  23418. ** to inform the VFS layer that, according to POSIX, any existing mapping
  23419. ** may now be invalid and should be unmapped.
  23420. */
  23421. static int rtthreadUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  23422. rtthreadFile *pFd = (rtthreadFile *)fd; /* The underlying database file */
  23423. UNUSED_PARAMETER(iOff);
  23424. return SQLITE_OK;
  23425. }
  23426. /*
  23427. ** Here ends the implementation of all sqlite3_file methods.
  23428. **
  23429. ********************** End sqlite3_file Methods *******************************
  23430. ******************************************************************************/
  23431. /*
  23432. ** This division contains definitions of sqlite3_io_methods objects that
  23433. ** implement various file locking strategies. It also contains definitions
  23434. ** of "finder" functions. A finder-function is used to locate the appropriate
  23435. ** sqlite3_io_methods object for a particular database file. The pAppData
  23436. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  23437. ** the correct finder-function for that VFS.
  23438. **
  23439. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  23440. ** object. The only interesting finder-function is autolockIoFinder, which
  23441. ** looks at the filesystem type and tries to guess the best locking
  23442. ** strategy from that.
  23443. **
  23444. ** For finder-funtion F, two objects are created:
  23445. **
  23446. ** (1) The real finder-function named "FImpt()".
  23447. **
  23448. ** (2) A constant pointer to this function named just "F".
  23449. **
  23450. **
  23451. ** A pointer to the F pointer is used as the pAppData value for VFS
  23452. ** objects. We have to do this instead of letting pAppData point
  23453. ** directly at the finder-function since C90 rules prevent a void*
  23454. ** from be cast into a function pointer.
  23455. **
  23456. **
  23457. ** Each instance of this macro generates two objects:
  23458. **
  23459. ** * A constant sqlite3_io_methods object call METHOD that has locking
  23460. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  23461. **
  23462. ** * An I/O method finder function called FINDER that returns a pointer
  23463. ** to the METHOD object in the previous bullet.
  23464. */
  23465. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  23466. static const sqlite3_io_methods METHOD = { \
  23467. VERSION, /* iVersion */ \
  23468. CLOSE, /* xClose */ \
  23469. rtthreadRead, /* xRead */ \
  23470. rtthreadWrite, /* xWrite */ \
  23471. rtthreadTruncate, /* xTruncate */ \
  23472. rtthreadSync, /* xSync */ \
  23473. rtthreadFileSize, /* xFileSize */ \
  23474. LOCK, /* xLock */ \
  23475. UNLOCK, /* xUnlock */ \
  23476. CKLOCK, /* xCheckReservedLock */ \
  23477. rtthreadFileControl, /* xFileControl */ \
  23478. rtthreadSectorSize, /* xSectorSize */ \
  23479. rtthreadDeviceCharacteristics, /* xDeviceCapabilities */ \
  23480. rtthreadShmMap, /* xShmMap */ \
  23481. rtthreadShmLock, /* xShmLock */ \
  23482. rtthreadShmBarrier, /* xShmBarrier */ \
  23483. rtthreadShmUnmap, /* xShmUnmap */ \
  23484. rtthreadFetch, /* xFetch */ \
  23485. rtthreadUnfetch, /* xUnfetch */ \
  23486. }; \
  23487. static const sqlite3_io_methods *FINDER##Impl(const char *z, rtthreadFile *p){ \
  23488. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  23489. return &METHOD; \
  23490. } \
  23491. static const sqlite3_io_methods *(*const FINDER)(const char*,rtthreadFile *p) \
  23492. = FINDER##Impl;
  23493. /*
  23494. ** Here are all of the sqlite3_io_methods objects for each of the
  23495. ** locking strategies. Functions that return pointers to these methods
  23496. ** are also created.
  23497. */
  23498. IOMETHODS(
  23499. nolockIoFinder, /* Finder function name */
  23500. nolockIoMethods, /* sqlite3_io_methods object name */
  23501. 1, /* shared memory is disabled */
  23502. nolockClose, /* xClose method */
  23503. nolockLock, /* xLock method */
  23504. nolockUnlock, /* xUnlock method */
  23505. nolockCheckReservedLock /* xCheckReservedLock method */
  23506. )
  23507. IOMETHODS(
  23508. dotlockIoFinder, /* Finder function name */
  23509. dotlockIoMethods, /* sqlite3_io_methods object name */
  23510. 1, /* shared memory is disabled */
  23511. dotlockClose, /* xClose method */
  23512. dotlockLock, /* xLock method */
  23513. dotlockUnlock, /* xUnlock method */
  23514. dotlockCheckReservedLock /* xCheckReservedLock method */
  23515. )
  23516. #if SQLITE_ENABLE_LOCKING_STYLE
  23517. IOMETHODS(
  23518. flockIoFinder, /* Finder function name */
  23519. flockIoMethods, /* sqlite3_io_methods object name */
  23520. 1, /* shared memory is disabled */
  23521. flockClose, /* xClose method */
  23522. flockLock, /* xLock method */
  23523. flockUnlock, /* xUnlock method */
  23524. flockCheckReservedLock /* xCheckReservedLock method */
  23525. )
  23526. #endif
  23527. /*
  23528. ** An abstract type for a pointer to a IO method finder function:
  23529. */
  23530. typedef const sqlite3_io_methods *(*finder_type)(const char*,rtthreadFile*);
  23531. /****************************************************************************
  23532. **************************** sqlite3_vfs methods ****************************
  23533. **
  23534. ** This division contains the implementation of methods on the
  23535. ** sqlite3_vfs object.
  23536. */
  23537. /*
  23538. ** Initialize the contents of the rtthreadFile structure pointed to by pId.
  23539. */
  23540. static int fillInRtthreadFile(
  23541. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23542. int h, /* Open file descriptor of file being opened */
  23543. sqlite3_file *pId, /* Write to the rtthreadFile structure here */
  23544. const char *zFilename, /* Name of the file being opened */
  23545. int ctrlFlags /* Zero or more UNIXFILE_* values */
  23546. ){
  23547. const sqlite3_io_methods *pLockingStyle;
  23548. rtthreadFile *pNew = (rtthreadFile *)pId;
  23549. int rc = SQLITE_OK;
  23550. assert( pNew->pInode==NULL );
  23551. /* Usually the path zFilename should not be a relative pathname. The
  23552. ** exception is when opening the proxy "conch" file in builds that
  23553. ** include the special Apple locking styles.
  23554. */
  23555. assert( zFilename==0 || zFilename[0]=='/' );
  23556. /* No locking occurs in temporary files */
  23557. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  23558. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  23559. pNew->h = h;
  23560. pNew->pVfs = pVfs;
  23561. pNew->zPath = zFilename;
  23562. pNew->ctrlFlags = (u8)ctrlFlags;
  23563. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  23564. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  23565. pNew->ctrlFlags |= UNIXFILE_PSOW;
  23566. }
  23567. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  23568. pNew->ctrlFlags |= UNIXFILE_EXCL;
  23569. }
  23570. if( ctrlFlags & UNIXFILE_NOLOCK ){
  23571. pLockingStyle = &nolockIoMethods;
  23572. }else{
  23573. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  23574. #if SQLITE_ENABLE_LOCKING_STYLE
  23575. /* Cache zFilename in the locking context (AFP and dotlock override) for
  23576. ** proxyLock activation is possible (remote proxy is based on db name)
  23577. ** zFilename remains valid until file is closed, to support */
  23578. pNew->lockingContext = (void*)zFilename;
  23579. #endif
  23580. }
  23581. if( pLockingStyle == &dotlockIoMethods ){
  23582. /* Dotfile locking uses the file path so it needs to be included in
  23583. ** the dotlockLockingContext
  23584. */
  23585. char *zLockFile;
  23586. int nFilename;
  23587. assert( zFilename!=0 );
  23588. nFilename = (int)strlen(zFilename) + 6;
  23589. zLockFile = (char *)sqlite3_malloc(nFilename);
  23590. if( zLockFile==0 ){
  23591. rc = SQLITE_NOMEM;
  23592. }else{
  23593. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  23594. }
  23595. pNew->lockingContext = zLockFile;
  23596. }
  23597. pNew->lastErrno = 0;
  23598. if( rc!=SQLITE_OK ){
  23599. if( h>=0 ) robust_close(pNew, h, __LINE__);
  23600. }else{
  23601. pNew->pMethod = pLockingStyle;
  23602. OpenCounter(+1);
  23603. verifyDbFile(pNew);
  23604. }
  23605. return rc;
  23606. }
  23607. /*
  23608. ** Return the name of a directory in which to put temporary files.
  23609. ** If no suitable temporary file directory can be found, return NULL.
  23610. */
  23611. static const char* rtthreadTempFileDir(void){
  23612. static const char *azDirs[] = {
  23613. 0,
  23614. "/sql",
  23615. "/sql/tmp"
  23616. "/tmp",
  23617. 0 /* List terminator */
  23618. };
  23619. unsigned int i;
  23620. struct stat buf;
  23621. const char *zDir = 0;
  23622. azDirs[0] = sqlite3_temp_directory;
  23623. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  23624. if( zDir==0 ) continue;
  23625. if( osStat(zDir, &buf) ) continue;
  23626. if( !S_ISDIR(buf.st_mode) ) continue;
  23627. break;
  23628. }
  23629. return zDir;
  23630. }
  23631. /*
  23632. ** Create a temporary file name in zBuf. zBuf must be allocated
  23633. ** by the calling process and must be big enough to hold at least
  23634. ** pVfs->mxPathname bytes.
  23635. */
  23636. static int rtthreadGetTempname(int nBuf, char *zBuf){
  23637. static const unsigned char zChars[] =
  23638. "abcdefghijklmnopqrstuvwxyz"
  23639. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  23640. "0123456789";
  23641. unsigned int i, j;
  23642. const char *zDir;
  23643. /* It's odd to simulate an io-error here, but really this is just
  23644. ** using the io-error infrastructure to test that SQLite handles this
  23645. ** function failing.
  23646. */
  23647. SimulateIOError( return SQLITE_IOERR );
  23648. zDir = rtthreadTempFileDir();
  23649. if( zDir==0 ) zDir = ".";
  23650. /* Check that the output buffer is large enough for the temporary file
  23651. ** name. If it is not, return SQLITE_ERROR.
  23652. */
  23653. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  23654. return SQLITE_ERROR;
  23655. }
  23656. do{
  23657. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  23658. j = (int)strlen(zBuf);
  23659. sqlite3_randomness(15, &zBuf[j]);
  23660. for(i=0; i<15; i++, j++){
  23661. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  23662. }
  23663. zBuf[j] = 0;
  23664. zBuf[j+1] = 0;
  23665. }while( osAccess(zBuf,0)==0 );
  23666. return SQLITE_OK;
  23667. }
  23668. /*
  23669. ** Open the file zPath.
  23670. **
  23671. ** Previously, the SQLite OS layer used three functions in place of this
  23672. ** one:
  23673. **
  23674. ** sqlite3OsOpenReadWrite();
  23675. ** sqlite3OsOpenReadOnly();
  23676. ** sqlite3OsOpenExclusive();
  23677. **
  23678. ** These calls correspond to the following combinations of flags:
  23679. **
  23680. ** ReadWrite() -> (READWRITE | CREATE)
  23681. ** ReadOnly() -> (READONLY)
  23682. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  23683. **
  23684. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  23685. ** true, the file was configured to be automatically deleted when the
  23686. ** file handle closed. To achieve the same effect using this new
  23687. ** interface, add the DELETEONCLOSE flag to those specified above for
  23688. ** OpenExclusive().
  23689. */
  23690. static int rtthreadOpen(
  23691. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  23692. const char *zPath, /* Pathname of file to be opened */
  23693. sqlite3_file *pFile, /* The file descriptor to be filled in */
  23694. int flags, /* Input flags to control the opening */
  23695. int *pOutFlags /* Output flags returned to SQLite core */
  23696. ){
  23697. rtthreadFile *p = (rtthreadFile *)pFile;
  23698. int fd = -1; /* File descriptor returned by open() */
  23699. int openFlags = 0; /* Flags to pass to open() */
  23700. int eType = flags&0xFFFFFF00; /* Type of file to open */
  23701. int noLock; /* True to omit locking primitives */
  23702. int rc = SQLITE_OK; /* Function Return Code */
  23703. int ctrlFlags = 0; /* UNIXFILE_* flags */
  23704. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  23705. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  23706. int isCreate = (flags & SQLITE_OPEN_CREATE);
  23707. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  23708. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  23709. #if SQLITE_ENABLE_LOCKING_STYLE
  23710. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  23711. #endif
  23712. /* If creating a master or main-file journal, this function will open
  23713. ** a file-descriptor on the directory too. The first time unixSync()
  23714. ** is called the directory file descriptor will be fsync()ed and close()d.
  23715. */
  23716. int syncDir = (isCreate && (
  23717. eType==SQLITE_OPEN_MASTER_JOURNAL
  23718. || eType==SQLITE_OPEN_MAIN_JOURNAL
  23719. || eType==SQLITE_OPEN_WAL
  23720. ));
  23721. /* If argument zPath is a NULL pointer, this function is required to open
  23722. ** a temporary file. Use this buffer to store the file name in.
  23723. */
  23724. char zTmpname[MAX_PATHNAME+2];
  23725. const char *zName = zPath;
  23726. /* Check the following statements are true:
  23727. **
  23728. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  23729. ** (b) if CREATE is set, then READWRITE must also be set, and
  23730. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  23731. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  23732. */
  23733. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  23734. assert(isCreate==0 || isReadWrite);
  23735. assert(isExclusive==0 || isCreate);
  23736. assert(isDelete==0 || isCreate);
  23737. /* The main DB, main journal, WAL file and master journal are never
  23738. ** automatically deleted. Nor are they ever temporary files. */
  23739. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  23740. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  23741. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  23742. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  23743. /* Assert that the upper layer has set one of the "file-type" flags. */
  23744. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  23745. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  23746. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  23747. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  23748. );
  23749. memset(p, 0, sizeof(rtthreadFile));
  23750. if( !zName ){
  23751. /* If zName is NULL, the upper layer is requesting a temp file. */
  23752. assert(isDelete && !syncDir);
  23753. rc = rtthreadGetTempname(MAX_PATHNAME+2, zTmpname);
  23754. if( rc!=SQLITE_OK ){
  23755. return rc;
  23756. }
  23757. zName = zTmpname;
  23758. /* Generated temporary filenames are always double-zero terminated
  23759. ** for use by sqlite3_uri_parameter(). */
  23760. assert( zName[strlen(zName)+1]==0 );
  23761. }
  23762. /* Determine the value of the flags parameter passed to POSIX function
  23763. ** open(). These must be calculated even if open() is not called, as
  23764. ** they may be stored as part of the file handle and used by the
  23765. ** 'conch file' locking functions later on. */
  23766. if( isReadonly ) openFlags |= O_RDONLY;
  23767. if( isReadWrite ) openFlags |= O_RDWR;
  23768. if( isCreate ) openFlags |= O_CREAT;
  23769. if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/);
  23770. openFlags |= (0/*O_LARGEFILE*/|O_BINARY);
  23771. if( fd<0 ){
  23772. mode_t openMode = 0; /* Permissions to create file with */
  23773. fd = robust_open(zName, openFlags, openMode);
  23774. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  23775. if( fd<0 && errno!=DFS_STATUS_EISDIR && isReadWrite && !isExclusive ){
  23776. /* Failed to open the file for read/write access. Try read-only. */
  23777. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  23778. openFlags &= ~(O_RDWR|O_CREAT);
  23779. flags |= SQLITE_OPEN_READONLY;
  23780. openFlags |= O_RDONLY;
  23781. isReadonly = 1;
  23782. fd = robust_open(zName, openFlags, openMode);
  23783. }
  23784. if( fd<0 ){
  23785. rc = rtthreadLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  23786. goto open_finished;
  23787. }
  23788. }
  23789. assert( fd>=0 );
  23790. if( pOutFlags ){
  23791. *pOutFlags = flags;
  23792. }
  23793. if( isDelete ){
  23794. osUnlink(zName);
  23795. }
  23796. #if SQLITE_ENABLE_LOCKING_STYLE
  23797. else{
  23798. p->openFlags = openFlags;
  23799. }
  23800. #endif
  23801. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  23802. /* Set up appropriate ctrlFlags */
  23803. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  23804. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  23805. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  23806. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  23807. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  23808. rc = fillInRtthreadFile(pVfs, fd, pFile, zPath, ctrlFlags);
  23809. open_finished:
  23810. return rc;
  23811. }
  23812. /*
  23813. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  23814. ** the directory after deleting the file.
  23815. */
  23816. static int rtthreadDelete(
  23817. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  23818. const char *zPath, /* Name of file to be deleted */
  23819. int dirSync /* If true, fsync() directory after deleting file */
  23820. ){
  23821. int rc = SQLITE_OK;
  23822. UNUSED_PARAMETER(NotUsed);
  23823. SimulateIOError(return SQLITE_IOERR_DELETE);
  23824. if( osUnlink(zPath)==(-1) ){
  23825. if( errno==DFS_STATUS_ENOENT ){
  23826. rc = SQLITE_IOERR_DELETE_NOENT;
  23827. }else{
  23828. rc = rtthreadLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  23829. }
  23830. return rc;
  23831. }
  23832. #ifndef SQLITE_DISABLE_DIRSYNC
  23833. if( (dirSync & 1)!=0 ){
  23834. int fd;
  23835. rc = osOpenDirectory(zPath, &fd);
  23836. if( rc==SQLITE_OK ){
  23837. robust_close(0, fd, __LINE__);
  23838. }else if( rc==SQLITE_CANTOPEN ){
  23839. rc = SQLITE_OK;
  23840. }
  23841. }
  23842. #endif
  23843. return rc;
  23844. }
  23845. /*
  23846. ** Test the existence of or access permissions of file zPath. The
  23847. ** test performed depends on the value of flags:
  23848. **
  23849. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  23850. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  23851. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  23852. **
  23853. ** Otherwise return 0.
  23854. */
  23855. #ifndef F_OK
  23856. # define F_OK 0
  23857. #endif
  23858. #ifndef R_OK
  23859. # define R_OK 4
  23860. #endif
  23861. #ifndef W_OK
  23862. # define W_OK 2
  23863. #endif
  23864. static int rtthreadAccess(
  23865. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  23866. const char *zPath, /* Path of the file to examine */
  23867. int flags, /* What do we want to learn about the zPath file? */
  23868. int *pResOut /* Write result boolean here */
  23869. ){
  23870. int amode = 0;
  23871. UNUSED_PARAMETER(NotUsed);
  23872. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  23873. switch( flags ){
  23874. case SQLITE_ACCESS_EXISTS:
  23875. amode = F_OK;
  23876. break;
  23877. case SQLITE_ACCESS_READWRITE:
  23878. amode = W_OK|R_OK;
  23879. break;
  23880. case SQLITE_ACCESS_READ:
  23881. amode = R_OK;
  23882. break;
  23883. default:
  23884. assert(!"Invalid flags argument");
  23885. }
  23886. *pResOut = (osAccess(zPath, amode)==0);
  23887. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  23888. struct stat buf;
  23889. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  23890. *pResOut = 0;
  23891. }
  23892. }
  23893. return SQLITE_OK;
  23894. }
  23895. /*
  23896. ** Turn a relative pathname into a full pathname. The relative path
  23897. ** is stored as a nul-terminated string in the buffer pointed to by
  23898. ** zPath.
  23899. **
  23900. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  23901. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  23902. ** this buffer before returning.
  23903. */
  23904. static int rtthreadFullPathname(
  23905. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  23906. const char *zPath, /* Possibly relative input path */
  23907. int nOut, /* Size of output buffer in bytes */
  23908. char *zOut /* Output buffer */
  23909. ){
  23910. /* It's odd to simulate an io-error here, but really this is just
  23911. ** using the io-error infrastructure to test that SQLite handles this
  23912. ** function failing. This function could fail if, for example, the
  23913. ** current working directory has been unlinked.
  23914. */
  23915. SimulateIOError( return SQLITE_ERROR );
  23916. assert( pVfs->mxPathname==MAX_PATHNAME );
  23917. UNUSED_PARAMETER(pVfs);
  23918. zOut[nOut-1] = '\0';
  23919. if( zPath[0]=='/' ){
  23920. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  23921. }else{
  23922. int nCwd;
  23923. if( osGetcwd(zOut, nOut-1)==0 ){
  23924. return rtthreadLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  23925. }
  23926. nCwd = (int)strlen(zOut);
  23927. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  23928. }
  23929. return SQLITE_OK;
  23930. }
  23931. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  23932. # error "rtthread not support load extension, compile with SQLITE_OMIT_WAL."
  23933. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  23934. #define rtthreadDlOpen 0
  23935. #define rtthreadDlError 0
  23936. #define rtthreadDlSym 0
  23937. #define rtthreadDlClose 0
  23938. #endif
  23939. /*
  23940. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  23941. */
  23942. static int rtthreadRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  23943. UNUSED_PARAMETER(NotUsed);
  23944. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  23945. /* We have to initialize zBuf to prevent valgrind from reporting
  23946. ** errors. The reports issued by valgrind are incorrect - we would
  23947. ** prefer that the randomness be increased by making use of the
  23948. ** uninitialized space in zBuf - but valgrind errors tend to worry
  23949. ** some users. Rather than argue, it seems easier just to initialize
  23950. ** the whole array and silence valgrind, even if that means less randomness
  23951. ** in the random seed.
  23952. **
  23953. ** When testing, initializing zBuf[] to zero is all we do. That means
  23954. ** that we always use the same random number sequence. This makes the
  23955. ** tests repeatable.
  23956. */
  23957. memset(zBuf, 0, nBuf);
  23958. {
  23959. int i;
  23960. char tick8, tick16;
  23961. tick8 = (char)rt_tick_get();
  23962. tick16 = (char)(rt_tick_get() >> 8);
  23963. for (i=0; i<nBuf; i++)
  23964. {
  23965. zBuf[i] = (char)(i ^ tick8 ^ tick16);
  23966. tick8 = zBuf[i];
  23967. tick16 = ~(tick8 ^ tick16);
  23968. }
  23969. }
  23970. return nBuf;
  23971. }
  23972. /*
  23973. ** Sleep for a little while. Return the amount of time slept.
  23974. ** The argument is the number of microseconds we want to sleep.
  23975. ** The return value is the number of microseconds of sleep actually
  23976. ** requested from the underlying operating system, a number which
  23977. ** might be greater than or equal to the argument, but not less
  23978. ** than the argument.
  23979. */
  23980. static int rtthreadSleep(sqlite3_vfs *NotUsed, int microseconds){
  23981. int seconds = (microseconds+999999)/1000000;
  23982. osSleep(seconds * 1000);
  23983. UNUSED_PARAMETER(NotUsed);
  23984. return seconds*1000000;
  23985. }
  23986. /*
  23987. ** The following variable, if set to a non-zero value, is interpreted as
  23988. ** the number of seconds since 1970 and is used to set the result of
  23989. ** sqlite3OsCurrentTime() during testing.
  23990. */
  23991. #ifdef SQLITE_TEST
  23992. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  23993. #endif
  23994. #ifndef NO_GETTOD
  23995. #define NO_GETTOD 1
  23996. #endif
  23997. /*
  23998. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  23999. ** the current time and date as a Julian Day number times 86_400_000. In
  24000. ** other words, write into *piNow the number of milliseconds since the Julian
  24001. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  24002. ** proleptic Gregorian calendar.
  24003. **
  24004. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  24005. ** cannot be found.
  24006. */
  24007. static int rtthreadCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  24008. static const sqlite3_int64 rtthreadEpoch = 24405875*(sqlite3_int64)8640000;
  24009. int rc = SQLITE_OK;
  24010. #if defined(NO_GETTOD)
  24011. time_t t;
  24012. time(&t);
  24013. *piNow = ((sqlite3_int64)t)*1000 + rtthreadEpoch;
  24014. #else
  24015. struct timeval sNow;
  24016. if( gettimeofday(&sNow, 0)==0 ){
  24017. *piNow = rtthreadEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  24018. }else{
  24019. rc = SQLITE_ERROR;
  24020. }
  24021. #endif
  24022. #ifdef SQLITE_TEST
  24023. if( sqlite3_current_time ){
  24024. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + rtthreadEpoch;
  24025. }
  24026. #endif
  24027. UNUSED_PARAMETER(NotUsed);
  24028. return rc;
  24029. }
  24030. /*
  24031. ** Find the current time (in Universal Coordinated Time). Write the
  24032. ** current time and date as a Julian Day number into *prNow and
  24033. ** return 0. Return 1 if the time and date cannot be found.
  24034. */
  24035. static int rtthreadCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  24036. sqlite3_int64 i = 0;
  24037. int rc;
  24038. UNUSED_PARAMETER(NotUsed);
  24039. rc = rtthreadCurrentTimeInt64(0, &i);
  24040. *prNow = i/86400000.0;
  24041. return rc;
  24042. }
  24043. /*
  24044. ** We added the xGetLastError() method with the intention of providing
  24045. ** better low-level error messages when operating-system problems come up
  24046. ** during SQLite operation. But so far, none of that has been implemented
  24047. ** in the core. So this routine is never called. For now, it is merely
  24048. ** a place-holder.
  24049. */
  24050. static int rtthreadGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  24051. UNUSED_PARAMETER(NotUsed);
  24052. UNUSED_PARAMETER(NotUsed2);
  24053. UNUSED_PARAMETER(NotUsed3);
  24054. return 0;
  24055. }
  24056. /*
  24057. ************************ End of sqlite3_vfs methods ***************************
  24058. ******************************************************************************/
  24059. /*
  24060. ** Initialize the operating system interface.
  24061. **
  24062. ** This routine registers all VFS implementations for unix-like operating
  24063. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  24064. ** should be the only routines in this file that are visible from other
  24065. ** files.
  24066. **
  24067. ** This routine is called once during SQLite initialization and by a
  24068. ** single thread. The memory allocation and mutex subsystems have not
  24069. ** necessarily been initialized when this routine is called, and so they
  24070. ** should not be used.
  24071. */
  24072. /*
  24073. ** The following macro defines an initializer for an sqlite3_vfs object.
  24074. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  24075. ** to the "finder" function. (pAppData is a pointer to a pointer because
  24076. ** silly C90 rules prohibit a void* from being cast to a function pointer
  24077. ** and so we have to go through the intermediate pointer to avoid problems
  24078. ** when compiling with -pedantic-errors on GCC.)
  24079. **
  24080. ** The FINDER parameter to this macro is the name of the pointer to the
  24081. ** finder-function. The finder-function returns a pointer to the
  24082. ** sqlite_io_methods object that implements the desired locking
  24083. ** behaviors. See the division above that contains the IOMETHODS
  24084. ** macro for addition information on finder-functions.
  24085. **
  24086. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  24087. ** object. But the "autolockIoFinder" available on MacOSX does a little
  24088. ** more than that; it looks at the filesystem type that hosts the
  24089. ** database file and tries to choose an locking method appropriate for
  24090. ** that filesystem time.
  24091. */
  24092. #define UNIXVFS(VFSNAME, FINDER) { \
  24093. 3, /* iVersion */ \
  24094. sizeof(rtthreadFile), /* szOsFile */ \
  24095. MAX_PATHNAME, /* mxPathname */ \
  24096. 0, /* pNext */ \
  24097. VFSNAME, /* zName */ \
  24098. (void*)&FINDER, /* pAppData */ \
  24099. rtthreadOpen, /* xOpen */ \
  24100. rtthreadDelete, /* xDelete */ \
  24101. rtthreadAccess, /* xAccess */ \
  24102. rtthreadFullPathname, /* xFullPathname */ \
  24103. rtthreadDlOpen, /* xDlOpen */ \
  24104. rtthreadDlError, /* xDlError */ \
  24105. rtthreadDlSym, /* xDlSym */ \
  24106. rtthreadDlClose, /* xDlClose */ \
  24107. rtthreadRandomness, /* xRandomness */ \
  24108. rtthreadSleep, /* xSleep */ \
  24109. rtthreadCurrentTime, /* xCurrentTime */ \
  24110. rtthreadGetLastError, /* xGetLastError */ \
  24111. rtthreadCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  24112. rtthreadSetSystemCall, /* xSetSystemCall */ \
  24113. rtthreadGetSystemCall, /* xGetSystemCall */ \
  24114. rtthreadNextSystemCall, /* xNextSystemCall */ \
  24115. }
  24116. SQLITE_API int sqlite3_os_init(void){
  24117. /*
  24118. ** All default VFSes for unix are contained in the following array.
  24119. **
  24120. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  24121. ** by the SQLite core when the VFS is registered. So the following
  24122. ** array cannot be const.
  24123. */
  24124. static sqlite3_vfs aVfs[] = {
  24125. UNIXVFS("unix-none", nolockIoFinder ),
  24126. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  24127. #if SQLITE_ENABLE_LOCKING_STYLE
  24128. UNIXVFS("unix-flock", flockIoFinder ),
  24129. #endif
  24130. };
  24131. unsigned int i; /* Loop counter */
  24132. /* Double-check that the aSyscall[] array has been constructed
  24133. ** correctly. See ticket [bb3a86e890c8e96ab] */
  24134. assert( ArraySize(aSyscall)==24 );
  24135. /* Register all VFSes defined in the aVfs[] array */
  24136. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  24137. sqlite3_vfs_register(&aVfs[i], i==0);
  24138. }
  24139. return SQLITE_OK;
  24140. }
  24141. /*
  24142. ** Shutdown the operating system interface.
  24143. **
  24144. ** Some operating systems might need to do some cleanup in this routine,
  24145. ** to release dynamically allocated objects. But not on unix.
  24146. ** This routine is a no-op for unix.
  24147. */
  24148. SQLITE_API int sqlite3_os_end(void){
  24149. return SQLITE_OK;
  24150. }
  24151. #endif /* SQLITE_OS_RTTHREAD */
  24152. /************** End of os_rtthread.c *****************************************/
  24153. /************** Begin file bitvec.c ******************************************/
  24154. /*
  24155. ** 2008 February 16
  24156. **
  24157. ** The author disclaims copyright to this source code. In place of
  24158. ** a legal notice, here is a blessing:
  24159. **
  24160. ** May you do good and not evil.
  24161. ** May you find forgiveness for yourself and forgive others.
  24162. ** May you share freely, never taking more than you give.
  24163. **
  24164. *************************************************************************
  24165. ** This file implements an object that represents a fixed-length
  24166. ** bitmap. Bits are numbered starting with 1.
  24167. **
  24168. ** A bitmap is used to record which pages of a database file have been
  24169. ** journalled during a transaction, or which pages have the "dont-write"
  24170. ** property. Usually only a few pages are meet either condition.
  24171. ** So the bitmap is usually sparse and has low cardinality.
  24172. ** But sometimes (for example when during a DROP of a large table) most
  24173. ** or all of the pages in a database can get journalled. In those cases,
  24174. ** the bitmap becomes dense with high cardinality. The algorithm needs
  24175. ** to handle both cases well.
  24176. **
  24177. ** The size of the bitmap is fixed when the object is created.
  24178. **
  24179. ** All bits are clear when the bitmap is created. Individual bits
  24180. ** may be set or cleared one at a time.
  24181. **
  24182. ** Test operations are about 100 times more common that set operations.
  24183. ** Clear operations are exceedingly rare. There are usually between
  24184. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  24185. ** sometimes grow into tens of thousands or larger. The size of the
  24186. ** Bitvec object is the number of pages in the database file at the
  24187. ** start of a transaction, and is thus usually less than a few thousand,
  24188. ** but can be as large as 2 billion for a really big database.
  24189. */
  24190. /* Size of the Bitvec structure in bytes. */
  24191. #define BITVEC_SZ 512
  24192. /* Round the union size down to the nearest pointer boundary, since that's how
  24193. ** it will be aligned within the Bitvec struct. */
  24194. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  24195. /* Type of the array "element" for the bitmap representation.
  24196. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  24197. ** Setting this to the "natural word" size of your CPU may improve
  24198. ** performance. */
  24199. #define BITVEC_TELEM u8
  24200. /* Size, in bits, of the bitmap element. */
  24201. #define BITVEC_SZELEM 8
  24202. /* Number of elements in a bitmap array. */
  24203. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  24204. /* Number of bits in the bitmap array. */
  24205. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  24206. /* Number of u32 values in hash table. */
  24207. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  24208. /* Maximum number of entries in hash table before
  24209. ** sub-dividing and re-hashing. */
  24210. #define BITVEC_MXHASH (BITVEC_NINT/2)
  24211. /* Hashing function for the aHash representation.
  24212. ** Empirical testing showed that the *37 multiplier
  24213. ** (an arbitrary prime)in the hash function provided
  24214. ** no fewer collisions than the no-op *1. */
  24215. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  24216. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  24217. /*
  24218. ** A bitmap is an instance of the following structure.
  24219. **
  24220. ** This bitmap records the existence of zero or more bits
  24221. ** with values between 1 and iSize, inclusive.
  24222. **
  24223. ** There are three possible representations of the bitmap.
  24224. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  24225. ** bitmap. The least significant bit is bit 1.
  24226. **
  24227. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  24228. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  24229. **
  24230. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  24231. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  24232. ** handles up to iDivisor separate values of i. apSub[0] holds
  24233. ** values between 1 and iDivisor. apSub[1] holds values between
  24234. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  24235. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  24236. ** to hold deal with values between 1 and iDivisor.
  24237. */
  24238. struct Bitvec {
  24239. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  24240. u32 nSet; /* Number of bits that are set - only valid for aHash
  24241. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  24242. ** this would be 125. */
  24243. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  24244. /* Should >=0 for apSub element. */
  24245. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  24246. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  24247. union {
  24248. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  24249. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  24250. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  24251. } u;
  24252. };
  24253. /*
  24254. ** Create a new bitmap object able to handle bits between 0 and iSize,
  24255. ** inclusive. Return a pointer to the new object. Return NULL if
  24256. ** malloc fails.
  24257. */
  24258. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  24259. Bitvec *p;
  24260. assert( sizeof(*p)==BITVEC_SZ );
  24261. p = sqlite3MallocZero( sizeof(*p) );
  24262. if( p ){
  24263. p->iSize = iSize;
  24264. }
  24265. return p;
  24266. }
  24267. /*
  24268. ** Check to see if the i-th bit is set. Return true or false.
  24269. ** If p is NULL (if the bitmap has not been created) or if
  24270. ** i is out of range, then return false.
  24271. */
  24272. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  24273. if( p==0 ) return 0;
  24274. if( i>p->iSize || i==0 ) return 0;
  24275. i--;
  24276. while( p->iDivisor ){
  24277. u32 bin = i/p->iDivisor;
  24278. i = i%p->iDivisor;
  24279. p = p->u.apSub[bin];
  24280. if (!p) {
  24281. return 0;
  24282. }
  24283. }
  24284. if( p->iSize<=BITVEC_NBIT ){
  24285. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  24286. } else{
  24287. u32 h = BITVEC_HASH(i++);
  24288. while( p->u.aHash[h] ){
  24289. if( p->u.aHash[h]==i ) return 1;
  24290. h = (h+1) % BITVEC_NINT;
  24291. }
  24292. return 0;
  24293. }
  24294. }
  24295. /*
  24296. ** Set the i-th bit. Return 0 on success and an error code if
  24297. ** anything goes wrong.
  24298. **
  24299. ** This routine might cause sub-bitmaps to be allocated. Failing
  24300. ** to get the memory needed to hold the sub-bitmap is the only
  24301. ** that can go wrong with an insert, assuming p and i are valid.
  24302. **
  24303. ** The calling function must ensure that p is a valid Bitvec object
  24304. ** and that the value for "i" is within range of the Bitvec object.
  24305. ** Otherwise the behavior is undefined.
  24306. */
  24307. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  24308. u32 h;
  24309. if( p==0 ) return SQLITE_OK;
  24310. assert( i>0 );
  24311. assert( i<=p->iSize );
  24312. i--;
  24313. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  24314. u32 bin = i/p->iDivisor;
  24315. i = i%p->iDivisor;
  24316. if( p->u.apSub[bin]==0 ){
  24317. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  24318. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  24319. }
  24320. p = p->u.apSub[bin];
  24321. }
  24322. if( p->iSize<=BITVEC_NBIT ){
  24323. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  24324. return SQLITE_OK;
  24325. }
  24326. h = BITVEC_HASH(i++);
  24327. /* if there wasn't a hash collision, and this doesn't */
  24328. /* completely fill the hash, then just add it without */
  24329. /* worring about sub-dividing and re-hashing. */
  24330. if( !p->u.aHash[h] ){
  24331. if (p->nSet<(BITVEC_NINT-1)) {
  24332. goto bitvec_set_end;
  24333. } else {
  24334. goto bitvec_set_rehash;
  24335. }
  24336. }
  24337. /* there was a collision, check to see if it's already */
  24338. /* in hash, if not, try to find a spot for it */
  24339. do {
  24340. if( p->u.aHash[h]==i ) return SQLITE_OK;
  24341. h++;
  24342. if( h>=BITVEC_NINT ) h = 0;
  24343. } while( p->u.aHash[h] );
  24344. /* we didn't find it in the hash. h points to the first */
  24345. /* available free spot. check to see if this is going to */
  24346. /* make our hash too "full". */
  24347. bitvec_set_rehash:
  24348. if( p->nSet>=BITVEC_MXHASH ){
  24349. unsigned int j;
  24350. int rc;
  24351. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  24352. if( aiValues==0 ){
  24353. return SQLITE_NOMEM;
  24354. }else{
  24355. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  24356. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  24357. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  24358. rc = sqlite3BitvecSet(p, i);
  24359. for(j=0; j<BITVEC_NINT; j++){
  24360. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  24361. }
  24362. sqlite3StackFree(0, aiValues);
  24363. return rc;
  24364. }
  24365. }
  24366. bitvec_set_end:
  24367. p->nSet++;
  24368. p->u.aHash[h] = i;
  24369. return SQLITE_OK;
  24370. }
  24371. /*
  24372. ** Clear the i-th bit.
  24373. **
  24374. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  24375. ** that BitvecClear can use to rebuilt its hash table.
  24376. */
  24377. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  24378. if( p==0 ) return;
  24379. assert( i>0 );
  24380. i--;
  24381. while( p->iDivisor ){
  24382. u32 bin = i/p->iDivisor;
  24383. i = i%p->iDivisor;
  24384. p = p->u.apSub[bin];
  24385. if (!p) {
  24386. return;
  24387. }
  24388. }
  24389. if( p->iSize<=BITVEC_NBIT ){
  24390. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  24391. }else{
  24392. unsigned int j;
  24393. u32 *aiValues = pBuf;
  24394. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  24395. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  24396. p->nSet = 0;
  24397. for(j=0; j<BITVEC_NINT; j++){
  24398. if( aiValues[j] && aiValues[j]!=(i+1) ){
  24399. u32 h = BITVEC_HASH(aiValues[j]-1);
  24400. p->nSet++;
  24401. while( p->u.aHash[h] ){
  24402. h++;
  24403. if( h>=BITVEC_NINT ) h = 0;
  24404. }
  24405. p->u.aHash[h] = aiValues[j];
  24406. }
  24407. }
  24408. }
  24409. }
  24410. /*
  24411. ** Destroy a bitmap object. Reclaim all memory used.
  24412. */
  24413. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  24414. if( p==0 ) return;
  24415. if( p->iDivisor ){
  24416. unsigned int i;
  24417. for(i=0; i<BITVEC_NPTR; i++){
  24418. sqlite3BitvecDestroy(p->u.apSub[i]);
  24419. }
  24420. }
  24421. sqlite3_free(p);
  24422. }
  24423. /*
  24424. ** Return the value of the iSize parameter specified when Bitvec *p
  24425. ** was created.
  24426. */
  24427. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  24428. return p->iSize;
  24429. }
  24430. #ifndef SQLITE_OMIT_BUILTIN_TEST
  24431. /*
  24432. ** Let V[] be an array of unsigned characters sufficient to hold
  24433. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  24434. ** Then the following macros can be used to set, clear, or test
  24435. ** individual bits within V.
  24436. */
  24437. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  24438. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  24439. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  24440. /*
  24441. ** This routine runs an extensive test of the Bitvec code.
  24442. **
  24443. ** The input is an array of integers that acts as a program
  24444. ** to test the Bitvec. The integers are opcodes followed
  24445. ** by 0, 1, or 3 operands, depending on the opcode. Another
  24446. ** opcode follows immediately after the last operand.
  24447. **
  24448. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  24449. ** "halt" opcode and causes the test to end.
  24450. **
  24451. ** 0 Halt and return the number of errors
  24452. ** 1 N S X Set N bits beginning with S and incrementing by X
  24453. ** 2 N S X Clear N bits beginning with S and incrementing by X
  24454. ** 3 N Set N randomly chosen bits
  24455. ** 4 N Clear N randomly chosen bits
  24456. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  24457. **
  24458. ** The opcodes 1 through 4 perform set and clear operations are performed
  24459. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  24460. ** Opcode 5 works on the linear array only, not on the Bitvec.
  24461. ** Opcode 5 is used to deliberately induce a fault in order to
  24462. ** confirm that error detection works.
  24463. **
  24464. ** At the conclusion of the test the linear array is compared
  24465. ** against the Bitvec object. If there are any differences,
  24466. ** an error is returned. If they are the same, zero is returned.
  24467. **
  24468. ** If a memory allocation error occurs, return -1.
  24469. */
  24470. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  24471. Bitvec *pBitvec = 0;
  24472. unsigned char *pV = 0;
  24473. int rc = -1;
  24474. int i, nx, pc, op;
  24475. void *pTmpSpace;
  24476. /* Allocate the Bitvec to be tested and a linear array of
  24477. ** bits to act as the reference */
  24478. pBitvec = sqlite3BitvecCreate( sz );
  24479. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  24480. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  24481. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  24482. /* NULL pBitvec tests */
  24483. sqlite3BitvecSet(0, 1);
  24484. sqlite3BitvecClear(0, 1, pTmpSpace);
  24485. /* Run the program */
  24486. pc = 0;
  24487. while( (op = aOp[pc])!=0 ){
  24488. switch( op ){
  24489. case 1:
  24490. case 2:
  24491. case 5: {
  24492. nx = 4;
  24493. i = aOp[pc+2] - 1;
  24494. aOp[pc+2] += aOp[pc+3];
  24495. break;
  24496. }
  24497. case 3:
  24498. case 4:
  24499. default: {
  24500. nx = 2;
  24501. sqlite3_randomness(sizeof(i), &i);
  24502. break;
  24503. }
  24504. }
  24505. if( (--aOp[pc+1]) > 0 ) nx = 0;
  24506. pc += nx;
  24507. i = (i & 0x7fffffff)%sz;
  24508. if( (op & 1)!=0 ){
  24509. SETBIT(pV, (i+1));
  24510. if( op!=5 ){
  24511. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  24512. }
  24513. }else{
  24514. CLEARBIT(pV, (i+1));
  24515. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  24516. }
  24517. }
  24518. /* Test to make sure the linear array exactly matches the
  24519. ** Bitvec object. Start with the assumption that they do
  24520. ** match (rc==0). Change rc to non-zero if a discrepancy
  24521. ** is found.
  24522. */
  24523. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  24524. + sqlite3BitvecTest(pBitvec, 0)
  24525. + (sqlite3BitvecSize(pBitvec) - sz);
  24526. for(i=1; i<=sz; i++){
  24527. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  24528. rc = i;
  24529. break;
  24530. }
  24531. }
  24532. /* Free allocated structure */
  24533. bitvec_end:
  24534. sqlite3_free(pTmpSpace);
  24535. sqlite3_free(pV);
  24536. sqlite3BitvecDestroy(pBitvec);
  24537. return rc;
  24538. }
  24539. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  24540. /************** End of bitvec.c **********************************************/
  24541. /************** Begin file pcache.c ******************************************/
  24542. /*
  24543. ** 2008 August 05
  24544. **
  24545. ** The author disclaims copyright to this source code. In place of
  24546. ** a legal notice, here is a blessing:
  24547. **
  24548. ** May you do good and not evil.
  24549. ** May you find forgiveness for yourself and forgive others.
  24550. ** May you share freely, never taking more than you give.
  24551. **
  24552. *************************************************************************
  24553. ** This file implements that page cache.
  24554. */
  24555. /*
  24556. ** A complete page cache is an instance of this structure.
  24557. */
  24558. struct PCache {
  24559. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  24560. PgHdr *pSynced; /* Last synced page in dirty page list */
  24561. int nRef; /* Number of referenced pages */
  24562. int szCache; /* Configured cache size */
  24563. int szPage; /* Size of every page in this cache */
  24564. int szExtra; /* Size of extra space for each page */
  24565. int bPurgeable; /* True if pages are on backing store */
  24566. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  24567. void *pStress; /* Argument to xStress */
  24568. sqlite3_pcache *pCache; /* Pluggable cache module */
  24569. PgHdr *pPage1; /* Reference to page 1 */
  24570. };
  24571. /*
  24572. ** Some of the assert() macros in this code are too expensive to run
  24573. ** even during normal debugging. Use them only rarely on long-running
  24574. ** tests. Enable the expensive asserts using the
  24575. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  24576. */
  24577. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  24578. # define expensive_assert(X) assert(X)
  24579. #else
  24580. # define expensive_assert(X)
  24581. #endif
  24582. /********************************** Linked List Management ********************/
  24583. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  24584. /*
  24585. ** Check that the pCache->pSynced variable is set correctly. If it
  24586. ** is not, either fail an assert or return zero. Otherwise, return
  24587. ** non-zero. This is only used in debugging builds, as follows:
  24588. **
  24589. ** expensive_assert( pcacheCheckSynced(pCache) );
  24590. */
  24591. static int pcacheCheckSynced(PCache *pCache){
  24592. PgHdr *p;
  24593. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  24594. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  24595. }
  24596. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  24597. }
  24598. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  24599. /*
  24600. ** Remove page pPage from the list of dirty pages.
  24601. */
  24602. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  24603. PCache *p = pPage->pCache;
  24604. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  24605. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  24606. /* Update the PCache1.pSynced variable if necessary. */
  24607. if( p->pSynced==pPage ){
  24608. PgHdr *pSynced = pPage->pDirtyPrev;
  24609. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  24610. pSynced = pSynced->pDirtyPrev;
  24611. }
  24612. p->pSynced = pSynced;
  24613. }
  24614. if( pPage->pDirtyNext ){
  24615. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  24616. }else{
  24617. assert( pPage==p->pDirtyTail );
  24618. p->pDirtyTail = pPage->pDirtyPrev;
  24619. }
  24620. if( pPage->pDirtyPrev ){
  24621. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  24622. }else{
  24623. assert( pPage==p->pDirty );
  24624. p->pDirty = pPage->pDirtyNext;
  24625. }
  24626. pPage->pDirtyNext = 0;
  24627. pPage->pDirtyPrev = 0;
  24628. expensive_assert( pcacheCheckSynced(p) );
  24629. }
  24630. /*
  24631. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  24632. ** pPage).
  24633. */
  24634. static void pcacheAddToDirtyList(PgHdr *pPage){
  24635. PCache *p = pPage->pCache;
  24636. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  24637. pPage->pDirtyNext = p->pDirty;
  24638. if( pPage->pDirtyNext ){
  24639. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  24640. pPage->pDirtyNext->pDirtyPrev = pPage;
  24641. }
  24642. p->pDirty = pPage;
  24643. if( !p->pDirtyTail ){
  24644. p->pDirtyTail = pPage;
  24645. }
  24646. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  24647. p->pSynced = pPage;
  24648. }
  24649. expensive_assert( pcacheCheckSynced(p) );
  24650. }
  24651. /*
  24652. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  24653. ** being used for an in-memory database, this function is a no-op.
  24654. */
  24655. static void pcacheUnpin(PgHdr *p){
  24656. PCache *pCache = p->pCache;
  24657. if( pCache->bPurgeable ){
  24658. if( p->pgno==1 ){
  24659. pCache->pPage1 = 0;
  24660. }
  24661. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  24662. }
  24663. }
  24664. /*************************************************** General Interfaces ******
  24665. **
  24666. ** Initialize and shutdown the page cache subsystem. Neither of these
  24667. ** functions are threadsafe.
  24668. */
  24669. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  24670. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  24671. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  24672. ** built-in default page cache is used instead of the application defined
  24673. ** page cache. */
  24674. sqlite3PCacheSetDefault();
  24675. }
  24676. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  24677. }
  24678. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  24679. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  24680. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  24681. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  24682. }
  24683. }
  24684. /*
  24685. ** Return the size in bytes of a PCache object.
  24686. */
  24687. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  24688. /*
  24689. ** Create a new PCache object. Storage space to hold the object
  24690. ** has already been allocated and is passed in as the p pointer.
  24691. ** The caller discovers how much space needs to be allocated by
  24692. ** calling sqlite3PcacheSize().
  24693. */
  24694. SQLITE_PRIVATE void sqlite3PcacheOpen(
  24695. int szPage, /* Size of every page */
  24696. int szExtra, /* Extra space associated with each page */
  24697. int bPurgeable, /* True if pages are on backing store */
  24698. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  24699. void *pStress, /* Argument to xStress */
  24700. PCache *p /* Preallocated space for the PCache */
  24701. ){
  24702. memset(p, 0, sizeof(PCache));
  24703. p->szPage = szPage;
  24704. p->szExtra = szExtra;
  24705. p->bPurgeable = bPurgeable;
  24706. p->xStress = xStress;
  24707. p->pStress = pStress;
  24708. p->szCache = 100;
  24709. }
  24710. /*
  24711. ** Change the page size for PCache object. The caller must ensure that there
  24712. ** are no outstanding page references when this function is called.
  24713. */
  24714. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  24715. assert( pCache->nRef==0 && pCache->pDirty==0 );
  24716. if( pCache->pCache ){
  24717. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  24718. pCache->pCache = 0;
  24719. pCache->pPage1 = 0;
  24720. }
  24721. pCache->szPage = szPage;
  24722. }
  24723. /*
  24724. ** Compute the number of pages of cache requested.
  24725. */
  24726. static int numberOfCachePages(PCache *p){
  24727. if( p->szCache>=0 ){
  24728. return p->szCache;
  24729. }else{
  24730. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  24731. }
  24732. }
  24733. /*
  24734. ** Try to obtain a page from the cache.
  24735. */
  24736. SQLITE_PRIVATE int sqlite3PcacheFetch(
  24737. PCache *pCache, /* Obtain the page from this cache */
  24738. Pgno pgno, /* Page number to obtain */
  24739. int createFlag, /* If true, create page if it does not exist already */
  24740. PgHdr **ppPage /* Write the page here */
  24741. ){
  24742. sqlite3_pcache_page *pPage = 0;
  24743. PgHdr *pPgHdr = 0;
  24744. int eCreate;
  24745. assert( pCache!=0 );
  24746. assert( createFlag==1 || createFlag==0 );
  24747. assert( pgno>0 );
  24748. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  24749. ** allocate it now.
  24750. */
  24751. if( !pCache->pCache && createFlag ){
  24752. sqlite3_pcache *p;
  24753. p = sqlite3GlobalConfig.pcache2.xCreate(
  24754. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  24755. );
  24756. if( !p ){
  24757. return SQLITE_NOMEM;
  24758. }
  24759. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  24760. pCache->pCache = p;
  24761. }
  24762. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  24763. if( pCache->pCache ){
  24764. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  24765. }
  24766. if( !pPage && eCreate==1 ){
  24767. PgHdr *pPg;
  24768. /* Find a dirty page to write-out and recycle. First try to find a
  24769. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  24770. ** cleared), but if that is not possible settle for any other
  24771. ** unreferenced dirty page.
  24772. */
  24773. expensive_assert( pcacheCheckSynced(pCache) );
  24774. for(pPg=pCache->pSynced;
  24775. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  24776. pPg=pPg->pDirtyPrev
  24777. );
  24778. pCache->pSynced = pPg;
  24779. if( !pPg ){
  24780. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  24781. }
  24782. if( pPg ){
  24783. int rc;
  24784. #ifdef SQLITE_LOG_CACHE_SPILL
  24785. sqlite3_log(SQLITE_FULL,
  24786. "spill page %d making room for %d - cache used: %d/%d",
  24787. pPg->pgno, pgno,
  24788. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  24789. numberOfCachePages(pCache));
  24790. #endif
  24791. rc = pCache->xStress(pCache->pStress, pPg);
  24792. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  24793. return rc;
  24794. }
  24795. }
  24796. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  24797. }
  24798. if( pPage ){
  24799. pPgHdr = (PgHdr *)pPage->pExtra;
  24800. if( !pPgHdr->pPage ){
  24801. memset(pPgHdr, 0, sizeof(PgHdr));
  24802. pPgHdr->pPage = pPage;
  24803. pPgHdr->pData = pPage->pBuf;
  24804. pPgHdr->pExtra = (void *)&pPgHdr[1];
  24805. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  24806. pPgHdr->pCache = pCache;
  24807. pPgHdr->pgno = pgno;
  24808. }
  24809. assert( pPgHdr->pCache==pCache );
  24810. assert( pPgHdr->pgno==pgno );
  24811. assert( pPgHdr->pData==pPage->pBuf );
  24812. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  24813. if( 0==pPgHdr->nRef ){
  24814. pCache->nRef++;
  24815. }
  24816. pPgHdr->nRef++;
  24817. if( pgno==1 ){
  24818. pCache->pPage1 = pPgHdr;
  24819. }
  24820. }
  24821. *ppPage = pPgHdr;
  24822. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  24823. }
  24824. /*
  24825. ** Decrement the reference count on a page. If the page is clean and the
  24826. ** reference count drops to 0, then it is made elible for recycling.
  24827. */
  24828. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  24829. assert( p->nRef>0 );
  24830. p->nRef--;
  24831. if( p->nRef==0 ){
  24832. PCache *pCache = p->pCache;
  24833. pCache->nRef--;
  24834. if( (p->flags&PGHDR_DIRTY)==0 ){
  24835. pcacheUnpin(p);
  24836. }else{
  24837. /* Move the page to the head of the dirty list. */
  24838. pcacheRemoveFromDirtyList(p);
  24839. pcacheAddToDirtyList(p);
  24840. }
  24841. }
  24842. }
  24843. /*
  24844. ** Increase the reference count of a supplied page by 1.
  24845. */
  24846. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  24847. assert(p->nRef>0);
  24848. p->nRef++;
  24849. }
  24850. /*
  24851. ** Drop a page from the cache. There must be exactly one reference to the
  24852. ** page. This function deletes that reference, so after it returns the
  24853. ** page pointed to by p is invalid.
  24854. */
  24855. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  24856. PCache *pCache;
  24857. assert( p->nRef==1 );
  24858. if( p->flags&PGHDR_DIRTY ){
  24859. pcacheRemoveFromDirtyList(p);
  24860. }
  24861. pCache = p->pCache;
  24862. pCache->nRef--;
  24863. if( p->pgno==1 ){
  24864. pCache->pPage1 = 0;
  24865. }
  24866. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  24867. }
  24868. /*
  24869. ** Make sure the page is marked as dirty. If it isn't dirty already,
  24870. ** make it so.
  24871. */
  24872. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  24873. p->flags &= ~PGHDR_DONT_WRITE;
  24874. assert( p->nRef>0 );
  24875. if( 0==(p->flags & PGHDR_DIRTY) ){
  24876. p->flags |= PGHDR_DIRTY;
  24877. pcacheAddToDirtyList( p);
  24878. }
  24879. }
  24880. /*
  24881. ** Make sure the page is marked as clean. If it isn't clean already,
  24882. ** make it so.
  24883. */
  24884. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  24885. if( (p->flags & PGHDR_DIRTY) ){
  24886. pcacheRemoveFromDirtyList(p);
  24887. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  24888. if( p->nRef==0 ){
  24889. pcacheUnpin(p);
  24890. }
  24891. }
  24892. }
  24893. /*
  24894. ** Make every page in the cache clean.
  24895. */
  24896. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  24897. PgHdr *p;
  24898. while( (p = pCache->pDirty)!=0 ){
  24899. sqlite3PcacheMakeClean(p);
  24900. }
  24901. }
  24902. /*
  24903. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  24904. */
  24905. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  24906. PgHdr *p;
  24907. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  24908. p->flags &= ~PGHDR_NEED_SYNC;
  24909. }
  24910. pCache->pSynced = pCache->pDirtyTail;
  24911. }
  24912. /*
  24913. ** Change the page number of page p to newPgno.
  24914. */
  24915. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  24916. PCache *pCache = p->pCache;
  24917. assert( p->nRef>0 );
  24918. assert( newPgno>0 );
  24919. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  24920. p->pgno = newPgno;
  24921. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  24922. pcacheRemoveFromDirtyList(p);
  24923. pcacheAddToDirtyList(p);
  24924. }
  24925. }
  24926. /*
  24927. ** Drop every cache entry whose page number is greater than "pgno". The
  24928. ** caller must ensure that there are no outstanding references to any pages
  24929. ** other than page 1 with a page number greater than pgno.
  24930. **
  24931. ** If there is a reference to page 1 and the pgno parameter passed to this
  24932. ** function is 0, then the data area associated with page 1 is zeroed, but
  24933. ** the page object is not dropped.
  24934. */
  24935. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  24936. if( pCache->pCache ){
  24937. PgHdr *p;
  24938. PgHdr *pNext;
  24939. for(p=pCache->pDirty; p; p=pNext){
  24940. pNext = p->pDirtyNext;
  24941. /* This routine never gets call with a positive pgno except right
  24942. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  24943. ** it must be that pgno==0.
  24944. */
  24945. assert( p->pgno>0 );
  24946. if( ALWAYS(p->pgno>pgno) ){
  24947. assert( p->flags&PGHDR_DIRTY );
  24948. sqlite3PcacheMakeClean(p);
  24949. }
  24950. }
  24951. if( pgno==0 && pCache->pPage1 ){
  24952. memset(pCache->pPage1->pData, 0, pCache->szPage);
  24953. pgno = 1;
  24954. }
  24955. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  24956. }
  24957. }
  24958. /*
  24959. ** Close a cache.
  24960. */
  24961. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  24962. if( pCache->pCache ){
  24963. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  24964. }
  24965. }
  24966. /*
  24967. ** Discard the contents of the cache.
  24968. */
  24969. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  24970. sqlite3PcacheTruncate(pCache, 0);
  24971. }
  24972. /*
  24973. ** Merge two lists of pages connected by pDirty and in pgno order.
  24974. ** Do not both fixing the pDirtyPrev pointers.
  24975. */
  24976. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  24977. PgHdr result, *pTail;
  24978. pTail = &result;
  24979. while( pA && pB ){
  24980. if( pA->pgno<pB->pgno ){
  24981. pTail->pDirty = pA;
  24982. pTail = pA;
  24983. pA = pA->pDirty;
  24984. }else{
  24985. pTail->pDirty = pB;
  24986. pTail = pB;
  24987. pB = pB->pDirty;
  24988. }
  24989. }
  24990. if( pA ){
  24991. pTail->pDirty = pA;
  24992. }else if( pB ){
  24993. pTail->pDirty = pB;
  24994. }else{
  24995. pTail->pDirty = 0;
  24996. }
  24997. return result.pDirty;
  24998. }
  24999. /*
  25000. ** Sort the list of pages in accending order by pgno. Pages are
  25001. ** connected by pDirty pointers. The pDirtyPrev pointers are
  25002. ** corrupted by this sort.
  25003. **
  25004. ** Since there cannot be more than 2^31 distinct pages in a database,
  25005. ** there cannot be more than 31 buckets required by the merge sorter.
  25006. ** One extra bucket is added to catch overflow in case something
  25007. ** ever changes to make the previous sentence incorrect.
  25008. */
  25009. #define N_SORT_BUCKET 32
  25010. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  25011. PgHdr *a[N_SORT_BUCKET], *p;
  25012. int i;
  25013. memset(a, 0, sizeof(a));
  25014. while( pIn ){
  25015. p = pIn;
  25016. pIn = p->pDirty;
  25017. p->pDirty = 0;
  25018. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  25019. if( a[i]==0 ){
  25020. a[i] = p;
  25021. break;
  25022. }else{
  25023. p = pcacheMergeDirtyList(a[i], p);
  25024. a[i] = 0;
  25025. }
  25026. }
  25027. if( NEVER(i==N_SORT_BUCKET-1) ){
  25028. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  25029. ** the input list. But that is impossible.
  25030. */
  25031. a[i] = pcacheMergeDirtyList(a[i], p);
  25032. }
  25033. }
  25034. p = a[0];
  25035. for(i=1; i<N_SORT_BUCKET; i++){
  25036. p = pcacheMergeDirtyList(p, a[i]);
  25037. }
  25038. return p;
  25039. }
  25040. /*
  25041. ** Return a list of all dirty pages in the cache, sorted by page number.
  25042. */
  25043. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  25044. PgHdr *p;
  25045. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  25046. p->pDirty = p->pDirtyNext;
  25047. }
  25048. return pcacheSortDirtyList(pCache->pDirty);
  25049. }
  25050. /*
  25051. ** Return the total number of referenced pages held by the cache.
  25052. */
  25053. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  25054. return pCache->nRef;
  25055. }
  25056. /*
  25057. ** Return the number of references to the page supplied as an argument.
  25058. */
  25059. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  25060. return p->nRef;
  25061. }
  25062. /*
  25063. ** Return the total number of pages in the cache.
  25064. */
  25065. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  25066. int nPage = 0;
  25067. if( pCache->pCache ){
  25068. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  25069. }
  25070. return nPage;
  25071. }
  25072. #ifdef SQLITE_TEST
  25073. /*
  25074. ** Get the suggested cache-size value.
  25075. */
  25076. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  25077. return numberOfCachePages(pCache);
  25078. }
  25079. #endif
  25080. /*
  25081. ** Set the suggested cache-size value.
  25082. */
  25083. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  25084. pCache->szCache = mxPage;
  25085. if( pCache->pCache ){
  25086. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  25087. numberOfCachePages(pCache));
  25088. }
  25089. }
  25090. /*
  25091. ** Free up as much memory as possible from the page cache.
  25092. */
  25093. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  25094. if( pCache->pCache ){
  25095. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  25096. }
  25097. }
  25098. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  25099. /*
  25100. ** For all dirty pages currently in the cache, invoke the specified
  25101. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  25102. ** defined.
  25103. */
  25104. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  25105. PgHdr *pDirty;
  25106. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  25107. xIter(pDirty);
  25108. }
  25109. }
  25110. #endif
  25111. /************** End of pcache.c **********************************************/
  25112. /************** Begin file pcache1.c *****************************************/
  25113. /*
  25114. ** 2008 November 05
  25115. **
  25116. ** The author disclaims copyright to this source code. In place of
  25117. ** a legal notice, here is a blessing:
  25118. **
  25119. ** May you do good and not evil.
  25120. ** May you find forgiveness for yourself and forgive others.
  25121. ** May you share freely, never taking more than you give.
  25122. **
  25123. *************************************************************************
  25124. **
  25125. ** This file implements the default page cache implementation (the
  25126. ** sqlite3_pcache interface). It also contains part of the implementation
  25127. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  25128. ** If the default page cache implementation is overriden, then neither of
  25129. ** these two features are available.
  25130. */
  25131. typedef struct PCache1 PCache1;
  25132. typedef struct PgHdr1 PgHdr1;
  25133. typedef struct PgFreeslot PgFreeslot;
  25134. typedef struct PGroup PGroup;
  25135. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  25136. ** of one or more PCaches that are able to recycle each others unpinned
  25137. ** pages when they are under memory pressure. A PGroup is an instance of
  25138. ** the following object.
  25139. **
  25140. ** This page cache implementation works in one of two modes:
  25141. **
  25142. ** (1) Every PCache is the sole member of its own PGroup. There is
  25143. ** one PGroup per PCache.
  25144. **
  25145. ** (2) There is a single global PGroup that all PCaches are a member
  25146. ** of.
  25147. **
  25148. ** Mode 1 uses more memory (since PCache instances are not able to rob
  25149. ** unused pages from other PCaches) but it also operates without a mutex,
  25150. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  25151. ** threadsafe, but recycles pages more efficiently.
  25152. **
  25153. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  25154. ** PGroup which is the pcache1.grp global variable and its mutex is
  25155. ** SQLITE_MUTEX_STATIC_LRU.
  25156. */
  25157. struct PGroup {
  25158. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  25159. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  25160. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  25161. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  25162. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  25163. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  25164. };
  25165. /* Each page cache is an instance of the following object. Every
  25166. ** open database file (including each in-memory database and each
  25167. ** temporary or transient database) has a single page cache which
  25168. ** is an instance of this object.
  25169. **
  25170. ** Pointers to structures of this type are cast and returned as
  25171. ** opaque sqlite3_pcache* handles.
  25172. */
  25173. struct PCache1 {
  25174. /* Cache configuration parameters. Page size (szPage) and the purgeable
  25175. ** flag (bPurgeable) are set when the cache is created. nMax may be
  25176. ** modified at any time by a call to the pcache1Cachesize() method.
  25177. ** The PGroup mutex must be held when accessing nMax.
  25178. */
  25179. PGroup *pGroup; /* PGroup this cache belongs to */
  25180. int szPage; /* Size of allocated pages in bytes */
  25181. int szExtra; /* Size of extra space in bytes */
  25182. int bPurgeable; /* True if cache is purgeable */
  25183. unsigned int nMin; /* Minimum number of pages reserved */
  25184. unsigned int nMax; /* Configured "cache_size" value */
  25185. unsigned int n90pct; /* nMax*9/10 */
  25186. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  25187. /* Hash table of all pages. The following variables may only be accessed
  25188. ** when the accessor is holding the PGroup mutex.
  25189. */
  25190. unsigned int nRecyclable; /* Number of pages in the LRU list */
  25191. unsigned int nPage; /* Total number of pages in apHash */
  25192. unsigned int nHash; /* Number of slots in apHash[] */
  25193. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  25194. };
  25195. /*
  25196. ** Each cache entry is represented by an instance of the following
  25197. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  25198. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  25199. ** in memory.
  25200. */
  25201. struct PgHdr1 {
  25202. sqlite3_pcache_page page;
  25203. unsigned int iKey; /* Key value (page number) */
  25204. PgHdr1 *pNext; /* Next in hash table chain */
  25205. PCache1 *pCache; /* Cache that currently owns this page */
  25206. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  25207. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  25208. };
  25209. /*
  25210. ** Free slots in the allocator used to divide up the buffer provided using
  25211. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  25212. */
  25213. struct PgFreeslot {
  25214. PgFreeslot *pNext; /* Next free slot */
  25215. };
  25216. /*
  25217. ** Global data used by this cache.
  25218. */
  25219. static SQLITE_WSD struct PCacheGlobal {
  25220. PGroup grp; /* The global PGroup for mode (2) */
  25221. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  25222. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  25223. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  25224. ** The nFreeSlot and pFree values do require mutex protection.
  25225. */
  25226. int isInit; /* True if initialized */
  25227. int szSlot; /* Size of each free slot */
  25228. int nSlot; /* The number of pcache slots */
  25229. int nReserve; /* Try to keep nFreeSlot above this */
  25230. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  25231. /* Above requires no mutex. Use mutex below for variable that follow. */
  25232. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  25233. PgFreeslot *pFree; /* Free page blocks */
  25234. int nFreeSlot; /* Number of unused pcache slots */
  25235. /* The following value requires a mutex to change. We skip the mutex on
  25236. ** reading because (1) most platforms read a 32-bit integer atomically and
  25237. ** (2) even if an incorrect value is read, no great harm is done since this
  25238. ** is really just an optimization. */
  25239. int bUnderPressure; /* True if low on PAGECACHE memory */
  25240. } pcache1_g;
  25241. /*
  25242. ** All code in this file should access the global structure above via the
  25243. ** alias "pcache1". This ensures that the WSD emulation is used when
  25244. ** compiling for systems that do not support real WSD.
  25245. */
  25246. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  25247. /*
  25248. ** Macros to enter and leave the PCache LRU mutex.
  25249. */
  25250. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  25251. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  25252. /******************************************************************************/
  25253. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  25254. /*
  25255. ** This function is called during initialization if a static buffer is
  25256. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  25257. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  25258. ** enough to contain 'n' buffers of 'sz' bytes each.
  25259. **
  25260. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  25261. ** to be serialized already. There is no need for further mutexing.
  25262. */
  25263. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  25264. if( pcache1.isInit ){
  25265. PgFreeslot *p;
  25266. sz = ROUNDDOWN8(sz);
  25267. pcache1.szSlot = sz;
  25268. pcache1.nSlot = pcache1.nFreeSlot = n;
  25269. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  25270. pcache1.pStart = pBuf;
  25271. pcache1.pFree = 0;
  25272. pcache1.bUnderPressure = 0;
  25273. while( n-- ){
  25274. p = (PgFreeslot*)pBuf;
  25275. p->pNext = pcache1.pFree;
  25276. pcache1.pFree = p;
  25277. pBuf = (void*)&((char*)pBuf)[sz];
  25278. }
  25279. pcache1.pEnd = pBuf;
  25280. }
  25281. }
  25282. /*
  25283. ** Malloc function used within this file to allocate space from the buffer
  25284. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  25285. ** such buffer exists or there is no space left in it, this function falls
  25286. ** back to sqlite3Malloc().
  25287. **
  25288. ** Multiple threads can run this routine at the same time. Global variables
  25289. ** in pcache1 need to be protected via mutex.
  25290. */
  25291. static void *pcache1Alloc(int nByte){
  25292. void *p = 0;
  25293. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  25294. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  25295. if( nByte<=pcache1.szSlot ){
  25296. sqlite3_mutex_enter(pcache1.mutex);
  25297. p = (PgHdr1 *)pcache1.pFree;
  25298. if( p ){
  25299. pcache1.pFree = pcache1.pFree->pNext;
  25300. pcache1.nFreeSlot--;
  25301. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  25302. assert( pcache1.nFreeSlot>=0 );
  25303. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  25304. }
  25305. sqlite3_mutex_leave(pcache1.mutex);
  25306. }
  25307. if( p==0 ){
  25308. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  25309. ** it from sqlite3Malloc instead.
  25310. */
  25311. p = sqlite3Malloc(nByte);
  25312. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  25313. if( p ){
  25314. int sz = sqlite3MallocSize(p);
  25315. sqlite3_mutex_enter(pcache1.mutex);
  25316. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  25317. sqlite3_mutex_leave(pcache1.mutex);
  25318. }
  25319. #endif
  25320. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  25321. }
  25322. return p;
  25323. }
  25324. /*
  25325. ** Free an allocated buffer obtained from pcache1Alloc().
  25326. */
  25327. static int pcache1Free(void *p){
  25328. int nFreed = 0;
  25329. if( p==0 ) return 0;
  25330. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  25331. PgFreeslot *pSlot;
  25332. sqlite3_mutex_enter(pcache1.mutex);
  25333. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  25334. pSlot = (PgFreeslot*)p;
  25335. pSlot->pNext = pcache1.pFree;
  25336. pcache1.pFree = pSlot;
  25337. pcache1.nFreeSlot++;
  25338. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  25339. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  25340. sqlite3_mutex_leave(pcache1.mutex);
  25341. }else{
  25342. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  25343. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25344. nFreed = sqlite3MallocSize(p);
  25345. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  25346. sqlite3_mutex_enter(pcache1.mutex);
  25347. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  25348. sqlite3_mutex_leave(pcache1.mutex);
  25349. #endif
  25350. sqlite3_free(p);
  25351. }
  25352. return nFreed;
  25353. }
  25354. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25355. /*
  25356. ** Return the size of a pcache allocation
  25357. */
  25358. static int pcache1MemSize(void *p){
  25359. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  25360. return pcache1.szSlot;
  25361. }else{
  25362. int iSize;
  25363. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  25364. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25365. iSize = sqlite3MallocSize(p);
  25366. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  25367. return iSize;
  25368. }
  25369. }
  25370. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  25371. /*
  25372. ** Allocate a new page object initially associated with cache pCache.
  25373. */
  25374. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  25375. PgHdr1 *p = 0;
  25376. void *pPg;
  25377. /* The group mutex must be released before pcache1Alloc() is called. This
  25378. ** is because it may call sqlite3_release_memory(), which assumes that
  25379. ** this mutex is not held. */
  25380. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25381. pcache1LeaveMutex(pCache->pGroup);
  25382. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  25383. pPg = pcache1Alloc(pCache->szPage);
  25384. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  25385. if( !pPg || !p ){
  25386. pcache1Free(pPg);
  25387. sqlite3_free(p);
  25388. pPg = 0;
  25389. }
  25390. #else
  25391. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  25392. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  25393. #endif
  25394. pcache1EnterMutex(pCache->pGroup);
  25395. if( pPg ){
  25396. p->page.pBuf = pPg;
  25397. p->page.pExtra = &p[1];
  25398. if( pCache->bPurgeable ){
  25399. pCache->pGroup->nCurrentPage++;
  25400. }
  25401. return p;
  25402. }
  25403. return 0;
  25404. }
  25405. /*
  25406. ** Free a page object allocated by pcache1AllocPage().
  25407. **
  25408. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  25409. ** that the current implementation happens to never call this routine
  25410. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  25411. */
  25412. static void pcache1FreePage(PgHdr1 *p){
  25413. if( ALWAYS(p) ){
  25414. PCache1 *pCache = p->pCache;
  25415. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  25416. pcache1Free(p->page.pBuf);
  25417. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  25418. sqlite3_free(p);
  25419. #endif
  25420. if( pCache->bPurgeable ){
  25421. pCache->pGroup->nCurrentPage--;
  25422. }
  25423. }
  25424. }
  25425. /*
  25426. ** Malloc function used by SQLite to obtain space from the buffer configured
  25427. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  25428. ** exists, this function falls back to sqlite3Malloc().
  25429. */
  25430. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  25431. return pcache1Alloc(sz);
  25432. }
  25433. /*
  25434. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  25435. */
  25436. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  25437. pcache1Free(p);
  25438. }
  25439. /*
  25440. ** Return true if it desirable to avoid allocating a new page cache
  25441. ** entry.
  25442. **
  25443. ** If memory was allocated specifically to the page cache using
  25444. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  25445. ** it is desirable to avoid allocating a new page cache entry because
  25446. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  25447. ** for all page cache needs and we should not need to spill the
  25448. ** allocation onto the heap.
  25449. **
  25450. ** Or, the heap is used for all page cache memory but the heap is
  25451. ** under memory pressure, then again it is desirable to avoid
  25452. ** allocating a new page cache entry in order to avoid stressing
  25453. ** the heap even further.
  25454. */
  25455. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  25456. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  25457. return pcache1.bUnderPressure;
  25458. }else{
  25459. return sqlite3HeapNearlyFull();
  25460. }
  25461. }
  25462. /******************************************************************************/
  25463. /******** General Implementation Functions ************************************/
  25464. /*
  25465. ** This function is used to resize the hash table used by the cache passed
  25466. ** as the first argument.
  25467. **
  25468. ** The PCache mutex must be held when this function is called.
  25469. */
  25470. static int pcache1ResizeHash(PCache1 *p){
  25471. PgHdr1 **apNew;
  25472. unsigned int nNew;
  25473. unsigned int i;
  25474. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  25475. nNew = p->nHash*2;
  25476. if( nNew<256 ){
  25477. nNew = 256;
  25478. }
  25479. pcache1LeaveMutex(p->pGroup);
  25480. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  25481. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  25482. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  25483. pcache1EnterMutex(p->pGroup);
  25484. if( apNew ){
  25485. for(i=0; i<p->nHash; i++){
  25486. PgHdr1 *pPage;
  25487. PgHdr1 *pNext = p->apHash[i];
  25488. while( (pPage = pNext)!=0 ){
  25489. unsigned int h = pPage->iKey % nNew;
  25490. pNext = pPage->pNext;
  25491. pPage->pNext = apNew[h];
  25492. apNew[h] = pPage;
  25493. }
  25494. }
  25495. sqlite3_free(p->apHash);
  25496. p->apHash = apNew;
  25497. p->nHash = nNew;
  25498. }
  25499. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  25500. }
  25501. /*
  25502. ** This function is used internally to remove the page pPage from the
  25503. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  25504. ** LRU list, then this function is a no-op.
  25505. **
  25506. ** The PGroup mutex must be held when this function is called.
  25507. **
  25508. ** If pPage is NULL then this routine is a no-op.
  25509. */
  25510. static void pcache1PinPage(PgHdr1 *pPage){
  25511. PCache1 *pCache;
  25512. PGroup *pGroup;
  25513. if( pPage==0 ) return;
  25514. pCache = pPage->pCache;
  25515. pGroup = pCache->pGroup;
  25516. assert( sqlite3_mutex_held(pGroup->mutex) );
  25517. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  25518. if( pPage->pLruPrev ){
  25519. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  25520. }
  25521. if( pPage->pLruNext ){
  25522. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  25523. }
  25524. if( pGroup->pLruHead==pPage ){
  25525. pGroup->pLruHead = pPage->pLruNext;
  25526. }
  25527. if( pGroup->pLruTail==pPage ){
  25528. pGroup->pLruTail = pPage->pLruPrev;
  25529. }
  25530. pPage->pLruNext = 0;
  25531. pPage->pLruPrev = 0;
  25532. pPage->pCache->nRecyclable--;
  25533. }
  25534. }
  25535. /*
  25536. ** Remove the page supplied as an argument from the hash table
  25537. ** (PCache1.apHash structure) that it is currently stored in.
  25538. **
  25539. ** The PGroup mutex must be held when this function is called.
  25540. */
  25541. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  25542. unsigned int h;
  25543. PCache1 *pCache = pPage->pCache;
  25544. PgHdr1 **pp;
  25545. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25546. h = pPage->iKey % pCache->nHash;
  25547. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  25548. *pp = (*pp)->pNext;
  25549. pCache->nPage--;
  25550. }
  25551. /*
  25552. ** If there are currently more than nMaxPage pages allocated, try
  25553. ** to recycle pages to reduce the number allocated to nMaxPage.
  25554. */
  25555. static void pcache1EnforceMaxPage(PGroup *pGroup){
  25556. assert( sqlite3_mutex_held(pGroup->mutex) );
  25557. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  25558. PgHdr1 *p = pGroup->pLruTail;
  25559. assert( p->pCache->pGroup==pGroup );
  25560. pcache1PinPage(p);
  25561. pcache1RemoveFromHash(p);
  25562. pcache1FreePage(p);
  25563. }
  25564. }
  25565. /*
  25566. ** Discard all pages from cache pCache with a page number (key value)
  25567. ** greater than or equal to iLimit. Any pinned pages that meet this
  25568. ** criteria are unpinned before they are discarded.
  25569. **
  25570. ** The PCache mutex must be held when this function is called.
  25571. */
  25572. static void pcache1TruncateUnsafe(
  25573. PCache1 *pCache, /* The cache to truncate */
  25574. unsigned int iLimit /* Drop pages with this pgno or larger */
  25575. ){
  25576. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  25577. unsigned int h;
  25578. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  25579. for(h=0; h<pCache->nHash; h++){
  25580. PgHdr1 **pp = &pCache->apHash[h];
  25581. PgHdr1 *pPage;
  25582. while( (pPage = *pp)!=0 ){
  25583. if( pPage->iKey>=iLimit ){
  25584. pCache->nPage--;
  25585. *pp = pPage->pNext;
  25586. pcache1PinPage(pPage);
  25587. pcache1FreePage(pPage);
  25588. }else{
  25589. pp = &pPage->pNext;
  25590. TESTONLY( nPage++; )
  25591. }
  25592. }
  25593. }
  25594. assert( pCache->nPage==nPage );
  25595. }
  25596. /******************************************************************************/
  25597. /******** sqlite3_pcache Methods **********************************************/
  25598. /*
  25599. ** Implementation of the sqlite3_pcache.xInit method.
  25600. */
  25601. static int pcache1Init(void *NotUsed){
  25602. UNUSED_PARAMETER(NotUsed);
  25603. assert( pcache1.isInit==0 );
  25604. memset(&pcache1, 0, sizeof(pcache1));
  25605. if( sqlite3GlobalConfig.bCoreMutex ){
  25606. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  25607. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  25608. }
  25609. pcache1.grp.mxPinned = 10;
  25610. pcache1.isInit = 1;
  25611. return SQLITE_OK;
  25612. }
  25613. /*
  25614. ** Implementation of the sqlite3_pcache.xShutdown method.
  25615. ** Note that the static mutex allocated in xInit does
  25616. ** not need to be freed.
  25617. */
  25618. static void pcache1Shutdown(void *NotUsed){
  25619. UNUSED_PARAMETER(NotUsed);
  25620. assert( pcache1.isInit!=0 );
  25621. memset(&pcache1, 0, sizeof(pcache1));
  25622. }
  25623. /*
  25624. ** Implementation of the sqlite3_pcache.xCreate method.
  25625. **
  25626. ** Allocate a new cache.
  25627. */
  25628. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  25629. PCache1 *pCache; /* The newly created page cache */
  25630. PGroup *pGroup; /* The group the new page cache will belong to */
  25631. int sz; /* Bytes of memory required to allocate the new cache */
  25632. /*
  25633. ** The separateCache variable is true if each PCache has its own private
  25634. ** PGroup. In other words, separateCache is true for mode (1) where no
  25635. ** mutexing is required.
  25636. **
  25637. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  25638. **
  25639. ** * Always use a unified cache in single-threaded applications
  25640. **
  25641. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  25642. ** use separate caches (mode-1)
  25643. */
  25644. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  25645. const int separateCache = 0;
  25646. #else
  25647. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  25648. #endif
  25649. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  25650. assert( szExtra < 300 );
  25651. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  25652. pCache = (PCache1 *)sqlite3MallocZero(sz);
  25653. if( pCache ){
  25654. if( separateCache ){
  25655. pGroup = (PGroup*)&pCache[1];
  25656. pGroup->mxPinned = 10;
  25657. }else{
  25658. pGroup = &pcache1.grp;
  25659. }
  25660. pCache->pGroup = pGroup;
  25661. pCache->szPage = szPage;
  25662. pCache->szExtra = szExtra;
  25663. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  25664. if( bPurgeable ){
  25665. pCache->nMin = 10;
  25666. pcache1EnterMutex(pGroup);
  25667. pGroup->nMinPage += pCache->nMin;
  25668. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25669. pcache1LeaveMutex(pGroup);
  25670. }
  25671. }
  25672. return (sqlite3_pcache *)pCache;
  25673. }
  25674. /*
  25675. ** Implementation of the sqlite3_pcache.xCachesize method.
  25676. **
  25677. ** Configure the cache_size limit for a cache.
  25678. */
  25679. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  25680. PCache1 *pCache = (PCache1 *)p;
  25681. if( pCache->bPurgeable ){
  25682. PGroup *pGroup = pCache->pGroup;
  25683. pcache1EnterMutex(pGroup);
  25684. pGroup->nMaxPage += (nMax - pCache->nMax);
  25685. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25686. pCache->nMax = nMax;
  25687. pCache->n90pct = pCache->nMax*9/10;
  25688. pcache1EnforceMaxPage(pGroup);
  25689. pcache1LeaveMutex(pGroup);
  25690. }
  25691. }
  25692. /*
  25693. ** Implementation of the sqlite3_pcache.xShrink method.
  25694. **
  25695. ** Free up as much memory as possible.
  25696. */
  25697. static void pcache1Shrink(sqlite3_pcache *p){
  25698. PCache1 *pCache = (PCache1*)p;
  25699. if( pCache->bPurgeable ){
  25700. PGroup *pGroup = pCache->pGroup;
  25701. int savedMaxPage;
  25702. pcache1EnterMutex(pGroup);
  25703. savedMaxPage = pGroup->nMaxPage;
  25704. pGroup->nMaxPage = 0;
  25705. pcache1EnforceMaxPage(pGroup);
  25706. pGroup->nMaxPage = savedMaxPage;
  25707. pcache1LeaveMutex(pGroup);
  25708. }
  25709. }
  25710. /*
  25711. ** Implementation of the sqlite3_pcache.xPagecount method.
  25712. */
  25713. static int pcache1Pagecount(sqlite3_pcache *p){
  25714. int n;
  25715. PCache1 *pCache = (PCache1*)p;
  25716. pcache1EnterMutex(pCache->pGroup);
  25717. n = pCache->nPage;
  25718. pcache1LeaveMutex(pCache->pGroup);
  25719. return n;
  25720. }
  25721. /*
  25722. ** Implementation of the sqlite3_pcache.xFetch method.
  25723. **
  25724. ** Fetch a page by key value.
  25725. **
  25726. ** Whether or not a new page may be allocated by this function depends on
  25727. ** the value of the createFlag argument. 0 means do not allocate a new
  25728. ** page. 1 means allocate a new page if space is easily available. 2
  25729. ** means to try really hard to allocate a new page.
  25730. **
  25731. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  25732. ** database) there is really no difference between createFlag 1 and 2. So
  25733. ** the calling function (pcache.c) will never have a createFlag of 1 on
  25734. ** a non-purgeable cache.
  25735. **
  25736. ** There are three different approaches to obtaining space for a page,
  25737. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  25738. **
  25739. ** 1. Regardless of the value of createFlag, the cache is searched for a
  25740. ** copy of the requested page. If one is found, it is returned.
  25741. **
  25742. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  25743. ** returned.
  25744. **
  25745. ** 3. If createFlag is 1, and the page is not already in the cache, then
  25746. ** return NULL (do not allocate a new page) if any of the following
  25747. ** conditions are true:
  25748. **
  25749. ** (a) the number of pages pinned by the cache is greater than
  25750. ** PCache1.nMax, or
  25751. **
  25752. ** (b) the number of pages pinned by the cache is greater than
  25753. ** the sum of nMax for all purgeable caches, less the sum of
  25754. ** nMin for all other purgeable caches, or
  25755. **
  25756. ** 4. If none of the first three conditions apply and the cache is marked
  25757. ** as purgeable, and if one of the following is true:
  25758. **
  25759. ** (a) The number of pages allocated for the cache is already
  25760. ** PCache1.nMax, or
  25761. **
  25762. ** (b) The number of pages allocated for all purgeable caches is
  25763. ** already equal to or greater than the sum of nMax for all
  25764. ** purgeable caches,
  25765. **
  25766. ** (c) The system is under memory pressure and wants to avoid
  25767. ** unnecessary pages cache entry allocations
  25768. **
  25769. ** then attempt to recycle a page from the LRU list. If it is the right
  25770. ** size, return the recycled buffer. Otherwise, free the buffer and
  25771. ** proceed to step 5.
  25772. **
  25773. ** 5. Otherwise, allocate and return a new page buffer.
  25774. */
  25775. static sqlite3_pcache_page *pcache1Fetch(
  25776. sqlite3_pcache *p,
  25777. unsigned int iKey,
  25778. int createFlag
  25779. ){
  25780. unsigned int nPinned;
  25781. PCache1 *pCache = (PCache1 *)p;
  25782. PGroup *pGroup;
  25783. PgHdr1 *pPage = 0;
  25784. assert( pCache->bPurgeable || createFlag!=1 );
  25785. assert( pCache->bPurgeable || pCache->nMin==0 );
  25786. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  25787. assert( pCache->nMin==0 || pCache->bPurgeable );
  25788. pcache1EnterMutex(pGroup = pCache->pGroup);
  25789. /* Step 1: Search the hash table for an existing entry. */
  25790. if( pCache->nHash>0 ){
  25791. unsigned int h = iKey % pCache->nHash;
  25792. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  25793. }
  25794. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  25795. if( pPage || createFlag==0 ){
  25796. pcache1PinPage(pPage);
  25797. goto fetch_out;
  25798. }
  25799. /* The pGroup local variable will normally be initialized by the
  25800. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  25801. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  25802. ** local variable here. Delaying the initialization of pGroup is an
  25803. ** optimization: The common case is to exit the module before reaching
  25804. ** this point.
  25805. */
  25806. #ifdef SQLITE_MUTEX_OMIT
  25807. pGroup = pCache->pGroup;
  25808. #endif
  25809. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  25810. assert( pCache->nPage >= pCache->nRecyclable );
  25811. nPinned = pCache->nPage - pCache->nRecyclable;
  25812. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  25813. assert( pCache->n90pct == pCache->nMax*9/10 );
  25814. if( createFlag==1 && (
  25815. nPinned>=pGroup->mxPinned
  25816. || nPinned>=pCache->n90pct
  25817. || pcache1UnderMemoryPressure(pCache)
  25818. )){
  25819. goto fetch_out;
  25820. }
  25821. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  25822. goto fetch_out;
  25823. }
  25824. assert( pCache->nHash>0 && pCache->apHash );
  25825. /* Step 4. Try to recycle a page. */
  25826. if( pCache->bPurgeable && pGroup->pLruTail && (
  25827. (pCache->nPage+1>=pCache->nMax)
  25828. || pGroup->nCurrentPage>=pGroup->nMaxPage
  25829. || pcache1UnderMemoryPressure(pCache)
  25830. )){
  25831. PCache1 *pOther;
  25832. pPage = pGroup->pLruTail;
  25833. pcache1RemoveFromHash(pPage);
  25834. pcache1PinPage(pPage);
  25835. pOther = pPage->pCache;
  25836. /* We want to verify that szPage and szExtra are the same for pOther
  25837. ** and pCache. Assert that we can verify this by comparing sums. */
  25838. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  25839. assert( pCache->szExtra<512 );
  25840. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  25841. assert( pOther->szExtra<512 );
  25842. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  25843. pcache1FreePage(pPage);
  25844. pPage = 0;
  25845. }else{
  25846. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  25847. }
  25848. }
  25849. /* Step 5. If a usable page buffer has still not been found,
  25850. ** attempt to allocate a new one.
  25851. */
  25852. if( !pPage ){
  25853. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  25854. pPage = pcache1AllocPage(pCache);
  25855. if( createFlag==1 ) sqlite3EndBenignMalloc();
  25856. }
  25857. if( pPage ){
  25858. unsigned int h = iKey % pCache->nHash;
  25859. pCache->nPage++;
  25860. pPage->iKey = iKey;
  25861. pPage->pNext = pCache->apHash[h];
  25862. pPage->pCache = pCache;
  25863. pPage->pLruPrev = 0;
  25864. pPage->pLruNext = 0;
  25865. *(void **)pPage->page.pExtra = 0;
  25866. pCache->apHash[h] = pPage;
  25867. }
  25868. fetch_out:
  25869. if( pPage && iKey>pCache->iMaxKey ){
  25870. pCache->iMaxKey = iKey;
  25871. }
  25872. pcache1LeaveMutex(pGroup);
  25873. return &pPage->page;
  25874. }
  25875. /*
  25876. ** Implementation of the sqlite3_pcache.xUnpin method.
  25877. **
  25878. ** Mark a page as unpinned (eligible for asynchronous recycling).
  25879. */
  25880. static void pcache1Unpin(
  25881. sqlite3_pcache *p,
  25882. sqlite3_pcache_page *pPg,
  25883. int reuseUnlikely
  25884. ){
  25885. PCache1 *pCache = (PCache1 *)p;
  25886. PgHdr1 *pPage = (PgHdr1 *)pPg;
  25887. PGroup *pGroup = pCache->pGroup;
  25888. assert( pPage->pCache==pCache );
  25889. pcache1EnterMutex(pGroup);
  25890. /* It is an error to call this function if the page is already
  25891. ** part of the PGroup LRU list.
  25892. */
  25893. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  25894. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  25895. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  25896. pcache1RemoveFromHash(pPage);
  25897. pcache1FreePage(pPage);
  25898. }else{
  25899. /* Add the page to the PGroup LRU list. */
  25900. if( pGroup->pLruHead ){
  25901. pGroup->pLruHead->pLruPrev = pPage;
  25902. pPage->pLruNext = pGroup->pLruHead;
  25903. pGroup->pLruHead = pPage;
  25904. }else{
  25905. pGroup->pLruTail = pPage;
  25906. pGroup->pLruHead = pPage;
  25907. }
  25908. pCache->nRecyclable++;
  25909. }
  25910. pcache1LeaveMutex(pCache->pGroup);
  25911. }
  25912. /*
  25913. ** Implementation of the sqlite3_pcache.xRekey method.
  25914. */
  25915. static void pcache1Rekey(
  25916. sqlite3_pcache *p,
  25917. sqlite3_pcache_page *pPg,
  25918. unsigned int iOld,
  25919. unsigned int iNew
  25920. ){
  25921. PCache1 *pCache = (PCache1 *)p;
  25922. PgHdr1 *pPage = (PgHdr1 *)pPg;
  25923. PgHdr1 **pp;
  25924. unsigned int h;
  25925. assert( pPage->iKey==iOld );
  25926. assert( pPage->pCache==pCache );
  25927. pcache1EnterMutex(pCache->pGroup);
  25928. h = iOld%pCache->nHash;
  25929. pp = &pCache->apHash[h];
  25930. while( (*pp)!=pPage ){
  25931. pp = &(*pp)->pNext;
  25932. }
  25933. *pp = pPage->pNext;
  25934. h = iNew%pCache->nHash;
  25935. pPage->iKey = iNew;
  25936. pPage->pNext = pCache->apHash[h];
  25937. pCache->apHash[h] = pPage;
  25938. if( iNew>pCache->iMaxKey ){
  25939. pCache->iMaxKey = iNew;
  25940. }
  25941. pcache1LeaveMutex(pCache->pGroup);
  25942. }
  25943. /*
  25944. ** Implementation of the sqlite3_pcache.xTruncate method.
  25945. **
  25946. ** Discard all unpinned pages in the cache with a page number equal to
  25947. ** or greater than parameter iLimit. Any pinned pages with a page number
  25948. ** equal to or greater than iLimit are implicitly unpinned.
  25949. */
  25950. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  25951. PCache1 *pCache = (PCache1 *)p;
  25952. pcache1EnterMutex(pCache->pGroup);
  25953. if( iLimit<=pCache->iMaxKey ){
  25954. pcache1TruncateUnsafe(pCache, iLimit);
  25955. pCache->iMaxKey = iLimit-1;
  25956. }
  25957. pcache1LeaveMutex(pCache->pGroup);
  25958. }
  25959. /*
  25960. ** Implementation of the sqlite3_pcache.xDestroy method.
  25961. **
  25962. ** Destroy a cache allocated using pcache1Create().
  25963. */
  25964. static void pcache1Destroy(sqlite3_pcache *p){
  25965. PCache1 *pCache = (PCache1 *)p;
  25966. PGroup *pGroup = pCache->pGroup;
  25967. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  25968. pcache1EnterMutex(pGroup);
  25969. pcache1TruncateUnsafe(pCache, 0);
  25970. assert( pGroup->nMaxPage >= pCache->nMax );
  25971. pGroup->nMaxPage -= pCache->nMax;
  25972. assert( pGroup->nMinPage >= pCache->nMin );
  25973. pGroup->nMinPage -= pCache->nMin;
  25974. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  25975. pcache1EnforceMaxPage(pGroup);
  25976. pcache1LeaveMutex(pGroup);
  25977. sqlite3_free(pCache->apHash);
  25978. sqlite3_free(pCache);
  25979. }
  25980. /*
  25981. ** This function is called during initialization (sqlite3_initialize()) to
  25982. ** install the default pluggable cache module, assuming the user has not
  25983. ** already provided an alternative.
  25984. */
  25985. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  25986. static const sqlite3_pcache_methods2 defaultMethods = {
  25987. 1, /* iVersion */
  25988. 0, /* pArg */
  25989. pcache1Init, /* xInit */
  25990. pcache1Shutdown, /* xShutdown */
  25991. pcache1Create, /* xCreate */
  25992. pcache1Cachesize, /* xCachesize */
  25993. pcache1Pagecount, /* xPagecount */
  25994. pcache1Fetch, /* xFetch */
  25995. pcache1Unpin, /* xUnpin */
  25996. pcache1Rekey, /* xRekey */
  25997. pcache1Truncate, /* xTruncate */
  25998. pcache1Destroy, /* xDestroy */
  25999. pcache1Shrink /* xShrink */
  26000. };
  26001. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  26002. }
  26003. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  26004. /*
  26005. ** This function is called to free superfluous dynamically allocated memory
  26006. ** held by the pager system. Memory in use by any SQLite pager allocated
  26007. ** by the current thread may be sqlite3_free()ed.
  26008. **
  26009. ** nReq is the number of bytes of memory required. Once this much has
  26010. ** been released, the function returns. The return value is the total number
  26011. ** of bytes of memory released.
  26012. */
  26013. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  26014. int nFree = 0;
  26015. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  26016. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  26017. if( pcache1.pStart==0 ){
  26018. PgHdr1 *p;
  26019. pcache1EnterMutex(&pcache1.grp);
  26020. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  26021. nFree += pcache1MemSize(p->page.pBuf);
  26022. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  26023. nFree += sqlite3MemSize(p);
  26024. #endif
  26025. pcache1PinPage(p);
  26026. pcache1RemoveFromHash(p);
  26027. pcache1FreePage(p);
  26028. }
  26029. pcache1LeaveMutex(&pcache1.grp);
  26030. }
  26031. return nFree;
  26032. }
  26033. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  26034. #ifdef SQLITE_TEST
  26035. /*
  26036. ** This function is used by test procedures to inspect the internal state
  26037. ** of the global cache.
  26038. */
  26039. SQLITE_PRIVATE void sqlite3PcacheStats(
  26040. int *pnCurrent, /* OUT: Total number of pages cached */
  26041. int *pnMax, /* OUT: Global maximum cache size */
  26042. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  26043. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  26044. ){
  26045. PgHdr1 *p;
  26046. int nRecyclable = 0;
  26047. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  26048. nRecyclable++;
  26049. }
  26050. *pnCurrent = pcache1.grp.nCurrentPage;
  26051. *pnMax = (int)pcache1.grp.nMaxPage;
  26052. *pnMin = (int)pcache1.grp.nMinPage;
  26053. *pnRecyclable = nRecyclable;
  26054. }
  26055. #endif
  26056. /************** End of pcache1.c *********************************************/
  26057. /************** Begin file rowset.c ******************************************/
  26058. /*
  26059. ** 2008 December 3
  26060. **
  26061. ** The author disclaims copyright to this source code. In place of
  26062. ** a legal notice, here is a blessing:
  26063. **
  26064. ** May you do good and not evil.
  26065. ** May you find forgiveness for yourself and forgive others.
  26066. ** May you share freely, never taking more than you give.
  26067. **
  26068. *************************************************************************
  26069. **
  26070. ** This module implements an object we call a "RowSet".
  26071. **
  26072. ** The RowSet object is a collection of rowids. Rowids
  26073. ** are inserted into the RowSet in an arbitrary order. Inserts
  26074. ** can be intermixed with tests to see if a given rowid has been
  26075. ** previously inserted into the RowSet.
  26076. **
  26077. ** After all inserts are finished, it is possible to extract the
  26078. ** elements of the RowSet in sorted order. Once this extraction
  26079. ** process has started, no new elements may be inserted.
  26080. **
  26081. ** Hence, the primitive operations for a RowSet are:
  26082. **
  26083. ** CREATE
  26084. ** INSERT
  26085. ** TEST
  26086. ** SMALLEST
  26087. ** DESTROY
  26088. **
  26089. ** The CREATE and DESTROY primitives are the constructor and destructor,
  26090. ** obviously. The INSERT primitive adds a new element to the RowSet.
  26091. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  26092. ** extracts the least value from the RowSet.
  26093. **
  26094. ** The INSERT primitive might allocate additional memory. Memory is
  26095. ** allocated in chunks so most INSERTs do no allocation. There is an
  26096. ** upper bound on the size of allocated memory. No memory is freed
  26097. ** until DESTROY.
  26098. **
  26099. ** The TEST primitive includes a "batch" number. The TEST primitive
  26100. ** will only see elements that were inserted before the last change
  26101. ** in the batch number. In other words, if an INSERT occurs between
  26102. ** two TESTs where the TESTs have the same batch nubmer, then the
  26103. ** value added by the INSERT will not be visible to the second TEST.
  26104. ** The initial batch number is zero, so if the very first TEST contains
  26105. ** a non-zero batch number, it will see all prior INSERTs.
  26106. **
  26107. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  26108. ** that is attempted.
  26109. **
  26110. ** The cost of an INSERT is roughly constant. (Sometime new memory
  26111. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  26112. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  26113. ** The cost of a TEST using the same batch number is O(logN). The cost
  26114. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  26115. ** primitives are constant time. The cost of DESTROY is O(N).
  26116. **
  26117. ** There is an added cost of O(N) when switching between TEST and
  26118. ** SMALLEST primitives.
  26119. */
  26120. /*
  26121. ** Target size for allocation chunks.
  26122. */
  26123. #define ROWSET_ALLOCATION_SIZE 1024
  26124. /*
  26125. ** The number of rowset entries per allocation chunk.
  26126. */
  26127. #define ROWSET_ENTRY_PER_CHUNK \
  26128. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  26129. /*
  26130. ** Each entry in a RowSet is an instance of the following object.
  26131. **
  26132. ** This same object is reused to store a linked list of trees of RowSetEntry
  26133. ** objects. In that alternative use, pRight points to the next entry
  26134. ** in the list, pLeft points to the tree, and v is unused. The
  26135. ** RowSet.pForest value points to the head of this forest list.
  26136. */
  26137. struct RowSetEntry {
  26138. i64 v; /* ROWID value for this entry */
  26139. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  26140. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  26141. };
  26142. /*
  26143. ** RowSetEntry objects are allocated in large chunks (instances of the
  26144. ** following structure) to reduce memory allocation overhead. The
  26145. ** chunks are kept on a linked list so that they can be deallocated
  26146. ** when the RowSet is destroyed.
  26147. */
  26148. struct RowSetChunk {
  26149. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  26150. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  26151. };
  26152. /*
  26153. ** A RowSet in an instance of the following structure.
  26154. **
  26155. ** A typedef of this structure if found in sqliteInt.h.
  26156. */
  26157. struct RowSet {
  26158. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  26159. sqlite3 *db; /* The database connection */
  26160. struct RowSetEntry *pEntry; /* List of entries using pRight */
  26161. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  26162. struct RowSetEntry *pFresh; /* Source of new entry objects */
  26163. struct RowSetEntry *pForest; /* List of binary trees of entries */
  26164. u16 nFresh; /* Number of objects on pFresh */
  26165. u8 rsFlags; /* Various flags */
  26166. u8 iBatch; /* Current insert batch */
  26167. };
  26168. /*
  26169. ** Allowed values for RowSet.rsFlags
  26170. */
  26171. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  26172. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  26173. /*
  26174. ** Turn bulk memory into a RowSet object. N bytes of memory
  26175. ** are available at pSpace. The db pointer is used as a memory context
  26176. ** for any subsequent allocations that need to occur.
  26177. ** Return a pointer to the new RowSet object.
  26178. **
  26179. ** It must be the case that N is sufficient to make a Rowset. If not
  26180. ** an assertion fault occurs.
  26181. **
  26182. ** If N is larger than the minimum, use the surplus as an initial
  26183. ** allocation of entries available to be filled.
  26184. */
  26185. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  26186. RowSet *p;
  26187. assert( N >= ROUND8(sizeof(*p)) );
  26188. p = pSpace;
  26189. p->pChunk = 0;
  26190. p->db = db;
  26191. p->pEntry = 0;
  26192. p->pLast = 0;
  26193. p->pForest = 0;
  26194. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  26195. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  26196. p->rsFlags = ROWSET_SORTED;
  26197. p->iBatch = 0;
  26198. return p;
  26199. }
  26200. /*
  26201. ** Deallocate all chunks from a RowSet. This frees all memory that
  26202. ** the RowSet has allocated over its lifetime. This routine is
  26203. ** the destructor for the RowSet.
  26204. */
  26205. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  26206. struct RowSetChunk *pChunk, *pNextChunk;
  26207. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  26208. pNextChunk = pChunk->pNextChunk;
  26209. sqlite3DbFree(p->db, pChunk);
  26210. }
  26211. p->pChunk = 0;
  26212. p->nFresh = 0;
  26213. p->pEntry = 0;
  26214. p->pLast = 0;
  26215. p->pForest = 0;
  26216. p->rsFlags = ROWSET_SORTED;
  26217. }
  26218. /*
  26219. ** Allocate a new RowSetEntry object that is associated with the
  26220. ** given RowSet. Return a pointer to the new and completely uninitialized
  26221. ** objected.
  26222. **
  26223. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  26224. ** routine returns NULL.
  26225. */
  26226. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  26227. assert( p!=0 );
  26228. if( p->nFresh==0 ){
  26229. struct RowSetChunk *pNew;
  26230. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  26231. if( pNew==0 ){
  26232. return 0;
  26233. }
  26234. pNew->pNextChunk = p->pChunk;
  26235. p->pChunk = pNew;
  26236. p->pFresh = pNew->aEntry;
  26237. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  26238. }
  26239. p->nFresh--;
  26240. return p->pFresh++;
  26241. }
  26242. /*
  26243. ** Insert a new value into a RowSet.
  26244. **
  26245. ** The mallocFailed flag of the database connection is set if a
  26246. ** memory allocation fails.
  26247. */
  26248. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  26249. struct RowSetEntry *pEntry; /* The new entry */
  26250. struct RowSetEntry *pLast; /* The last prior entry */
  26251. /* This routine is never called after sqlite3RowSetNext() */
  26252. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  26253. pEntry = rowSetEntryAlloc(p);
  26254. if( pEntry==0 ) return;
  26255. pEntry->v = rowid;
  26256. pEntry->pRight = 0;
  26257. pLast = p->pLast;
  26258. if( pLast ){
  26259. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  26260. p->rsFlags &= ~ROWSET_SORTED;
  26261. }
  26262. pLast->pRight = pEntry;
  26263. }else{
  26264. p->pEntry = pEntry;
  26265. }
  26266. p->pLast = pEntry;
  26267. }
  26268. /*
  26269. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  26270. **
  26271. ** The input lists are connected via pRight pointers and are
  26272. ** assumed to each already be in sorted order.
  26273. */
  26274. static struct RowSetEntry *rowSetEntryMerge(
  26275. struct RowSetEntry *pA, /* First sorted list to be merged */
  26276. struct RowSetEntry *pB /* Second sorted list to be merged */
  26277. ){
  26278. struct RowSetEntry head;
  26279. struct RowSetEntry *pTail;
  26280. pTail = &head;
  26281. while( pA && pB ){
  26282. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  26283. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  26284. if( pA->v<pB->v ){
  26285. pTail->pRight = pA;
  26286. pA = pA->pRight;
  26287. pTail = pTail->pRight;
  26288. }else if( pB->v<pA->v ){
  26289. pTail->pRight = pB;
  26290. pB = pB->pRight;
  26291. pTail = pTail->pRight;
  26292. }else{
  26293. pA = pA->pRight;
  26294. }
  26295. }
  26296. if( pA ){
  26297. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  26298. pTail->pRight = pA;
  26299. }else{
  26300. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  26301. pTail->pRight = pB;
  26302. }
  26303. return head.pRight;
  26304. }
  26305. /*
  26306. ** Sort all elements on the list of RowSetEntry objects into order of
  26307. ** increasing v.
  26308. */
  26309. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  26310. unsigned int i;
  26311. struct RowSetEntry *pNext, *aBucket[40];
  26312. memset(aBucket, 0, sizeof(aBucket));
  26313. while( pIn ){
  26314. pNext = pIn->pRight;
  26315. pIn->pRight = 0;
  26316. for(i=0; aBucket[i]; i++){
  26317. pIn = rowSetEntryMerge(aBucket[i], pIn);
  26318. aBucket[i] = 0;
  26319. }
  26320. aBucket[i] = pIn;
  26321. pIn = pNext;
  26322. }
  26323. pIn = 0;
  26324. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  26325. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  26326. }
  26327. return pIn;
  26328. }
  26329. /*
  26330. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  26331. ** Convert this tree into a linked list connected by the pRight pointers
  26332. ** and return pointers to the first and last elements of the new list.
  26333. */
  26334. static void rowSetTreeToList(
  26335. struct RowSetEntry *pIn, /* Root of the input tree */
  26336. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  26337. struct RowSetEntry **ppLast /* Write tail of the output list here */
  26338. ){
  26339. assert( pIn!=0 );
  26340. if( pIn->pLeft ){
  26341. struct RowSetEntry *p;
  26342. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  26343. p->pRight = pIn;
  26344. }else{
  26345. *ppFirst = pIn;
  26346. }
  26347. if( pIn->pRight ){
  26348. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  26349. }else{
  26350. *ppLast = pIn;
  26351. }
  26352. assert( (*ppLast)->pRight==0 );
  26353. }
  26354. /*
  26355. ** Convert a sorted list of elements (connected by pRight) into a binary
  26356. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  26357. ** node taken from the head of *ppList. A depth of 2 means a tree with
  26358. ** three nodes. And so forth.
  26359. **
  26360. ** Use as many entries from the input list as required and update the
  26361. ** *ppList to point to the unused elements of the list. If the input
  26362. ** list contains too few elements, then construct an incomplete tree
  26363. ** and leave *ppList set to NULL.
  26364. **
  26365. ** Return a pointer to the root of the constructed binary tree.
  26366. */
  26367. static struct RowSetEntry *rowSetNDeepTree(
  26368. struct RowSetEntry **ppList,
  26369. int iDepth
  26370. ){
  26371. struct RowSetEntry *p; /* Root of the new tree */
  26372. struct RowSetEntry *pLeft; /* Left subtree */
  26373. if( *ppList==0 ){
  26374. return 0;
  26375. }
  26376. if( iDepth==1 ){
  26377. p = *ppList;
  26378. *ppList = p->pRight;
  26379. p->pLeft = p->pRight = 0;
  26380. return p;
  26381. }
  26382. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  26383. p = *ppList;
  26384. if( p==0 ){
  26385. return pLeft;
  26386. }
  26387. p->pLeft = pLeft;
  26388. *ppList = p->pRight;
  26389. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  26390. return p;
  26391. }
  26392. /*
  26393. ** Convert a sorted list of elements into a binary tree. Make the tree
  26394. ** as deep as it needs to be in order to contain the entire list.
  26395. */
  26396. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  26397. int iDepth; /* Depth of the tree so far */
  26398. struct RowSetEntry *p; /* Current tree root */
  26399. struct RowSetEntry *pLeft; /* Left subtree */
  26400. assert( pList!=0 );
  26401. p = pList;
  26402. pList = p->pRight;
  26403. p->pLeft = p->pRight = 0;
  26404. for(iDepth=1; pList; iDepth++){
  26405. pLeft = p;
  26406. p = pList;
  26407. pList = p->pRight;
  26408. p->pLeft = pLeft;
  26409. p->pRight = rowSetNDeepTree(&pList, iDepth);
  26410. }
  26411. return p;
  26412. }
  26413. /*
  26414. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  26415. ** sort them all together into one big ordered list on p->pEntry.
  26416. **
  26417. ** This routine should only be called once in the life of a RowSet.
  26418. */
  26419. static void rowSetToList(RowSet *p){
  26420. /* This routine is called only once */
  26421. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  26422. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  26423. p->pEntry = rowSetEntrySort(p->pEntry);
  26424. }
  26425. /* While this module could theoretically support it, sqlite3RowSetNext()
  26426. ** is never called after sqlite3RowSetText() for the same RowSet. So
  26427. ** there is never a forest to deal with. Should this change, simply
  26428. ** remove the assert() and the #if 0. */
  26429. assert( p->pForest==0 );
  26430. #if 0
  26431. while( p->pForest ){
  26432. struct RowSetEntry *pTree = p->pForest->pLeft;
  26433. if( pTree ){
  26434. struct RowSetEntry *pHead, *pTail;
  26435. rowSetTreeToList(pTree, &pHead, &pTail);
  26436. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  26437. }
  26438. p->pForest = p->pForest->pRight;
  26439. }
  26440. #endif
  26441. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  26442. }
  26443. /*
  26444. ** Extract the smallest element from the RowSet.
  26445. ** Write the element into *pRowid. Return 1 on success. Return
  26446. ** 0 if the RowSet is already empty.
  26447. **
  26448. ** After this routine has been called, the sqlite3RowSetInsert()
  26449. ** routine may not be called again.
  26450. */
  26451. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  26452. assert( p!=0 );
  26453. /* Merge the forest into a single sorted list on first call */
  26454. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  26455. /* Return the next entry on the list */
  26456. if( p->pEntry ){
  26457. *pRowid = p->pEntry->v;
  26458. p->pEntry = p->pEntry->pRight;
  26459. if( p->pEntry==0 ){
  26460. sqlite3RowSetClear(p);
  26461. }
  26462. return 1;
  26463. }else{
  26464. return 0;
  26465. }
  26466. }
  26467. /*
  26468. ** Check to see if element iRowid was inserted into the rowset as
  26469. ** part of any insert batch prior to iBatch. Return 1 or 0.
  26470. **
  26471. ** If this is the first test of a new batch and if there exist entires
  26472. ** on pRowSet->pEntry, then sort those entires into the forest at
  26473. ** pRowSet->pForest so that they can be tested.
  26474. */
  26475. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  26476. struct RowSetEntry *p, *pTree;
  26477. /* This routine is never called after sqlite3RowSetNext() */
  26478. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  26479. /* Sort entries into the forest on the first test of a new batch
  26480. */
  26481. if( iBatch!=pRowSet->iBatch ){
  26482. p = pRowSet->pEntry;
  26483. if( p ){
  26484. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  26485. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  26486. p = rowSetEntrySort(p);
  26487. }
  26488. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  26489. ppPrevTree = &pTree->pRight;
  26490. if( pTree->pLeft==0 ){
  26491. pTree->pLeft = rowSetListToTree(p);
  26492. break;
  26493. }else{
  26494. struct RowSetEntry *pAux, *pTail;
  26495. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  26496. pTree->pLeft = 0;
  26497. p = rowSetEntryMerge(pAux, p);
  26498. }
  26499. }
  26500. if( pTree==0 ){
  26501. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  26502. if( pTree ){
  26503. pTree->v = 0;
  26504. pTree->pRight = 0;
  26505. pTree->pLeft = rowSetListToTree(p);
  26506. }
  26507. }
  26508. pRowSet->pEntry = 0;
  26509. pRowSet->pLast = 0;
  26510. pRowSet->rsFlags |= ROWSET_SORTED;
  26511. }
  26512. pRowSet->iBatch = iBatch;
  26513. }
  26514. /* Test to see if the iRowid value appears anywhere in the forest.
  26515. ** Return 1 if it does and 0 if not.
  26516. */
  26517. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  26518. p = pTree->pLeft;
  26519. while( p ){
  26520. if( p->v<iRowid ){
  26521. p = p->pRight;
  26522. }else if( p->v>iRowid ){
  26523. p = p->pLeft;
  26524. }else{
  26525. return 1;
  26526. }
  26527. }
  26528. }
  26529. return 0;
  26530. }
  26531. /************** End of rowset.c **********************************************/
  26532. /************** Begin file pager.c *******************************************/
  26533. /*
  26534. ** 2001 September 15
  26535. **
  26536. ** The author disclaims copyright to this source code. In place of
  26537. ** a legal notice, here is a blessing:
  26538. **
  26539. ** May you do good and not evil.
  26540. ** May you find forgiveness for yourself and forgive others.
  26541. ** May you share freely, never taking more than you give.
  26542. **
  26543. *************************************************************************
  26544. ** This is the implementation of the page cache subsystem or "pager".
  26545. **
  26546. ** The pager is used to access a database disk file. It implements
  26547. ** atomic commit and rollback through the use of a journal file that
  26548. ** is separate from the database file. The pager also implements file
  26549. ** locking to prevent two processes from writing the same database
  26550. ** file simultaneously, or one process from reading the database while
  26551. ** another is writing.
  26552. */
  26553. #ifndef SQLITE_OMIT_DISKIO
  26554. /************** Include wal.h in the middle of pager.c ***********************/
  26555. /************** Begin file wal.h *********************************************/
  26556. /*
  26557. ** 2010 February 1
  26558. **
  26559. ** The author disclaims copyright to this source code. In place of
  26560. ** a legal notice, here is a blessing:
  26561. **
  26562. ** May you do good and not evil.
  26563. ** May you find forgiveness for yourself and forgive others.
  26564. ** May you share freely, never taking more than you give.
  26565. **
  26566. *************************************************************************
  26567. ** This header file defines the interface to the write-ahead logging
  26568. ** system. Refer to the comments below and the header comment attached to
  26569. ** the implementation of each function in log.c for further details.
  26570. */
  26571. #ifndef _WAL_H_
  26572. #define _WAL_H_
  26573. /* Additional values that can be added to the sync_flags argument of
  26574. ** sqlite3WalFrames():
  26575. */
  26576. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  26577. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  26578. #ifdef SQLITE_OMIT_WAL
  26579. # define sqlite3WalOpen(x,y,z) 0
  26580. # define sqlite3WalLimit(x,y)
  26581. # define sqlite3WalClose(w,x,y,z) 0
  26582. # define sqlite3WalBeginReadTransaction(y,z) 0
  26583. # define sqlite3WalEndReadTransaction(z)
  26584. # define sqlite3WalDbsize(y) 0
  26585. # define sqlite3WalBeginWriteTransaction(y) 0
  26586. # define sqlite3WalEndWriteTransaction(x) 0
  26587. # define sqlite3WalUndo(x,y,z) 0
  26588. # define sqlite3WalSavepoint(y,z)
  26589. # define sqlite3WalSavepointUndo(y,z) 0
  26590. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  26591. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  26592. # define sqlite3WalCallback(z) 0
  26593. # define sqlite3WalExclusiveMode(y,z) 0
  26594. # define sqlite3WalHeapMemory(z) 0
  26595. # define sqlite3WalFramesize(z) 0
  26596. # define sqlite3WalFindFrame(x,y,z) 0
  26597. #else
  26598. #define WAL_SAVEPOINT_NDATA 4
  26599. /* Connection to a write-ahead log (WAL) file.
  26600. ** There is one object of this type for each pager.
  26601. */
  26602. typedef struct Wal Wal;
  26603. /* Open and close a connection to a write-ahead log. */
  26604. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  26605. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  26606. /* Set the limiting size of a WAL file. */
  26607. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  26608. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  26609. ** snapshot is like a read-transaction. It is the state of the database
  26610. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  26611. ** preserves the current state even if the other threads or processes
  26612. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  26613. ** transaction and releases the lock.
  26614. */
  26615. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  26616. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  26617. /* Read a page from the write-ahead log, if it is present. */
  26618. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  26619. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  26620. /* If the WAL is not empty, return the size of the database. */
  26621. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  26622. /* Obtain or release the WRITER lock. */
  26623. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  26624. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  26625. /* Undo any frames written (but not committed) to the log */
  26626. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  26627. /* Return an integer that records the current (uncommitted) write
  26628. ** position in the WAL */
  26629. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  26630. /* Move the write position of the WAL back to iFrame. Called in
  26631. ** response to a ROLLBACK TO command. */
  26632. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  26633. /* Write a frame or frames to the log. */
  26634. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  26635. /* Copy pages from the log to the database file */
  26636. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  26637. Wal *pWal, /* Write-ahead log connection */
  26638. int eMode, /* One of PASSIVE, FULL and RESTART */
  26639. int (*xBusy)(void*), /* Function to call when busy */
  26640. void *pBusyArg, /* Context argument for xBusyHandler */
  26641. int sync_flags, /* Flags to sync db file with (or 0) */
  26642. int nBuf, /* Size of buffer nBuf */
  26643. u8 *zBuf, /* Temporary buffer to use */
  26644. int *pnLog, /* OUT: Number of frames in WAL */
  26645. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  26646. );
  26647. /* Return the value to pass to a sqlite3_wal_hook callback, the
  26648. ** number of frames in the WAL at the point of the last commit since
  26649. ** sqlite3WalCallback() was called. If no commits have occurred since
  26650. ** the last call, then return 0.
  26651. */
  26652. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  26653. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  26654. ** by the pager layer on the database file.
  26655. */
  26656. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  26657. /* Return true if the argument is non-NULL and the WAL module is using
  26658. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  26659. ** WAL module is using shared-memory, return false.
  26660. */
  26661. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  26662. #ifdef SQLITE_ENABLE_ZIPVFS
  26663. /* If the WAL file is not empty, return the number of bytes of content
  26664. ** stored in each frame (i.e. the db page-size when the WAL was created).
  26665. */
  26666. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  26667. #endif
  26668. #endif /* ifndef SQLITE_OMIT_WAL */
  26669. #endif /* _WAL_H_ */
  26670. /************** End of wal.h *************************************************/
  26671. /************** Continuing where we left off in pager.c **********************/
  26672. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  26673. **
  26674. ** This comment block describes invariants that hold when using a rollback
  26675. ** journal. These invariants do not apply for journal_mode=WAL,
  26676. ** journal_mode=MEMORY, or journal_mode=OFF.
  26677. **
  26678. ** Within this comment block, a page is deemed to have been synced
  26679. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  26680. ** Otherwise, the page is not synced until the xSync method of the VFS
  26681. ** is called successfully on the file containing the page.
  26682. **
  26683. ** Definition: A page of the database file is said to be "overwriteable" if
  26684. ** one or more of the following are true about the page:
  26685. **
  26686. ** (a) The original content of the page as it was at the beginning of
  26687. ** the transaction has been written into the rollback journal and
  26688. ** synced.
  26689. **
  26690. ** (b) The page was a freelist leaf page at the start of the transaction.
  26691. **
  26692. ** (c) The page number is greater than the largest page that existed in
  26693. ** the database file at the start of the transaction.
  26694. **
  26695. ** (1) A page of the database file is never overwritten unless one of the
  26696. ** following are true:
  26697. **
  26698. ** (a) The page and all other pages on the same sector are overwriteable.
  26699. **
  26700. ** (b) The atomic page write optimization is enabled, and the entire
  26701. ** transaction other than the update of the transaction sequence
  26702. ** number consists of a single page change.
  26703. **
  26704. ** (2) The content of a page written into the rollback journal exactly matches
  26705. ** both the content in the database when the rollback journal was written
  26706. ** and the content in the database at the beginning of the current
  26707. ** transaction.
  26708. **
  26709. ** (3) Writes to the database file are an integer multiple of the page size
  26710. ** in length and are aligned on a page boundary.
  26711. **
  26712. ** (4) Reads from the database file are either aligned on a page boundary and
  26713. ** an integer multiple of the page size in length or are taken from the
  26714. ** first 100 bytes of the database file.
  26715. **
  26716. ** (5) All writes to the database file are synced prior to the rollback journal
  26717. ** being deleted, truncated, or zeroed.
  26718. **
  26719. ** (6) If a master journal file is used, then all writes to the database file
  26720. ** are synced prior to the master journal being deleted.
  26721. **
  26722. ** Definition: Two databases (or the same database at two points it time)
  26723. ** are said to be "logically equivalent" if they give the same answer to
  26724. ** all queries. Note in particular the content of freelist leaf
  26725. ** pages can be changed arbitarily without effecting the logical equivalence
  26726. ** of the database.
  26727. **
  26728. ** (7) At any time, if any subset, including the empty set and the total set,
  26729. ** of the unsynced changes to a rollback journal are removed and the
  26730. ** journal is rolled back, the resulting database file will be logical
  26731. ** equivalent to the database file at the beginning of the transaction.
  26732. **
  26733. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  26734. ** is called to restore the database file to the same size it was at
  26735. ** the beginning of the transaction. (In some VFSes, the xTruncate
  26736. ** method is a no-op, but that does not change the fact the SQLite will
  26737. ** invoke it.)
  26738. **
  26739. ** (9) Whenever the database file is modified, at least one bit in the range
  26740. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  26741. ** the EXCLUSIVE lock, thus signaling other connections on the same
  26742. ** database to flush their caches.
  26743. **
  26744. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  26745. ** than one billion transactions.
  26746. **
  26747. ** (11) A database file is well-formed at the beginning and at the conclusion
  26748. ** of every transaction.
  26749. **
  26750. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  26751. ** the database file.
  26752. **
  26753. ** (13) A SHARED lock is held on the database file while reading any
  26754. ** content out of the database file.
  26755. **
  26756. ******************************************************************************/
  26757. /*
  26758. ** Macros for troubleshooting. Normally turned off
  26759. */
  26760. #if 0
  26761. int sqlite3PagerTrace=1; /* True to enable tracing */
  26762. #define sqlite3DebugPrintf printf
  26763. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  26764. #else
  26765. #define PAGERTRACE(X)
  26766. #endif
  26767. /*
  26768. ** The following two macros are used within the PAGERTRACE() macros above
  26769. ** to print out file-descriptors.
  26770. **
  26771. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  26772. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  26773. ** struct as its argument.
  26774. */
  26775. #define PAGERID(p) ((int)(p->fd))
  26776. #define FILEHANDLEID(fd) ((int)fd)
  26777. /*
  26778. ** The Pager.eState variable stores the current 'state' of a pager. A
  26779. ** pager may be in any one of the seven states shown in the following
  26780. ** state diagram.
  26781. **
  26782. ** OPEN <------+------+
  26783. ** | | |
  26784. ** V | |
  26785. ** +---------> READER-------+ |
  26786. ** | | |
  26787. ** | V |
  26788. ** |<-------WRITER_LOCKED------> ERROR
  26789. ** | | ^
  26790. ** | V |
  26791. ** |<------WRITER_CACHEMOD-------->|
  26792. ** | | |
  26793. ** | V |
  26794. ** |<-------WRITER_DBMOD---------->|
  26795. ** | | |
  26796. ** | V |
  26797. ** +<------WRITER_FINISHED-------->+
  26798. **
  26799. **
  26800. ** List of state transitions and the C [function] that performs each:
  26801. **
  26802. ** OPEN -> READER [sqlite3PagerSharedLock]
  26803. ** READER -> OPEN [pager_unlock]
  26804. **
  26805. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  26806. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  26807. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  26808. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  26809. ** WRITER_*** -> READER [pager_end_transaction]
  26810. **
  26811. ** WRITER_*** -> ERROR [pager_error]
  26812. ** ERROR -> OPEN [pager_unlock]
  26813. **
  26814. **
  26815. ** OPEN:
  26816. **
  26817. ** The pager starts up in this state. Nothing is guaranteed in this
  26818. ** state - the file may or may not be locked and the database size is
  26819. ** unknown. The database may not be read or written.
  26820. **
  26821. ** * No read or write transaction is active.
  26822. ** * Any lock, or no lock at all, may be held on the database file.
  26823. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  26824. **
  26825. ** READER:
  26826. **
  26827. ** In this state all the requirements for reading the database in
  26828. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  26829. ** was) in exclusive-locking mode, a user-level read transaction is
  26830. ** open. The database size is known in this state.
  26831. **
  26832. ** A connection running with locking_mode=normal enters this state when
  26833. ** it opens a read-transaction on the database and returns to state
  26834. ** OPEN after the read-transaction is completed. However a connection
  26835. ** running in locking_mode=exclusive (including temp databases) remains in
  26836. ** this state even after the read-transaction is closed. The only way
  26837. ** a locking_mode=exclusive connection can transition from READER to OPEN
  26838. ** is via the ERROR state (see below).
  26839. **
  26840. ** * A read transaction may be active (but a write-transaction cannot).
  26841. ** * A SHARED or greater lock is held on the database file.
  26842. ** * The dbSize variable may be trusted (even if a user-level read
  26843. ** transaction is not active). The dbOrigSize and dbFileSize variables
  26844. ** may not be trusted at this point.
  26845. ** * If the database is a WAL database, then the WAL connection is open.
  26846. ** * Even if a read-transaction is not open, it is guaranteed that
  26847. ** there is no hot-journal in the file-system.
  26848. **
  26849. ** WRITER_LOCKED:
  26850. **
  26851. ** The pager moves to this state from READER when a write-transaction
  26852. ** is first opened on the database. In WRITER_LOCKED state, all locks
  26853. ** required to start a write-transaction are held, but no actual
  26854. ** modifications to the cache or database have taken place.
  26855. **
  26856. ** In rollback mode, a RESERVED or (if the transaction was opened with
  26857. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  26858. ** moving to this state, but the journal file is not written to or opened
  26859. ** to in this state. If the transaction is committed or rolled back while
  26860. ** in WRITER_LOCKED state, all that is required is to unlock the database
  26861. ** file.
  26862. **
  26863. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  26864. ** If the connection is running with locking_mode=exclusive, an attempt
  26865. ** is made to obtain an EXCLUSIVE lock on the database file.
  26866. **
  26867. ** * A write transaction is active.
  26868. ** * If the connection is open in rollback-mode, a RESERVED or greater
  26869. ** lock is held on the database file.
  26870. ** * If the connection is open in WAL-mode, a WAL write transaction
  26871. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  26872. ** called).
  26873. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  26874. ** * The contents of the pager cache have not been modified.
  26875. ** * The journal file may or may not be open.
  26876. ** * Nothing (not even the first header) has been written to the journal.
  26877. **
  26878. ** WRITER_CACHEMOD:
  26879. **
  26880. ** A pager moves from WRITER_LOCKED state to this state when a page is
  26881. ** first modified by the upper layer. In rollback mode the journal file
  26882. ** is opened (if it is not already open) and a header written to the
  26883. ** start of it. The database file on disk has not been modified.
  26884. **
  26885. ** * A write transaction is active.
  26886. ** * A RESERVED or greater lock is held on the database file.
  26887. ** * The journal file is open and the first header has been written
  26888. ** to it, but the header has not been synced to disk.
  26889. ** * The contents of the page cache have been modified.
  26890. **
  26891. ** WRITER_DBMOD:
  26892. **
  26893. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  26894. ** when it modifies the contents of the database file. WAL connections
  26895. ** never enter this state (since they do not modify the database file,
  26896. ** just the log file).
  26897. **
  26898. ** * A write transaction is active.
  26899. ** * An EXCLUSIVE or greater lock is held on the database file.
  26900. ** * The journal file is open and the first header has been written
  26901. ** and synced to disk.
  26902. ** * The contents of the page cache have been modified (and possibly
  26903. ** written to disk).
  26904. **
  26905. ** WRITER_FINISHED:
  26906. **
  26907. ** It is not possible for a WAL connection to enter this state.
  26908. **
  26909. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  26910. ** state after the entire transaction has been successfully written into the
  26911. ** database file. In this state the transaction may be committed simply
  26912. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  26913. ** not possible to modify the database further. At this point, the upper
  26914. ** layer must either commit or rollback the transaction.
  26915. **
  26916. ** * A write transaction is active.
  26917. ** * An EXCLUSIVE or greater lock is held on the database file.
  26918. ** * All writing and syncing of journal and database data has finished.
  26919. ** If no error occurred, all that remains is to finalize the journal to
  26920. ** commit the transaction. If an error did occur, the caller will need
  26921. ** to rollback the transaction.
  26922. **
  26923. ** ERROR:
  26924. **
  26925. ** The ERROR state is entered when an IO or disk-full error (including
  26926. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  26927. ** difficult to be sure that the in-memory pager state (cache contents,
  26928. ** db size etc.) are consistent with the contents of the file-system.
  26929. **
  26930. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  26931. ** cannot.
  26932. **
  26933. ** For example, if an IO error occurs while performing a rollback,
  26934. ** the contents of the page-cache may be left in an inconsistent state.
  26935. ** At this point it would be dangerous to change back to READER state
  26936. ** (as usually happens after a rollback). Any subsequent readers might
  26937. ** report database corruption (due to the inconsistent cache), and if
  26938. ** they upgrade to writers, they may inadvertently corrupt the database
  26939. ** file. To avoid this hazard, the pager switches into the ERROR state
  26940. ** instead of READER following such an error.
  26941. **
  26942. ** Once it has entered the ERROR state, any attempt to use the pager
  26943. ** to read or write data returns an error. Eventually, once all
  26944. ** outstanding transactions have been abandoned, the pager is able to
  26945. ** transition back to OPEN state, discarding the contents of the
  26946. ** page-cache and any other in-memory state at the same time. Everything
  26947. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  26948. ** when a read-transaction is next opened on the pager (transitioning
  26949. ** the pager into READER state). At that point the system has recovered
  26950. ** from the error.
  26951. **
  26952. ** Specifically, the pager jumps into the ERROR state if:
  26953. **
  26954. ** 1. An error occurs while attempting a rollback. This happens in
  26955. ** function sqlite3PagerRollback().
  26956. **
  26957. ** 2. An error occurs while attempting to finalize a journal file
  26958. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  26959. **
  26960. ** 3. An error occurs while attempting to write to the journal or
  26961. ** database file in function pagerStress() in order to free up
  26962. ** memory.
  26963. **
  26964. ** In other cases, the error is returned to the b-tree layer. The b-tree
  26965. ** layer then attempts a rollback operation. If the error condition
  26966. ** persists, the pager enters the ERROR state via condition (1) above.
  26967. **
  26968. ** Condition (3) is necessary because it can be triggered by a read-only
  26969. ** statement executed within a transaction. In this case, if the error
  26970. ** code were simply returned to the user, the b-tree layer would not
  26971. ** automatically attempt a rollback, as it assumes that an error in a
  26972. ** read-only statement cannot leave the pager in an internally inconsistent
  26973. ** state.
  26974. **
  26975. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  26976. ** * There are one or more outstanding references to pages (after the
  26977. ** last reference is dropped the pager should move back to OPEN state).
  26978. ** * The pager is not an in-memory pager.
  26979. **
  26980. **
  26981. ** Notes:
  26982. **
  26983. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  26984. ** connection is open in WAL mode. A WAL connection is always in one
  26985. ** of the first four states.
  26986. **
  26987. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  26988. ** state. There are two exceptions: immediately after exclusive-mode has
  26989. ** been turned on (and before any read or write transactions are
  26990. ** executed), and when the pager is leaving the "error state".
  26991. **
  26992. ** * See also: assert_pager_state().
  26993. */
  26994. #define PAGER_OPEN 0
  26995. #define PAGER_READER 1
  26996. #define PAGER_WRITER_LOCKED 2
  26997. #define PAGER_WRITER_CACHEMOD 3
  26998. #define PAGER_WRITER_DBMOD 4
  26999. #define PAGER_WRITER_FINISHED 5
  27000. #define PAGER_ERROR 6
  27001. /*
  27002. ** The Pager.eLock variable is almost always set to one of the
  27003. ** following locking-states, according to the lock currently held on
  27004. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  27005. ** This variable is kept up to date as locks are taken and released by
  27006. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  27007. **
  27008. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  27009. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  27010. ** the operation was successful. In these circumstances pagerLockDb() and
  27011. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  27012. ** when unlocking the file, and only updated when locking the file if the
  27013. ** VFS call is successful. This way, the Pager.eLock variable may be set
  27014. ** to a less exclusive (lower) value than the lock that is actually held
  27015. ** at the system level, but it is never set to a more exclusive value.
  27016. **
  27017. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  27018. ** be a few redundant xLock() calls or a lock may be held for longer than
  27019. ** required, but nothing really goes wrong.
  27020. **
  27021. ** The exception is when the database file is unlocked as the pager moves
  27022. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  27023. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  27024. ** transition, by the same pager or any other). If the call to xUnlock()
  27025. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  27026. ** can confuse the call to xCheckReservedLock() call made later as part
  27027. ** of hot-journal detection.
  27028. **
  27029. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  27030. ** lock held by this process or any others". So xCheckReservedLock may
  27031. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  27032. ** doesn't know it because of a previous error in xUnlock). If this happens
  27033. ** a hot-journal may be mistaken for a journal being created by an active
  27034. ** transaction in another process, causing SQLite to read from the database
  27035. ** without rolling it back.
  27036. **
  27037. ** To work around this, if a call to xUnlock() fails when unlocking the
  27038. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  27039. ** is only changed back to a real locking state after a successful call
  27040. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  27041. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  27042. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  27043. ** lock on the database file before attempting to roll it back. See function
  27044. ** PagerSharedLock() for more detail.
  27045. **
  27046. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  27047. ** PAGER_OPEN state.
  27048. */
  27049. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  27050. /*
  27051. ** A macro used for invoking the codec if there is one
  27052. */
  27053. #ifdef SQLITE_HAS_CODEC
  27054. # define CODEC1(P,D,N,X,E) \
  27055. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  27056. # define CODEC2(P,D,N,X,E,O) \
  27057. if( P->xCodec==0 ){ O=(char*)D; }else \
  27058. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  27059. #else
  27060. # define CODEC1(P,D,N,X,E) /* NO-OP */
  27061. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  27062. #endif
  27063. /*
  27064. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  27065. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  27066. ** This could conceivably cause corruption following a power failure on
  27067. ** such a system. This is currently an undocumented limit.
  27068. */
  27069. #define MAX_SECTOR_SIZE 0x10000
  27070. /*
  27071. ** An instance of the following structure is allocated for each active
  27072. ** savepoint and statement transaction in the system. All such structures
  27073. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  27074. ** resized using sqlite3Realloc().
  27075. **
  27076. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  27077. ** set to 0. If a journal-header is written into the main journal while
  27078. ** the savepoint is active, then iHdrOffset is set to the byte offset
  27079. ** immediately following the last journal record written into the main
  27080. ** journal before the journal-header. This is required during savepoint
  27081. ** rollback (see pagerPlaybackSavepoint()).
  27082. */
  27083. typedef struct PagerSavepoint PagerSavepoint;
  27084. struct PagerSavepoint {
  27085. i64 iOffset; /* Starting offset in main journal */
  27086. i64 iHdrOffset; /* See above */
  27087. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  27088. Pgno nOrig; /* Original number of pages in file */
  27089. Pgno iSubRec; /* Index of first record in sub-journal */
  27090. #ifndef SQLITE_OMIT_WAL
  27091. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  27092. #endif
  27093. };
  27094. /*
  27095. ** Bits of the Pager.doNotSpill flag. See further description below.
  27096. */
  27097. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  27098. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  27099. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  27100. /*
  27101. ** A open page cache is an instance of struct Pager. A description of
  27102. ** some of the more important member variables follows:
  27103. **
  27104. ** eState
  27105. **
  27106. ** The current 'state' of the pager object. See the comment and state
  27107. ** diagram above for a description of the pager state.
  27108. **
  27109. ** eLock
  27110. **
  27111. ** For a real on-disk database, the current lock held on the database file -
  27112. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  27113. **
  27114. ** For a temporary or in-memory database (neither of which require any
  27115. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  27116. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  27117. ** logic into thinking that it already has all the locks it will ever
  27118. ** need (and no reason to release them).
  27119. **
  27120. ** In some (obscure) circumstances, this variable may also be set to
  27121. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  27122. ** details.
  27123. **
  27124. ** changeCountDone
  27125. **
  27126. ** This boolean variable is used to make sure that the change-counter
  27127. ** (the 4-byte header field at byte offset 24 of the database file) is
  27128. ** not updated more often than necessary.
  27129. **
  27130. ** It is set to true when the change-counter field is updated, which
  27131. ** can only happen if an exclusive lock is held on the database file.
  27132. ** It is cleared (set to false) whenever an exclusive lock is
  27133. ** relinquished on the database file. Each time a transaction is committed,
  27134. ** The changeCountDone flag is inspected. If it is true, the work of
  27135. ** updating the change-counter is omitted for the current transaction.
  27136. **
  27137. ** This mechanism means that when running in exclusive mode, a connection
  27138. ** need only update the change-counter once, for the first transaction
  27139. ** committed.
  27140. **
  27141. ** setMaster
  27142. **
  27143. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  27144. ** (or may not) specify a master-journal name to be written into the
  27145. ** journal file before it is synced to disk.
  27146. **
  27147. ** Whether or not a journal file contains a master-journal pointer affects
  27148. ** the way in which the journal file is finalized after the transaction is
  27149. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  27150. ** If a journal file does not contain a master-journal pointer, it is
  27151. ** finalized by overwriting the first journal header with zeroes. If
  27152. ** it does contain a master-journal pointer the journal file is finalized
  27153. ** by truncating it to zero bytes, just as if the connection were
  27154. ** running in "journal_mode=truncate" mode.
  27155. **
  27156. ** Journal files that contain master journal pointers cannot be finalized
  27157. ** simply by overwriting the first journal-header with zeroes, as the
  27158. ** master journal pointer could interfere with hot-journal rollback of any
  27159. ** subsequently interrupted transaction that reuses the journal file.
  27160. **
  27161. ** The flag is cleared as soon as the journal file is finalized (either
  27162. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  27163. ** journal file from being successfully finalized, the setMaster flag
  27164. ** is cleared anyway (and the pager will move to ERROR state).
  27165. **
  27166. ** doNotSpill
  27167. **
  27168. ** This variables control the behavior of cache-spills (calls made by
  27169. ** the pcache module to the pagerStress() routine to write cached data
  27170. ** to the file-system in order to free up memory).
  27171. **
  27172. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  27173. ** writing to the database from pagerStress() is disabled altogether.
  27174. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  27175. ** comes up during savepoint rollback that requires the pcache module
  27176. ** to allocate a new page to prevent the journal file from being written
  27177. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  27178. ** case is a user preference.
  27179. **
  27180. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  27181. ** is permitted, but syncing the journal file is not. This flag is set
  27182. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  27183. ** the database page-size in order to prevent a journal sync from happening
  27184. ** in between the journalling of two pages on the same sector.
  27185. **
  27186. ** subjInMemory
  27187. **
  27188. ** This is a boolean variable. If true, then any required sub-journal
  27189. ** is opened as an in-memory journal file. If false, then in-memory
  27190. ** sub-journals are only used for in-memory pager files.
  27191. **
  27192. ** This variable is updated by the upper layer each time a new
  27193. ** write-transaction is opened.
  27194. **
  27195. ** dbSize, dbOrigSize, dbFileSize
  27196. **
  27197. ** Variable dbSize is set to the number of pages in the database file.
  27198. ** It is valid in PAGER_READER and higher states (all states except for
  27199. ** OPEN and ERROR).
  27200. **
  27201. ** dbSize is set based on the size of the database file, which may be
  27202. ** larger than the size of the database (the value stored at offset
  27203. ** 28 of the database header by the btree). If the size of the file
  27204. ** is not an integer multiple of the page-size, the value stored in
  27205. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  27206. ** Except, any file that is greater than 0 bytes in size is considered
  27207. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  27208. ** to dbSize==1).
  27209. **
  27210. ** During a write-transaction, if pages with page-numbers greater than
  27211. ** dbSize are modified in the cache, dbSize is updated accordingly.
  27212. ** Similarly, if the database is truncated using PagerTruncateImage(),
  27213. ** dbSize is updated.
  27214. **
  27215. ** Variables dbOrigSize and dbFileSize are valid in states
  27216. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  27217. ** variable at the start of the transaction. It is used during rollback,
  27218. ** and to determine whether or not pages need to be journalled before
  27219. ** being modified.
  27220. **
  27221. ** Throughout a write-transaction, dbFileSize contains the size of
  27222. ** the file on disk in pages. It is set to a copy of dbSize when the
  27223. ** write-transaction is first opened, and updated when VFS calls are made
  27224. ** to write or truncate the database file on disk.
  27225. **
  27226. ** The only reason the dbFileSize variable is required is to suppress
  27227. ** unnecessary calls to xTruncate() after committing a transaction. If,
  27228. ** when a transaction is committed, the dbFileSize variable indicates
  27229. ** that the database file is larger than the database image (Pager.dbSize),
  27230. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  27231. ** to measure the database file on disk, and then truncates it if required.
  27232. ** dbFileSize is not used when rolling back a transaction. In this case
  27233. ** pager_truncate() is called unconditionally (which means there may be
  27234. ** a call to xFilesize() that is not strictly required). In either case,
  27235. ** pager_truncate() may cause the file to become smaller or larger.
  27236. **
  27237. ** dbHintSize
  27238. **
  27239. ** The dbHintSize variable is used to limit the number of calls made to
  27240. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  27241. **
  27242. ** dbHintSize is set to a copy of the dbSize variable when a
  27243. ** write-transaction is opened (at the same time as dbFileSize and
  27244. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  27245. ** dbHintSize is increased to the number of pages that correspond to the
  27246. ** size-hint passed to the method call. See pager_write_pagelist() for
  27247. ** details.
  27248. **
  27249. ** errCode
  27250. **
  27251. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  27252. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  27253. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  27254. ** sub-codes.
  27255. */
  27256. struct Pager {
  27257. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  27258. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  27259. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  27260. u8 useJournal; /* Use a rollback journal on this file */
  27261. u8 noSync; /* Do not sync the journal if true */
  27262. u8 fullSync; /* Do extra syncs of the journal for robustness */
  27263. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  27264. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  27265. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  27266. u8 tempFile; /* zFilename is a temporary file */
  27267. u8 readOnly; /* True for a read-only database */
  27268. u8 memDb; /* True to inhibit all file I/O */
  27269. /**************************************************************************
  27270. ** The following block contains those class members that change during
  27271. ** routine opertion. Class members not in this block are either fixed
  27272. ** when the pager is first created or else only change when there is a
  27273. ** significant mode change (such as changing the page_size, locking_mode,
  27274. ** or the journal_mode). From another view, these class members describe
  27275. ** the "state" of the pager, while other class members describe the
  27276. ** "configuration" of the pager.
  27277. */
  27278. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  27279. u8 eLock; /* Current lock held on database file */
  27280. u8 changeCountDone; /* Set after incrementing the change-counter */
  27281. u8 setMaster; /* True if a m-j name has been written to jrnl */
  27282. u8 doNotSpill; /* Do not spill the cache when non-zero */
  27283. u8 subjInMemory; /* True to use in-memory sub-journals */
  27284. Pgno dbSize; /* Number of pages in the database */
  27285. Pgno dbOrigSize; /* dbSize before the current transaction */
  27286. Pgno dbFileSize; /* Number of pages in the database file */
  27287. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  27288. int errCode; /* One of several kinds of errors */
  27289. int nRec; /* Pages journalled since last j-header written */
  27290. u32 cksumInit; /* Quasi-random value added to every checksum */
  27291. u32 nSubRec; /* Number of records written to sub-journal */
  27292. Bitvec *pInJournal; /* One bit for each page in the database file */
  27293. sqlite3_file *fd; /* File descriptor for database */
  27294. sqlite3_file *jfd; /* File descriptor for main journal */
  27295. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  27296. i64 journalOff; /* Current write offset in the journal file */
  27297. i64 journalHdr; /* Byte offset to previous journal header */
  27298. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  27299. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  27300. int nSavepoint; /* Number of elements in aSavepoint[] */
  27301. char dbFileVers[16]; /* Changes whenever database file changes */
  27302. u8 bUseFetch; /* True to use xFetch() */
  27303. int nMmapOut; /* Number of mmap pages currently outstanding */
  27304. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  27305. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  27306. /*
  27307. ** End of the routinely-changing class members
  27308. ***************************************************************************/
  27309. u16 nExtra; /* Add this many bytes to each in-memory page */
  27310. i16 nReserve; /* Number of unused bytes at end of each page */
  27311. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  27312. u32 sectorSize; /* Assumed sector size during rollback */
  27313. int pageSize; /* Number of bytes in a page */
  27314. Pgno mxPgno; /* Maximum allowed size of the database */
  27315. i64 journalSizeLimit; /* Size limit for persistent journal files */
  27316. char *zFilename; /* Name of the database file */
  27317. char *zJournal; /* Name of the journal file */
  27318. int (*xBusyHandler)(void*); /* Function to call when busy */
  27319. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  27320. int aStat[3]; /* Total cache hits, misses and writes */
  27321. #ifdef SQLITE_TEST
  27322. int nRead; /* Database pages read */
  27323. #endif
  27324. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  27325. #ifdef SQLITE_HAS_CODEC
  27326. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  27327. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  27328. void (*xCodecFree)(void*); /* Destructor for the codec */
  27329. void *pCodec; /* First argument to xCodec... methods */
  27330. #endif
  27331. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  27332. PCache *pPCache; /* Pointer to page cache object */
  27333. #ifndef SQLITE_OMIT_WAL
  27334. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  27335. char *zWal; /* File name for write-ahead log */
  27336. #endif
  27337. };
  27338. /*
  27339. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  27340. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  27341. ** or CACHE_WRITE to sqlite3_db_status().
  27342. */
  27343. #define PAGER_STAT_HIT 0
  27344. #define PAGER_STAT_MISS 1
  27345. #define PAGER_STAT_WRITE 2
  27346. /*
  27347. ** The following global variables hold counters used for
  27348. ** testing purposes only. These variables do not exist in
  27349. ** a non-testing build. These variables are not thread-safe.
  27350. */
  27351. #ifdef SQLITE_TEST
  27352. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  27353. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  27354. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  27355. # define PAGER_INCR(v) v++
  27356. #else
  27357. # define PAGER_INCR(v)
  27358. #endif
  27359. /*
  27360. ** Journal files begin with the following magic string. The data
  27361. ** was obtained from /dev/random. It is used only as a sanity check.
  27362. **
  27363. ** Since version 2.8.0, the journal format contains additional sanity
  27364. ** checking information. If the power fails while the journal is being
  27365. ** written, semi-random garbage data might appear in the journal
  27366. ** file after power is restored. If an attempt is then made
  27367. ** to roll the journal back, the database could be corrupted. The additional
  27368. ** sanity checking data is an attempt to discover the garbage in the
  27369. ** journal and ignore it.
  27370. **
  27371. ** The sanity checking information for the new journal format consists
  27372. ** of a 32-bit checksum on each page of data. The checksum covers both
  27373. ** the page number and the pPager->pageSize bytes of data for the page.
  27374. ** This cksum is initialized to a 32-bit random value that appears in the
  27375. ** journal file right after the header. The random initializer is important,
  27376. ** because garbage data that appears at the end of a journal is likely
  27377. ** data that was once in other files that have now been deleted. If the
  27378. ** garbage data came from an obsolete journal file, the checksums might
  27379. ** be correct. But by initializing the checksum to random value which
  27380. ** is different for every journal, we minimize that risk.
  27381. */
  27382. static const unsigned char aJournalMagic[] = {
  27383. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  27384. };
  27385. /*
  27386. ** The size of the of each page record in the journal is given by
  27387. ** the following macro.
  27388. */
  27389. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  27390. /*
  27391. ** The journal header size for this pager. This is usually the same
  27392. ** size as a single disk sector. See also setSectorSize().
  27393. */
  27394. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  27395. /*
  27396. ** The macro MEMDB is true if we are dealing with an in-memory database.
  27397. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  27398. ** the value of MEMDB will be a constant and the compiler will optimize
  27399. ** out code that would never execute.
  27400. */
  27401. #ifdef SQLITE_OMIT_MEMORYDB
  27402. # define MEMDB 0
  27403. #else
  27404. # define MEMDB pPager->memDb
  27405. #endif
  27406. /*
  27407. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  27408. ** interfaces to access the database using memory-mapped I/O.
  27409. */
  27410. #if SQLITE_MAX_MMAP_SIZE>0
  27411. # define USEFETCH(x) ((x)->bUseFetch)
  27412. #else
  27413. # define USEFETCH(x) 0
  27414. #endif
  27415. /*
  27416. ** The maximum legal page number is (2^31 - 1).
  27417. */
  27418. #define PAGER_MAX_PGNO 2147483647
  27419. /*
  27420. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  27421. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  27422. **
  27423. ** This is so that expressions can be written as:
  27424. **
  27425. ** if( isOpen(pPager->jfd) ){ ...
  27426. **
  27427. ** instead of
  27428. **
  27429. ** if( pPager->jfd->pMethods ){ ...
  27430. */
  27431. #define isOpen(pFd) ((pFd)->pMethods)
  27432. /*
  27433. ** Return true if this pager uses a write-ahead log instead of the usual
  27434. ** rollback journal. Otherwise false.
  27435. */
  27436. #ifndef SQLITE_OMIT_WAL
  27437. static int pagerUseWal(Pager *pPager){
  27438. return (pPager->pWal!=0);
  27439. }
  27440. #else
  27441. # define pagerUseWal(x) 0
  27442. # define pagerRollbackWal(x) 0
  27443. # define pagerWalFrames(v,w,x,y) 0
  27444. # define pagerOpenWalIfPresent(z) SQLITE_OK
  27445. # define pagerBeginReadTransaction(z) SQLITE_OK
  27446. #endif
  27447. #ifndef NDEBUG
  27448. /*
  27449. ** Usage:
  27450. **
  27451. ** assert( assert_pager_state(pPager) );
  27452. **
  27453. ** This function runs many asserts to try to find inconsistencies in
  27454. ** the internal state of the Pager object.
  27455. */
  27456. static int assert_pager_state(Pager *p){
  27457. Pager *pPager = p;
  27458. /* State must be valid. */
  27459. assert( p->eState==PAGER_OPEN
  27460. || p->eState==PAGER_READER
  27461. || p->eState==PAGER_WRITER_LOCKED
  27462. || p->eState==PAGER_WRITER_CACHEMOD
  27463. || p->eState==PAGER_WRITER_DBMOD
  27464. || p->eState==PAGER_WRITER_FINISHED
  27465. || p->eState==PAGER_ERROR
  27466. );
  27467. /* Regardless of the current state, a temp-file connection always behaves
  27468. ** as if it has an exclusive lock on the database file. It never updates
  27469. ** the change-counter field, so the changeCountDone flag is always set.
  27470. */
  27471. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  27472. assert( p->tempFile==0 || pPager->changeCountDone );
  27473. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  27474. ** And if the journal-mode is "OFF", the journal file must not be open.
  27475. */
  27476. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  27477. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  27478. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  27479. ** this means an in-memory pager performs no IO at all, it cannot encounter
  27480. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  27481. ** a journal file. (although the in-memory journal implementation may
  27482. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  27483. ** is therefore not possible for an in-memory pager to enter the ERROR
  27484. ** state.
  27485. */
  27486. if( MEMDB ){
  27487. assert( p->noSync );
  27488. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  27489. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  27490. );
  27491. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  27492. assert( pagerUseWal(p)==0 );
  27493. }
  27494. /* If changeCountDone is set, a RESERVED lock or greater must be held
  27495. ** on the file.
  27496. */
  27497. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  27498. assert( p->eLock!=PENDING_LOCK );
  27499. switch( p->eState ){
  27500. case PAGER_OPEN:
  27501. assert( !MEMDB );
  27502. assert( pPager->errCode==SQLITE_OK );
  27503. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  27504. break;
  27505. case PAGER_READER:
  27506. assert( pPager->errCode==SQLITE_OK );
  27507. assert( p->eLock!=UNKNOWN_LOCK );
  27508. assert( p->eLock>=SHARED_LOCK );
  27509. break;
  27510. case PAGER_WRITER_LOCKED:
  27511. assert( p->eLock!=UNKNOWN_LOCK );
  27512. assert( pPager->errCode==SQLITE_OK );
  27513. if( !pagerUseWal(pPager) ){
  27514. assert( p->eLock>=RESERVED_LOCK );
  27515. }
  27516. assert( pPager->dbSize==pPager->dbOrigSize );
  27517. assert( pPager->dbOrigSize==pPager->dbFileSize );
  27518. assert( pPager->dbOrigSize==pPager->dbHintSize );
  27519. assert( pPager->setMaster==0 );
  27520. break;
  27521. case PAGER_WRITER_CACHEMOD:
  27522. assert( p->eLock!=UNKNOWN_LOCK );
  27523. assert( pPager->errCode==SQLITE_OK );
  27524. if( !pagerUseWal(pPager) ){
  27525. /* It is possible that if journal_mode=wal here that neither the
  27526. ** journal file nor the WAL file are open. This happens during
  27527. ** a rollback transaction that switches from journal_mode=off
  27528. ** to journal_mode=wal.
  27529. */
  27530. assert( p->eLock>=RESERVED_LOCK );
  27531. assert( isOpen(p->jfd)
  27532. || p->journalMode==PAGER_JOURNALMODE_OFF
  27533. || p->journalMode==PAGER_JOURNALMODE_WAL
  27534. );
  27535. }
  27536. assert( pPager->dbOrigSize==pPager->dbFileSize );
  27537. assert( pPager->dbOrigSize==pPager->dbHintSize );
  27538. break;
  27539. case PAGER_WRITER_DBMOD:
  27540. assert( p->eLock==EXCLUSIVE_LOCK );
  27541. assert( pPager->errCode==SQLITE_OK );
  27542. assert( !pagerUseWal(pPager) );
  27543. assert( p->eLock>=EXCLUSIVE_LOCK );
  27544. assert( isOpen(p->jfd)
  27545. || p->journalMode==PAGER_JOURNALMODE_OFF
  27546. || p->journalMode==PAGER_JOURNALMODE_WAL
  27547. );
  27548. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  27549. break;
  27550. case PAGER_WRITER_FINISHED:
  27551. assert( p->eLock==EXCLUSIVE_LOCK );
  27552. assert( pPager->errCode==SQLITE_OK );
  27553. assert( !pagerUseWal(pPager) );
  27554. assert( isOpen(p->jfd)
  27555. || p->journalMode==PAGER_JOURNALMODE_OFF
  27556. || p->journalMode==PAGER_JOURNALMODE_WAL
  27557. );
  27558. break;
  27559. case PAGER_ERROR:
  27560. /* There must be at least one outstanding reference to the pager if
  27561. ** in ERROR state. Otherwise the pager should have already dropped
  27562. ** back to OPEN state.
  27563. */
  27564. assert( pPager->errCode!=SQLITE_OK );
  27565. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  27566. break;
  27567. }
  27568. return 1;
  27569. }
  27570. #endif /* ifndef NDEBUG */
  27571. #ifdef SQLITE_DEBUG
  27572. /*
  27573. ** Return a pointer to a human readable string in a static buffer
  27574. ** containing the state of the Pager object passed as an argument. This
  27575. ** is intended to be used within debuggers. For example, as an alternative
  27576. ** to "print *pPager" in gdb:
  27577. **
  27578. ** (gdb) printf "%s", print_pager_state(pPager)
  27579. */
  27580. static char *print_pager_state(Pager *p){
  27581. static char zRet[1024];
  27582. sqlite3_snprintf(1024, zRet,
  27583. "Filename: %s\n"
  27584. "State: %s errCode=%d\n"
  27585. "Lock: %s\n"
  27586. "Locking mode: locking_mode=%s\n"
  27587. "Journal mode: journal_mode=%s\n"
  27588. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  27589. "Journal: journalOff=%lld journalHdr=%lld\n"
  27590. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  27591. , p->zFilename
  27592. , p->eState==PAGER_OPEN ? "OPEN" :
  27593. p->eState==PAGER_READER ? "READER" :
  27594. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  27595. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  27596. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  27597. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  27598. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  27599. , (int)p->errCode
  27600. , p->eLock==NO_LOCK ? "NO_LOCK" :
  27601. p->eLock==RESERVED_LOCK ? "RESERVED" :
  27602. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  27603. p->eLock==SHARED_LOCK ? "SHARED" :
  27604. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  27605. , p->exclusiveMode ? "exclusive" : "normal"
  27606. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  27607. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  27608. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  27609. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  27610. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  27611. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  27612. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  27613. , p->journalOff, p->journalHdr
  27614. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  27615. );
  27616. return zRet;
  27617. }
  27618. #endif
  27619. /*
  27620. ** Return true if it is necessary to write page *pPg into the sub-journal.
  27621. ** A page needs to be written into the sub-journal if there exists one
  27622. ** or more open savepoints for which:
  27623. **
  27624. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  27625. ** * The bit corresponding to the page-number is not set in
  27626. ** PagerSavepoint.pInSavepoint.
  27627. */
  27628. static int subjRequiresPage(PgHdr *pPg){
  27629. Pager *pPager = pPg->pPager;
  27630. PagerSavepoint *p;
  27631. Pgno pgno;
  27632. int i;
  27633. if( pPager->nSavepoint ){
  27634. pgno = pPg->pgno;
  27635. for(i=0; i<pPager->nSavepoint; i++){
  27636. p = &pPager->aSavepoint[i];
  27637. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  27638. return 1;
  27639. }
  27640. }
  27641. }
  27642. return 0;
  27643. }
  27644. /*
  27645. ** Return true if the page is already in the journal file.
  27646. */
  27647. static int pageInJournal(PgHdr *pPg){
  27648. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  27649. }
  27650. /*
  27651. ** Read a 32-bit integer from the given file descriptor. Store the integer
  27652. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  27653. ** error code is something goes wrong.
  27654. **
  27655. ** All values are stored on disk as big-endian.
  27656. */
  27657. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  27658. unsigned char ac[4];
  27659. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  27660. if( rc==SQLITE_OK ){
  27661. *pRes = sqlite3Get4byte(ac);
  27662. }
  27663. return rc;
  27664. }
  27665. /*
  27666. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  27667. */
  27668. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  27669. /*
  27670. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  27671. ** on success or an error code is something goes wrong.
  27672. */
  27673. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  27674. char ac[4];
  27675. put32bits(ac, val);
  27676. return sqlite3OsWrite(fd, ac, 4, offset);
  27677. }
  27678. /*
  27679. ** Unlock the database file to level eLock, which must be either NO_LOCK
  27680. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  27681. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  27682. **
  27683. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  27684. ** called, do not modify it. See the comment above the #define of
  27685. ** UNKNOWN_LOCK for an explanation of this.
  27686. */
  27687. static int pagerUnlockDb(Pager *pPager, int eLock){
  27688. int rc = SQLITE_OK;
  27689. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  27690. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  27691. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  27692. if( isOpen(pPager->fd) ){
  27693. assert( pPager->eLock>=eLock );
  27694. rc = sqlite3OsUnlock(pPager->fd, eLock);
  27695. if( pPager->eLock!=UNKNOWN_LOCK ){
  27696. pPager->eLock = (u8)eLock;
  27697. }
  27698. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  27699. }
  27700. return rc;
  27701. }
  27702. /*
  27703. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  27704. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  27705. ** Pager.eLock variable to the new locking state.
  27706. **
  27707. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  27708. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  27709. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  27710. ** of this.
  27711. */
  27712. static int pagerLockDb(Pager *pPager, int eLock){
  27713. int rc = SQLITE_OK;
  27714. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  27715. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  27716. rc = sqlite3OsLock(pPager->fd, eLock);
  27717. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  27718. pPager->eLock = (u8)eLock;
  27719. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  27720. }
  27721. }
  27722. return rc;
  27723. }
  27724. /*
  27725. ** This function determines whether or not the atomic-write optimization
  27726. ** can be used with this pager. The optimization can be used if:
  27727. **
  27728. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  27729. ** a database page may be written atomically, and
  27730. ** (b) the value returned by OsSectorSize() is less than or equal
  27731. ** to the page size.
  27732. **
  27733. ** The optimization is also always enabled for temporary files. It is
  27734. ** an error to call this function if pPager is opened on an in-memory
  27735. ** database.
  27736. **
  27737. ** If the optimization cannot be used, 0 is returned. If it can be used,
  27738. ** then the value returned is the size of the journal file when it
  27739. ** contains rollback data for exactly one page.
  27740. */
  27741. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  27742. static int jrnlBufferSize(Pager *pPager){
  27743. assert( !MEMDB );
  27744. if( !pPager->tempFile ){
  27745. int dc; /* Device characteristics */
  27746. int nSector; /* Sector size */
  27747. int szPage; /* Page size */
  27748. assert( isOpen(pPager->fd) );
  27749. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  27750. nSector = pPager->sectorSize;
  27751. szPage = pPager->pageSize;
  27752. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  27753. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  27754. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  27755. return 0;
  27756. }
  27757. }
  27758. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  27759. }
  27760. #endif
  27761. /*
  27762. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  27763. ** on the cache using a hash function. This is used for testing
  27764. ** and debugging only.
  27765. */
  27766. #ifdef SQLITE_CHECK_PAGES
  27767. /*
  27768. ** Return a 32-bit hash of the page data for pPage.
  27769. */
  27770. static u32 pager_datahash(int nByte, unsigned char *pData){
  27771. u32 hash = 0;
  27772. int i;
  27773. for(i=0; i<nByte; i++){
  27774. hash = (hash*1039) + pData[i];
  27775. }
  27776. return hash;
  27777. }
  27778. static u32 pager_pagehash(PgHdr *pPage){
  27779. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  27780. }
  27781. static void pager_set_pagehash(PgHdr *pPage){
  27782. pPage->pageHash = pager_pagehash(pPage);
  27783. }
  27784. /*
  27785. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  27786. ** is defined, and NDEBUG is not defined, an assert() statement checks
  27787. ** that the page is either dirty or still matches the calculated page-hash.
  27788. */
  27789. #define CHECK_PAGE(x) checkPage(x)
  27790. static void checkPage(PgHdr *pPg){
  27791. Pager *pPager = pPg->pPager;
  27792. assert( pPager->eState!=PAGER_ERROR );
  27793. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  27794. }
  27795. #else
  27796. #define pager_datahash(X,Y) 0
  27797. #define pager_pagehash(X) 0
  27798. #define pager_set_pagehash(X)
  27799. #define CHECK_PAGE(x)
  27800. #endif /* SQLITE_CHECK_PAGES */
  27801. /*
  27802. ** When this is called the journal file for pager pPager must be open.
  27803. ** This function attempts to read a master journal file name from the
  27804. ** end of the file and, if successful, copies it into memory supplied
  27805. ** by the caller. See comments above writeMasterJournal() for the format
  27806. ** used to store a master journal file name at the end of a journal file.
  27807. **
  27808. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  27809. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  27810. ** enough space to write the master journal name). If the master journal
  27811. ** name in the journal is longer than nMaster bytes (including a
  27812. ** nul-terminator), then this is handled as if no master journal name
  27813. ** were present in the journal.
  27814. **
  27815. ** If a master journal file name is present at the end of the journal
  27816. ** file, then it is copied into the buffer pointed to by zMaster. A
  27817. ** nul-terminator byte is appended to the buffer following the master
  27818. ** journal file name.
  27819. **
  27820. ** If it is determined that no master journal file name is present
  27821. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  27822. **
  27823. ** If an error occurs while reading from the journal file, an SQLite
  27824. ** error code is returned.
  27825. */
  27826. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  27827. int rc; /* Return code */
  27828. u32 len; /* Length in bytes of master journal name */
  27829. i64 szJ; /* Total size in bytes of journal file pJrnl */
  27830. u32 cksum; /* MJ checksum value read from journal */
  27831. u32 u; /* Unsigned loop counter */
  27832. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  27833. zMaster[0] = '\0';
  27834. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  27835. || szJ<16
  27836. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  27837. || len>=nMaster
  27838. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  27839. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  27840. || memcmp(aMagic, aJournalMagic, 8)
  27841. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  27842. ){
  27843. return rc;
  27844. }
  27845. /* See if the checksum matches the master journal name */
  27846. for(u=0; u<len; u++){
  27847. cksum -= zMaster[u];
  27848. }
  27849. if( cksum ){
  27850. /* If the checksum doesn't add up, then one or more of the disk sectors
  27851. ** containing the master journal filename is corrupted. This means
  27852. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  27853. ** master-journal filename.
  27854. */
  27855. len = 0;
  27856. }
  27857. zMaster[len] = '\0';
  27858. return SQLITE_OK;
  27859. }
  27860. /*
  27861. ** Return the offset of the sector boundary at or immediately
  27862. ** following the value in pPager->journalOff, assuming a sector
  27863. ** size of pPager->sectorSize bytes.
  27864. **
  27865. ** i.e for a sector size of 512:
  27866. **
  27867. ** Pager.journalOff Return value
  27868. ** ---------------------------------------
  27869. ** 0 0
  27870. ** 512 512
  27871. ** 100 512
  27872. ** 2000 2048
  27873. **
  27874. */
  27875. static i64 journalHdrOffset(Pager *pPager){
  27876. i64 offset = 0;
  27877. i64 c = pPager->journalOff;
  27878. if( c ){
  27879. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  27880. }
  27881. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  27882. assert( offset>=c );
  27883. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  27884. return offset;
  27885. }
  27886. /*
  27887. ** The journal file must be open when this function is called.
  27888. **
  27889. ** This function is a no-op if the journal file has not been written to
  27890. ** within the current transaction (i.e. if Pager.journalOff==0).
  27891. **
  27892. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  27893. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  27894. ** zero the 28-byte header at the start of the journal file. In either case,
  27895. ** if the pager is not in no-sync mode, sync the journal file immediately
  27896. ** after writing or truncating it.
  27897. **
  27898. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  27899. ** following the truncation or zeroing described above the size of the
  27900. ** journal file in bytes is larger than this value, then truncate the
  27901. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  27902. ** not need to be synced following this operation.
  27903. **
  27904. ** If an IO error occurs, abandon processing and return the IO error code.
  27905. ** Otherwise, return SQLITE_OK.
  27906. */
  27907. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  27908. int rc = SQLITE_OK; /* Return code */
  27909. assert( isOpen(pPager->jfd) );
  27910. if( pPager->journalOff ){
  27911. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  27912. IOTRACE(("JZEROHDR %p\n", pPager))
  27913. if( doTruncate || iLimit==0 ){
  27914. rc = sqlite3OsTruncate(pPager->jfd, 0);
  27915. }else{
  27916. static const char zeroHdr[28] = {0};
  27917. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  27918. }
  27919. if( rc==SQLITE_OK && !pPager->noSync ){
  27920. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  27921. }
  27922. /* At this point the transaction is committed but the write lock
  27923. ** is still held on the file. If there is a size limit configured for
  27924. ** the persistent journal and the journal file currently consumes more
  27925. ** space than that limit allows for, truncate it now. There is no need
  27926. ** to sync the file following this operation.
  27927. */
  27928. if( rc==SQLITE_OK && iLimit>0 ){
  27929. i64 sz;
  27930. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  27931. if( rc==SQLITE_OK && sz>iLimit ){
  27932. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  27933. }
  27934. }
  27935. }
  27936. return rc;
  27937. }
  27938. /*
  27939. ** The journal file must be open when this routine is called. A journal
  27940. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  27941. ** current location.
  27942. **
  27943. ** The format for the journal header is as follows:
  27944. ** - 8 bytes: Magic identifying journal format.
  27945. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  27946. ** - 4 bytes: Random number used for page hash.
  27947. ** - 4 bytes: Initial database page count.
  27948. ** - 4 bytes: Sector size used by the process that wrote this journal.
  27949. ** - 4 bytes: Database page size.
  27950. **
  27951. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  27952. */
  27953. static int writeJournalHdr(Pager *pPager){
  27954. int rc = SQLITE_OK; /* Return code */
  27955. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  27956. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  27957. u32 nWrite; /* Bytes of header sector written */
  27958. int ii; /* Loop counter */
  27959. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  27960. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  27961. nHeader = JOURNAL_HDR_SZ(pPager);
  27962. }
  27963. /* If there are active savepoints and any of them were created
  27964. ** since the most recent journal header was written, update the
  27965. ** PagerSavepoint.iHdrOffset fields now.
  27966. */
  27967. for(ii=0; ii<pPager->nSavepoint; ii++){
  27968. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  27969. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  27970. }
  27971. }
  27972. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  27973. /*
  27974. ** Write the nRec Field - the number of page records that follow this
  27975. ** journal header. Normally, zero is written to this value at this time.
  27976. ** After the records are added to the journal (and the journal synced,
  27977. ** if in full-sync mode), the zero is overwritten with the true number
  27978. ** of records (see syncJournal()).
  27979. **
  27980. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  27981. ** reading the journal this value tells SQLite to assume that the
  27982. ** rest of the journal file contains valid page records. This assumption
  27983. ** is dangerous, as if a failure occurred whilst writing to the journal
  27984. ** file it may contain some garbage data. There are two scenarios
  27985. ** where this risk can be ignored:
  27986. **
  27987. ** * When the pager is in no-sync mode. Corruption can follow a
  27988. ** power failure in this case anyway.
  27989. **
  27990. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  27991. ** that garbage data is never appended to the journal file.
  27992. */
  27993. assert( isOpen(pPager->fd) || pPager->noSync );
  27994. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  27995. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  27996. ){
  27997. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  27998. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  27999. }else{
  28000. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  28001. }
  28002. /* The random check-hash initializer */
  28003. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  28004. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  28005. /* The initial database size */
  28006. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  28007. /* The assumed sector size for this process */
  28008. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  28009. /* The page size */
  28010. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  28011. /* Initializing the tail of the buffer is not necessary. Everything
  28012. ** works find if the following memset() is omitted. But initializing
  28013. ** the memory prevents valgrind from complaining, so we are willing to
  28014. ** take the performance hit.
  28015. */
  28016. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  28017. nHeader-(sizeof(aJournalMagic)+20));
  28018. /* In theory, it is only necessary to write the 28 bytes that the
  28019. ** journal header consumes to the journal file here. Then increment the
  28020. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  28021. ** record is written to the following sector (leaving a gap in the file
  28022. ** that will be implicitly filled in by the OS).
  28023. **
  28024. ** However it has been discovered that on some systems this pattern can
  28025. ** be significantly slower than contiguously writing data to the file,
  28026. ** even if that means explicitly writing data to the block of
  28027. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  28028. ** is done.
  28029. **
  28030. ** The loop is required here in case the sector-size is larger than the
  28031. ** database page size. Since the zHeader buffer is only Pager.pageSize
  28032. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  28033. ** to populate the entire journal header sector.
  28034. */
  28035. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  28036. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  28037. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  28038. assert( pPager->journalHdr <= pPager->journalOff );
  28039. pPager->journalOff += nHeader;
  28040. }
  28041. return rc;
  28042. }
  28043. /*
  28044. ** The journal file must be open when this is called. A journal header file
  28045. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  28046. ** file. The current location in the journal file is given by
  28047. ** pPager->journalOff. See comments above function writeJournalHdr() for
  28048. ** a description of the journal header format.
  28049. **
  28050. ** If the header is read successfully, *pNRec is set to the number of
  28051. ** page records following this header and *pDbSize is set to the size of the
  28052. ** database before the transaction began, in pages. Also, pPager->cksumInit
  28053. ** is set to the value read from the journal header. SQLITE_OK is returned
  28054. ** in this case.
  28055. **
  28056. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  28057. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  28058. ** cannot be read from the journal file an error code is returned.
  28059. */
  28060. static int readJournalHdr(
  28061. Pager *pPager, /* Pager object */
  28062. int isHot,
  28063. i64 journalSize, /* Size of the open journal file in bytes */
  28064. u32 *pNRec, /* OUT: Value read from the nRec field */
  28065. u32 *pDbSize /* OUT: Value of original database size field */
  28066. ){
  28067. int rc; /* Return code */
  28068. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  28069. i64 iHdrOff; /* Offset of journal header being read */
  28070. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  28071. /* Advance Pager.journalOff to the start of the next sector. If the
  28072. ** journal file is too small for there to be a header stored at this
  28073. ** point, return SQLITE_DONE.
  28074. */
  28075. pPager->journalOff = journalHdrOffset(pPager);
  28076. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  28077. return SQLITE_DONE;
  28078. }
  28079. iHdrOff = pPager->journalOff;
  28080. /* Read in the first 8 bytes of the journal header. If they do not match
  28081. ** the magic string found at the start of each journal header, return
  28082. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  28083. ** proceed.
  28084. */
  28085. if( isHot || iHdrOff!=pPager->journalHdr ){
  28086. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  28087. if( rc ){
  28088. return rc;
  28089. }
  28090. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  28091. return SQLITE_DONE;
  28092. }
  28093. }
  28094. /* Read the first three 32-bit fields of the journal header: The nRec
  28095. ** field, the checksum-initializer and the database size at the start
  28096. ** of the transaction. Return an error code if anything goes wrong.
  28097. */
  28098. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  28099. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  28100. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  28101. ){
  28102. return rc;
  28103. }
  28104. if( pPager->journalOff==0 ){
  28105. u32 iPageSize; /* Page-size field of journal header */
  28106. u32 iSectorSize; /* Sector-size field of journal header */
  28107. /* Read the page-size and sector-size journal header fields. */
  28108. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  28109. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  28110. ){
  28111. return rc;
  28112. }
  28113. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  28114. ** journal header to zero. In this case, assume that the Pager.pageSize
  28115. ** variable is already set to the correct page size.
  28116. */
  28117. if( iPageSize==0 ){
  28118. iPageSize = pPager->pageSize;
  28119. }
  28120. /* Check that the values read from the page-size and sector-size fields
  28121. ** are within range. To be 'in range', both values need to be a power
  28122. ** of two greater than or equal to 512 or 32, and not greater than their
  28123. ** respective compile time maximum limits.
  28124. */
  28125. if( iPageSize<512 || iSectorSize<32
  28126. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  28127. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  28128. ){
  28129. /* If the either the page-size or sector-size in the journal-header is
  28130. ** invalid, then the process that wrote the journal-header must have
  28131. ** crashed before the header was synced. In this case stop reading
  28132. ** the journal file here.
  28133. */
  28134. return SQLITE_DONE;
  28135. }
  28136. /* Update the page-size to match the value read from the journal.
  28137. ** Use a testcase() macro to make sure that malloc failure within
  28138. ** PagerSetPagesize() is tested.
  28139. */
  28140. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  28141. testcase( rc!=SQLITE_OK );
  28142. /* Update the assumed sector-size to match the value used by
  28143. ** the process that created this journal. If this journal was
  28144. ** created by a process other than this one, then this routine
  28145. ** is being called from within pager_playback(). The local value
  28146. ** of Pager.sectorSize is restored at the end of that routine.
  28147. */
  28148. pPager->sectorSize = iSectorSize;
  28149. }
  28150. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  28151. return rc;
  28152. }
  28153. /*
  28154. ** Write the supplied master journal name into the journal file for pager
  28155. ** pPager at the current location. The master journal name must be the last
  28156. ** thing written to a journal file. If the pager is in full-sync mode, the
  28157. ** journal file descriptor is advanced to the next sector boundary before
  28158. ** anything is written. The format is:
  28159. **
  28160. ** + 4 bytes: PAGER_MJ_PGNO.
  28161. ** + N bytes: Master journal filename in utf-8.
  28162. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  28163. ** + 4 bytes: Master journal name checksum.
  28164. ** + 8 bytes: aJournalMagic[].
  28165. **
  28166. ** The master journal page checksum is the sum of the bytes in the master
  28167. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  28168. **
  28169. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  28170. ** this call is a no-op.
  28171. */
  28172. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  28173. int rc; /* Return code */
  28174. int nMaster; /* Length of string zMaster */
  28175. i64 iHdrOff; /* Offset of header in journal file */
  28176. i64 jrnlSize; /* Size of journal file on disk */
  28177. u32 cksum = 0; /* Checksum of string zMaster */
  28178. assert( pPager->setMaster==0 );
  28179. assert( !pagerUseWal(pPager) );
  28180. if( !zMaster
  28181. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  28182. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  28183. ){
  28184. return SQLITE_OK;
  28185. }
  28186. pPager->setMaster = 1;
  28187. assert( isOpen(pPager->jfd) );
  28188. assert( pPager->journalHdr <= pPager->journalOff );
  28189. /* Calculate the length in bytes and the checksum of zMaster */
  28190. for(nMaster=0; zMaster[nMaster]; nMaster++){
  28191. cksum += zMaster[nMaster];
  28192. }
  28193. /* If in full-sync mode, advance to the next disk sector before writing
  28194. ** the master journal name. This is in case the previous page written to
  28195. ** the journal has already been synced.
  28196. */
  28197. if( pPager->fullSync ){
  28198. pPager->journalOff = journalHdrOffset(pPager);
  28199. }
  28200. iHdrOff = pPager->journalOff;
  28201. /* Write the master journal data to the end of the journal file. If
  28202. ** an error occurs, return the error code to the caller.
  28203. */
  28204. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  28205. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  28206. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  28207. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  28208. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  28209. ){
  28210. return rc;
  28211. }
  28212. pPager->journalOff += (nMaster+20);
  28213. /* If the pager is in peristent-journal mode, then the physical
  28214. ** journal-file may extend past the end of the master-journal name
  28215. ** and 8 bytes of magic data just written to the file. This is
  28216. ** dangerous because the code to rollback a hot-journal file
  28217. ** will not be able to find the master-journal name to determine
  28218. ** whether or not the journal is hot.
  28219. **
  28220. ** Easiest thing to do in this scenario is to truncate the journal
  28221. ** file to the required size.
  28222. */
  28223. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  28224. && jrnlSize>pPager->journalOff
  28225. ){
  28226. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  28227. }
  28228. return rc;
  28229. }
  28230. /*
  28231. ** Find a page in the hash table given its page number. Return
  28232. ** a pointer to the page or NULL if the requested page is not
  28233. ** already in memory.
  28234. */
  28235. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  28236. PgHdr *p; /* Return value */
  28237. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  28238. ** fail, since no attempt to allocate dynamic memory will be made.
  28239. */
  28240. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  28241. return p;
  28242. }
  28243. /*
  28244. ** Discard the entire contents of the in-memory page-cache.
  28245. */
  28246. static void pager_reset(Pager *pPager){
  28247. sqlite3BackupRestart(pPager->pBackup);
  28248. sqlite3PcacheClear(pPager->pPCache);
  28249. }
  28250. /*
  28251. ** Free all structures in the Pager.aSavepoint[] array and set both
  28252. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  28253. ** if it is open and the pager is not in exclusive mode.
  28254. */
  28255. static void releaseAllSavepoints(Pager *pPager){
  28256. int ii; /* Iterator for looping through Pager.aSavepoint */
  28257. for(ii=0; ii<pPager->nSavepoint; ii++){
  28258. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  28259. }
  28260. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  28261. sqlite3OsClose(pPager->sjfd);
  28262. }
  28263. sqlite3_free(pPager->aSavepoint);
  28264. pPager->aSavepoint = 0;
  28265. pPager->nSavepoint = 0;
  28266. pPager->nSubRec = 0;
  28267. }
  28268. /*
  28269. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  28270. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  28271. ** or SQLITE_NOMEM if a malloc failure occurs.
  28272. */
  28273. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  28274. int ii; /* Loop counter */
  28275. int rc = SQLITE_OK; /* Result code */
  28276. for(ii=0; ii<pPager->nSavepoint; ii++){
  28277. PagerSavepoint *p = &pPager->aSavepoint[ii];
  28278. if( pgno<=p->nOrig ){
  28279. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  28280. testcase( rc==SQLITE_NOMEM );
  28281. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  28282. }
  28283. }
  28284. return rc;
  28285. }
  28286. /*
  28287. ** This function is a no-op if the pager is in exclusive mode and not
  28288. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  28289. ** state.
  28290. **
  28291. ** If the pager is not in exclusive-access mode, the database file is
  28292. ** completely unlocked. If the file is unlocked and the file-system does
  28293. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  28294. ** closed (if it is open).
  28295. **
  28296. ** If the pager is in ERROR state when this function is called, the
  28297. ** contents of the pager cache are discarded before switching back to
  28298. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  28299. ** or not, any journal file left in the file-system will be treated
  28300. ** as a hot-journal and rolled back the next time a read-transaction
  28301. ** is opened (by this or by any other connection).
  28302. */
  28303. static void pager_unlock(Pager *pPager){
  28304. assert( pPager->eState==PAGER_READER
  28305. || pPager->eState==PAGER_OPEN
  28306. || pPager->eState==PAGER_ERROR
  28307. );
  28308. sqlite3BitvecDestroy(pPager->pInJournal);
  28309. pPager->pInJournal = 0;
  28310. releaseAllSavepoints(pPager);
  28311. if( pagerUseWal(pPager) ){
  28312. assert( !isOpen(pPager->jfd) );
  28313. sqlite3WalEndReadTransaction(pPager->pWal);
  28314. pPager->eState = PAGER_OPEN;
  28315. }else if( !pPager->exclusiveMode ){
  28316. int rc; /* Error code returned by pagerUnlockDb() */
  28317. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  28318. /* If the operating system support deletion of open files, then
  28319. ** close the journal file when dropping the database lock. Otherwise
  28320. ** another connection with journal_mode=delete might delete the file
  28321. ** out from under us.
  28322. */
  28323. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  28324. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  28325. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  28326. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  28327. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  28328. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  28329. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  28330. || 1!=(pPager->journalMode & 5)
  28331. ){
  28332. sqlite3OsClose(pPager->jfd);
  28333. }
  28334. /* If the pager is in the ERROR state and the call to unlock the database
  28335. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  28336. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  28337. ** is necessary.
  28338. */
  28339. rc = pagerUnlockDb(pPager, NO_LOCK);
  28340. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  28341. pPager->eLock = UNKNOWN_LOCK;
  28342. }
  28343. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  28344. ** without clearing the error code. This is intentional - the error
  28345. ** code is cleared and the cache reset in the block below.
  28346. */
  28347. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  28348. pPager->changeCountDone = 0;
  28349. pPager->eState = PAGER_OPEN;
  28350. }
  28351. /* If Pager.errCode is set, the contents of the pager cache cannot be
  28352. ** trusted. Now that there are no outstanding references to the pager,
  28353. ** it can safely move back to PAGER_OPEN state. This happens in both
  28354. ** normal and exclusive-locking mode.
  28355. */
  28356. if( pPager->errCode ){
  28357. assert( !MEMDB );
  28358. pager_reset(pPager);
  28359. pPager->changeCountDone = pPager->tempFile;
  28360. pPager->eState = PAGER_OPEN;
  28361. pPager->errCode = SQLITE_OK;
  28362. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  28363. }
  28364. pPager->journalOff = 0;
  28365. pPager->journalHdr = 0;
  28366. pPager->setMaster = 0;
  28367. }
  28368. /*
  28369. ** This function is called whenever an IOERR or FULL error that requires
  28370. ** the pager to transition into the ERROR state may ahve occurred.
  28371. ** The first argument is a pointer to the pager structure, the second
  28372. ** the error-code about to be returned by a pager API function. The
  28373. ** value returned is a copy of the second argument to this function.
  28374. **
  28375. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  28376. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  28377. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  28378. ** all major API calls on the Pager will immediately return Pager.errCode.
  28379. **
  28380. ** The ERROR state indicates that the contents of the pager-cache
  28381. ** cannot be trusted. This state can be cleared by completely discarding
  28382. ** the contents of the pager-cache. If a transaction was active when
  28383. ** the persistent error occurred, then the rollback journal may need
  28384. ** to be replayed to restore the contents of the database file (as if
  28385. ** it were a hot-journal).
  28386. */
  28387. static int pager_error(Pager *pPager, int rc){
  28388. int rc2 = rc & 0xff;
  28389. assert( rc==SQLITE_OK || !MEMDB );
  28390. assert(
  28391. pPager->errCode==SQLITE_FULL ||
  28392. pPager->errCode==SQLITE_OK ||
  28393. (pPager->errCode & 0xff)==SQLITE_IOERR
  28394. );
  28395. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  28396. pPager->errCode = rc;
  28397. pPager->eState = PAGER_ERROR;
  28398. }
  28399. return rc;
  28400. }
  28401. static int pager_truncate(Pager *pPager, Pgno nPage);
  28402. /*
  28403. ** This routine ends a transaction. A transaction is usually ended by
  28404. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  28405. ** after rollback of a hot-journal, or if an error occurs while opening
  28406. ** the journal file or writing the very first journal-header of a
  28407. ** database transaction.
  28408. **
  28409. ** This routine is never called in PAGER_ERROR state. If it is called
  28410. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  28411. ** exclusive than a RESERVED lock, it is a no-op.
  28412. **
  28413. ** Otherwise, any active savepoints are released.
  28414. **
  28415. ** If the journal file is open, then it is "finalized". Once a journal
  28416. ** file has been finalized it is not possible to use it to roll back a
  28417. ** transaction. Nor will it be considered to be a hot-journal by this
  28418. ** or any other database connection. Exactly how a journal is finalized
  28419. ** depends on whether or not the pager is running in exclusive mode and
  28420. ** the current journal-mode (Pager.journalMode value), as follows:
  28421. **
  28422. ** journalMode==MEMORY
  28423. ** Journal file descriptor is simply closed. This destroys an
  28424. ** in-memory journal.
  28425. **
  28426. ** journalMode==TRUNCATE
  28427. ** Journal file is truncated to zero bytes in size.
  28428. **
  28429. ** journalMode==PERSIST
  28430. ** The first 28 bytes of the journal file are zeroed. This invalidates
  28431. ** the first journal header in the file, and hence the entire journal
  28432. ** file. An invalid journal file cannot be rolled back.
  28433. **
  28434. ** journalMode==DELETE
  28435. ** The journal file is closed and deleted using sqlite3OsDelete().
  28436. **
  28437. ** If the pager is running in exclusive mode, this method of finalizing
  28438. ** the journal file is never used. Instead, if the journalMode is
  28439. ** DELETE and the pager is in exclusive mode, the method described under
  28440. ** journalMode==PERSIST is used instead.
  28441. **
  28442. ** After the journal is finalized, the pager moves to PAGER_READER state.
  28443. ** If running in non-exclusive rollback mode, the lock on the file is
  28444. ** downgraded to a SHARED_LOCK.
  28445. **
  28446. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  28447. ** any of the IO operations to finalize the journal file or unlock the
  28448. ** database then the IO error code is returned to the user. If the
  28449. ** operation to finalize the journal file fails, then the code still
  28450. ** tries to unlock the database file if not in exclusive mode. If the
  28451. ** unlock operation fails as well, then the first error code related
  28452. ** to the first error encountered (the journal finalization one) is
  28453. ** returned.
  28454. */
  28455. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  28456. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  28457. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  28458. /* Do nothing if the pager does not have an open write transaction
  28459. ** or at least a RESERVED lock. This function may be called when there
  28460. ** is no write-transaction active but a RESERVED or greater lock is
  28461. ** held under two circumstances:
  28462. **
  28463. ** 1. After a successful hot-journal rollback, it is called with
  28464. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  28465. **
  28466. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  28467. ** lock switches back to locking_mode=normal and then executes a
  28468. ** read-transaction, this function is called with eState==PAGER_READER
  28469. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  28470. */
  28471. assert( assert_pager_state(pPager) );
  28472. assert( pPager->eState!=PAGER_ERROR );
  28473. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  28474. return SQLITE_OK;
  28475. }
  28476. releaseAllSavepoints(pPager);
  28477. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  28478. if( isOpen(pPager->jfd) ){
  28479. assert( !pagerUseWal(pPager) );
  28480. /* Finalize the journal file. */
  28481. if( sqlite3IsMemJournal(pPager->jfd) ){
  28482. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  28483. sqlite3OsClose(pPager->jfd);
  28484. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  28485. if( pPager->journalOff==0 ){
  28486. rc = SQLITE_OK;
  28487. }else{
  28488. rc = sqlite3OsTruncate(pPager->jfd, 0);
  28489. }
  28490. pPager->journalOff = 0;
  28491. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  28492. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  28493. ){
  28494. rc = zeroJournalHdr(pPager, hasMaster);
  28495. pPager->journalOff = 0;
  28496. }else{
  28497. /* This branch may be executed with Pager.journalMode==MEMORY if
  28498. ** a hot-journal was just rolled back. In this case the journal
  28499. ** file should be closed and deleted. If this connection writes to
  28500. ** the database file, it will do so using an in-memory journal.
  28501. */
  28502. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  28503. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  28504. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  28505. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  28506. );
  28507. sqlite3OsClose(pPager->jfd);
  28508. if( bDelete ){
  28509. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  28510. }
  28511. }
  28512. }
  28513. #ifdef SQLITE_CHECK_PAGES
  28514. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  28515. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  28516. PgHdr *p = pager_lookup(pPager, 1);
  28517. if( p ){
  28518. p->pageHash = 0;
  28519. sqlite3PagerUnref(p);
  28520. }
  28521. }
  28522. #endif
  28523. sqlite3BitvecDestroy(pPager->pInJournal);
  28524. pPager->pInJournal = 0;
  28525. pPager->nRec = 0;
  28526. sqlite3PcacheCleanAll(pPager->pPCache);
  28527. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  28528. if( pagerUseWal(pPager) ){
  28529. /* Drop the WAL write-lock, if any. Also, if the connection was in
  28530. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  28531. ** lock held on the database file.
  28532. */
  28533. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  28534. assert( rc2==SQLITE_OK );
  28535. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  28536. /* This branch is taken when committing a transaction in rollback-journal
  28537. ** mode if the database file on disk is larger than the database image.
  28538. ** At this point the journal has been finalized and the transaction
  28539. ** successfully committed, but the EXCLUSIVE lock is still held on the
  28540. ** file. So it is safe to truncate the database file to its minimum
  28541. ** required size. */
  28542. assert( pPager->eLock==EXCLUSIVE_LOCK );
  28543. rc = pager_truncate(pPager, pPager->dbSize);
  28544. }
  28545. if( !pPager->exclusiveMode
  28546. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  28547. ){
  28548. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  28549. pPager->changeCountDone = 0;
  28550. }
  28551. pPager->eState = PAGER_READER;
  28552. pPager->setMaster = 0;
  28553. return (rc==SQLITE_OK?rc2:rc);
  28554. }
  28555. /*
  28556. ** Execute a rollback if a transaction is active and unlock the
  28557. ** database file.
  28558. **
  28559. ** If the pager has already entered the ERROR state, do not attempt
  28560. ** the rollback at this time. Instead, pager_unlock() is called. The
  28561. ** call to pager_unlock() will discard all in-memory pages, unlock
  28562. ** the database file and move the pager back to OPEN state. If this
  28563. ** means that there is a hot-journal left in the file-system, the next
  28564. ** connection to obtain a shared lock on the pager (which may be this one)
  28565. ** will roll it back.
  28566. **
  28567. ** If the pager has not already entered the ERROR state, but an IO or
  28568. ** malloc error occurs during a rollback, then this will itself cause
  28569. ** the pager to enter the ERROR state. Which will be cleared by the
  28570. ** call to pager_unlock(), as described above.
  28571. */
  28572. static void pagerUnlockAndRollback(Pager *pPager){
  28573. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  28574. assert( assert_pager_state(pPager) );
  28575. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  28576. sqlite3BeginBenignMalloc();
  28577. sqlite3PagerRollback(pPager);
  28578. sqlite3EndBenignMalloc();
  28579. }else if( !pPager->exclusiveMode ){
  28580. assert( pPager->eState==PAGER_READER );
  28581. pager_end_transaction(pPager, 0, 0);
  28582. }
  28583. }
  28584. pager_unlock(pPager);
  28585. }
  28586. /*
  28587. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  28588. ** of data. Compute and return a checksum based ont the contents of the
  28589. ** page of data and the current value of pPager->cksumInit.
  28590. **
  28591. ** This is not a real checksum. It is really just the sum of the
  28592. ** random initial value (pPager->cksumInit) and every 200th byte
  28593. ** of the page data, starting with byte offset (pPager->pageSize%200).
  28594. ** Each byte is interpreted as an 8-bit unsigned integer.
  28595. **
  28596. ** Changing the formula used to compute this checksum results in an
  28597. ** incompatible journal file format.
  28598. **
  28599. ** If journal corruption occurs due to a power failure, the most likely
  28600. ** scenario is that one end or the other of the record will be changed.
  28601. ** It is much less likely that the two ends of the journal record will be
  28602. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  28603. ** though fast and simple, catches the mostly likely kind of corruption.
  28604. */
  28605. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  28606. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  28607. int i = pPager->pageSize-200; /* Loop counter */
  28608. while( i>0 ){
  28609. cksum += aData[i];
  28610. i -= 200;
  28611. }
  28612. return cksum;
  28613. }
  28614. /*
  28615. ** Report the current page size and number of reserved bytes back
  28616. ** to the codec.
  28617. */
  28618. #ifdef SQLITE_HAS_CODEC
  28619. static void pagerReportSize(Pager *pPager){
  28620. if( pPager->xCodecSizeChng ){
  28621. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  28622. (int)pPager->nReserve);
  28623. }
  28624. }
  28625. #else
  28626. # define pagerReportSize(X) /* No-op if we do not support a codec */
  28627. #endif
  28628. /*
  28629. ** Read a single page from either the journal file (if isMainJrnl==1) or
  28630. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  28631. ** The page begins at offset *pOffset into the file. The *pOffset
  28632. ** value is increased to the start of the next page in the journal.
  28633. **
  28634. ** The main rollback journal uses checksums - the statement journal does
  28635. ** not.
  28636. **
  28637. ** If the page number of the page record read from the (sub-)journal file
  28638. ** is greater than the current value of Pager.dbSize, then playback is
  28639. ** skipped and SQLITE_OK is returned.
  28640. **
  28641. ** If pDone is not NULL, then it is a record of pages that have already
  28642. ** been played back. If the page at *pOffset has already been played back
  28643. ** (if the corresponding pDone bit is set) then skip the playback.
  28644. ** Make sure the pDone bit corresponding to the *pOffset page is set
  28645. ** prior to returning.
  28646. **
  28647. ** If the page record is successfully read from the (sub-)journal file
  28648. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  28649. ** while reading the record from the (sub-)journal file or while writing
  28650. ** to the database file, then the IO error code is returned. If data
  28651. ** is successfully read from the (sub-)journal file but appears to be
  28652. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  28653. ** two circumstances:
  28654. **
  28655. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  28656. ** * If the record is being rolled back from the main journal file
  28657. ** and the checksum field does not match the record content.
  28658. **
  28659. ** Neither of these two scenarios are possible during a savepoint rollback.
  28660. **
  28661. ** If this is a savepoint rollback, then memory may have to be dynamically
  28662. ** allocated by this function. If this is the case and an allocation fails,
  28663. ** SQLITE_NOMEM is returned.
  28664. */
  28665. static int pager_playback_one_page(
  28666. Pager *pPager, /* The pager being played back */
  28667. i64 *pOffset, /* Offset of record to playback */
  28668. Bitvec *pDone, /* Bitvec of pages already played back */
  28669. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  28670. int isSavepnt /* True for a savepoint rollback */
  28671. ){
  28672. int rc;
  28673. PgHdr *pPg; /* An existing page in the cache */
  28674. Pgno pgno; /* The page number of a page in journal */
  28675. u32 cksum; /* Checksum used for sanity checking */
  28676. char *aData; /* Temporary storage for the page */
  28677. sqlite3_file *jfd; /* The file descriptor for the journal file */
  28678. int isSynced; /* True if journal page is synced */
  28679. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  28680. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  28681. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  28682. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  28683. aData = pPager->pTmpSpace;
  28684. assert( aData ); /* Temp storage must have already been allocated */
  28685. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  28686. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  28687. ** or savepoint rollback done at the request of the caller) or this is
  28688. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  28689. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  28690. ** only reads from the main journal, not the sub-journal.
  28691. */
  28692. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  28693. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  28694. );
  28695. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  28696. /* Read the page number and page data from the journal or sub-journal
  28697. ** file. Return an error code to the caller if an IO error occurs.
  28698. */
  28699. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  28700. rc = read32bits(jfd, *pOffset, &pgno);
  28701. if( rc!=SQLITE_OK ) return rc;
  28702. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  28703. if( rc!=SQLITE_OK ) return rc;
  28704. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  28705. /* Sanity checking on the page. This is more important that I originally
  28706. ** thought. If a power failure occurs while the journal is being written,
  28707. ** it could cause invalid data to be written into the journal. We need to
  28708. ** detect this invalid data (with high probability) and ignore it.
  28709. */
  28710. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  28711. assert( !isSavepnt );
  28712. return SQLITE_DONE;
  28713. }
  28714. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  28715. return SQLITE_OK;
  28716. }
  28717. if( isMainJrnl ){
  28718. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  28719. if( rc ) return rc;
  28720. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  28721. return SQLITE_DONE;
  28722. }
  28723. }
  28724. /* If this page has already been played by before during the current
  28725. ** rollback, then don't bother to play it back again.
  28726. */
  28727. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  28728. return rc;
  28729. }
  28730. /* When playing back page 1, restore the nReserve setting
  28731. */
  28732. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  28733. pPager->nReserve = ((u8*)aData)[20];
  28734. pagerReportSize(pPager);
  28735. }
  28736. /* If the pager is in CACHEMOD state, then there must be a copy of this
  28737. ** page in the pager cache. In this case just update the pager cache,
  28738. ** not the database file. The page is left marked dirty in this case.
  28739. **
  28740. ** An exception to the above rule: If the database is in no-sync mode
  28741. ** and a page is moved during an incremental vacuum then the page may
  28742. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  28743. ** during a Movepage() call, then the page may not be in the cache
  28744. ** either. So the condition described in the above paragraph is not
  28745. ** assert()able.
  28746. **
  28747. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  28748. ** pager cache if it exists and the main file. The page is then marked
  28749. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  28750. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  28751. ** if the pager is in OPEN state.
  28752. **
  28753. ** Ticket #1171: The statement journal might contain page content that is
  28754. ** different from the page content at the start of the transaction.
  28755. ** This occurs when a page is changed prior to the start of a statement
  28756. ** then changed again within the statement. When rolling back such a
  28757. ** statement we must not write to the original database unless we know
  28758. ** for certain that original page contents are synced into the main rollback
  28759. ** journal. Otherwise, a power loss might leave modified data in the
  28760. ** database file without an entry in the rollback journal that can
  28761. ** restore the database to its original form. Two conditions must be
  28762. ** met before writing to the database files. (1) the database must be
  28763. ** locked. (2) we know that the original page content is fully synced
  28764. ** in the main journal either because the page is not in cache or else
  28765. ** the page is marked as needSync==0.
  28766. **
  28767. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  28768. ** is possible to fail a statement on a database that does not yet exist.
  28769. ** Do not attempt to write if database file has never been opened.
  28770. */
  28771. if( pagerUseWal(pPager) ){
  28772. pPg = 0;
  28773. }else{
  28774. pPg = pager_lookup(pPager, pgno);
  28775. }
  28776. assert( pPg || !MEMDB );
  28777. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  28778. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  28779. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  28780. (isMainJrnl?"main-journal":"sub-journal")
  28781. ));
  28782. if( isMainJrnl ){
  28783. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  28784. }else{
  28785. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  28786. }
  28787. if( isOpen(pPager->fd)
  28788. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  28789. && isSynced
  28790. ){
  28791. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  28792. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  28793. assert( !pagerUseWal(pPager) );
  28794. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  28795. if( pgno>pPager->dbFileSize ){
  28796. pPager->dbFileSize = pgno;
  28797. }
  28798. if( pPager->pBackup ){
  28799. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  28800. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  28801. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  28802. }
  28803. }else if( !isMainJrnl && pPg==0 ){
  28804. /* If this is a rollback of a savepoint and data was not written to
  28805. ** the database and the page is not in-memory, there is a potential
  28806. ** problem. When the page is next fetched by the b-tree layer, it
  28807. ** will be read from the database file, which may or may not be
  28808. ** current.
  28809. **
  28810. ** There are a couple of different ways this can happen. All are quite
  28811. ** obscure. When running in synchronous mode, this can only happen
  28812. ** if the page is on the free-list at the start of the transaction, then
  28813. ** populated, then moved using sqlite3PagerMovepage().
  28814. **
  28815. ** The solution is to add an in-memory page to the cache containing
  28816. ** the data just read from the sub-journal. Mark the page as dirty
  28817. ** and if the pager requires a journal-sync, then mark the page as
  28818. ** requiring a journal-sync before it is written.
  28819. */
  28820. assert( isSavepnt );
  28821. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  28822. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  28823. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  28824. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  28825. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  28826. if( rc!=SQLITE_OK ) return rc;
  28827. pPg->flags &= ~PGHDR_NEED_READ;
  28828. sqlite3PcacheMakeDirty(pPg);
  28829. }
  28830. if( pPg ){
  28831. /* No page should ever be explicitly rolled back that is in use, except
  28832. ** for page 1 which is held in use in order to keep the lock on the
  28833. ** database active. However such a page may be rolled back as a result
  28834. ** of an internal error resulting in an automatic call to
  28835. ** sqlite3PagerRollback().
  28836. */
  28837. void *pData;
  28838. pData = pPg->pData;
  28839. memcpy(pData, (u8*)aData, pPager->pageSize);
  28840. pPager->xReiniter(pPg);
  28841. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  28842. /* If the contents of this page were just restored from the main
  28843. ** journal file, then its content must be as they were when the
  28844. ** transaction was first opened. In this case we can mark the page
  28845. ** as clean, since there will be no need to write it out to the
  28846. ** database.
  28847. **
  28848. ** There is one exception to this rule. If the page is being rolled
  28849. ** back as part of a savepoint (or statement) rollback from an
  28850. ** unsynced portion of the main journal file, then it is not safe
  28851. ** to mark the page as clean. This is because marking the page as
  28852. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  28853. ** already in the journal file (recorded in Pager.pInJournal) and
  28854. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  28855. ** again within this transaction, it will be marked as dirty but
  28856. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  28857. ** be written out into the database file before its journal file
  28858. ** segment is synced. If a crash occurs during or following this,
  28859. ** database corruption may ensue.
  28860. */
  28861. assert( !pagerUseWal(pPager) );
  28862. sqlite3PcacheMakeClean(pPg);
  28863. }
  28864. pager_set_pagehash(pPg);
  28865. /* If this was page 1, then restore the value of Pager.dbFileVers.
  28866. ** Do this before any decoding. */
  28867. if( pgno==1 ){
  28868. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  28869. }
  28870. /* Decode the page just read from disk */
  28871. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  28872. sqlite3PcacheRelease(pPg);
  28873. }
  28874. return rc;
  28875. }
  28876. /*
  28877. ** Parameter zMaster is the name of a master journal file. A single journal
  28878. ** file that referred to the master journal file has just been rolled back.
  28879. ** This routine checks if it is possible to delete the master journal file,
  28880. ** and does so if it is.
  28881. **
  28882. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  28883. ** available for use within this function.
  28884. **
  28885. ** When a master journal file is created, it is populated with the names
  28886. ** of all of its child journals, one after another, formatted as utf-8
  28887. ** encoded text. The end of each child journal file is marked with a
  28888. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  28889. ** file for a transaction involving two databases might be:
  28890. **
  28891. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  28892. **
  28893. ** A master journal file may only be deleted once all of its child
  28894. ** journals have been rolled back.
  28895. **
  28896. ** This function reads the contents of the master-journal file into
  28897. ** memory and loops through each of the child journal names. For
  28898. ** each child journal, it checks if:
  28899. **
  28900. ** * if the child journal exists, and if so
  28901. ** * if the child journal contains a reference to master journal
  28902. ** file zMaster
  28903. **
  28904. ** If a child journal can be found that matches both of the criteria
  28905. ** above, this function returns without doing anything. Otherwise, if
  28906. ** no such child journal can be found, file zMaster is deleted from
  28907. ** the file-system using sqlite3OsDelete().
  28908. **
  28909. ** If an IO error within this function, an error code is returned. This
  28910. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  28911. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  28912. ** occur, SQLITE_OK is returned.
  28913. **
  28914. ** TODO: This function allocates a single block of memory to load
  28915. ** the entire contents of the master journal file. This could be
  28916. ** a couple of kilobytes or so - potentially larger than the page
  28917. ** size.
  28918. */
  28919. static int pager_delmaster(Pager *pPager, const char *zMaster){
  28920. sqlite3_vfs *pVfs = pPager->pVfs;
  28921. int rc; /* Return code */
  28922. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  28923. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  28924. char *zMasterJournal = 0; /* Contents of master journal file */
  28925. i64 nMasterJournal; /* Size of master journal file */
  28926. char *zJournal; /* Pointer to one journal within MJ file */
  28927. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  28928. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  28929. /* Allocate space for both the pJournal and pMaster file descriptors.
  28930. ** If successful, open the master journal file for reading.
  28931. */
  28932. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  28933. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  28934. if( !pMaster ){
  28935. rc = SQLITE_NOMEM;
  28936. }else{
  28937. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  28938. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  28939. }
  28940. if( rc!=SQLITE_OK ) goto delmaster_out;
  28941. /* Load the entire master journal file into space obtained from
  28942. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  28943. ** sufficient space (in zMasterPtr) to hold the names of master
  28944. ** journal files extracted from regular rollback-journals.
  28945. */
  28946. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  28947. if( rc!=SQLITE_OK ) goto delmaster_out;
  28948. nMasterPtr = pVfs->mxPathname+1;
  28949. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  28950. if( !zMasterJournal ){
  28951. rc = SQLITE_NOMEM;
  28952. goto delmaster_out;
  28953. }
  28954. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  28955. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  28956. if( rc!=SQLITE_OK ) goto delmaster_out;
  28957. zMasterJournal[nMasterJournal] = 0;
  28958. zJournal = zMasterJournal;
  28959. while( (zJournal-zMasterJournal)<nMasterJournal ){
  28960. int exists;
  28961. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  28962. if( rc!=SQLITE_OK ){
  28963. goto delmaster_out;
  28964. }
  28965. if( exists ){
  28966. /* One of the journals pointed to by the master journal exists.
  28967. ** Open it and check if it points at the master journal. If
  28968. ** so, return without deleting the master journal file.
  28969. */
  28970. int c;
  28971. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  28972. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  28973. if( rc!=SQLITE_OK ){
  28974. goto delmaster_out;
  28975. }
  28976. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  28977. sqlite3OsClose(pJournal);
  28978. if( rc!=SQLITE_OK ){
  28979. goto delmaster_out;
  28980. }
  28981. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  28982. if( c ){
  28983. /* We have a match. Do not delete the master journal file. */
  28984. goto delmaster_out;
  28985. }
  28986. }
  28987. zJournal += (sqlite3Strlen30(zJournal)+1);
  28988. }
  28989. sqlite3OsClose(pMaster);
  28990. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  28991. delmaster_out:
  28992. sqlite3_free(zMasterJournal);
  28993. if( pMaster ){
  28994. sqlite3OsClose(pMaster);
  28995. assert( !isOpen(pJournal) );
  28996. sqlite3_free(pMaster);
  28997. }
  28998. return rc;
  28999. }
  29000. /*
  29001. ** This function is used to change the actual size of the database
  29002. ** file in the file-system. This only happens when committing a transaction,
  29003. ** or rolling back a transaction (including rolling back a hot-journal).
  29004. **
  29005. ** If the main database file is not open, or the pager is not in either
  29006. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  29007. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  29008. ** If the file on disk is currently larger than nPage pages, then use the VFS
  29009. ** xTruncate() method to truncate it.
  29010. **
  29011. ** Or, it might might be the case that the file on disk is smaller than
  29012. ** nPage pages. Some operating system implementations can get confused if
  29013. ** you try to truncate a file to some size that is larger than it
  29014. ** currently is, so detect this case and write a single zero byte to
  29015. ** the end of the new file instead.
  29016. **
  29017. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  29018. ** the database file, return the error code to the caller.
  29019. */
  29020. static int pager_truncate(Pager *pPager, Pgno nPage){
  29021. int rc = SQLITE_OK;
  29022. assert( pPager->eState!=PAGER_ERROR );
  29023. assert( pPager->eState!=PAGER_READER );
  29024. if( isOpen(pPager->fd)
  29025. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  29026. ){
  29027. i64 currentSize, newSize;
  29028. int szPage = pPager->pageSize;
  29029. assert( pPager->eLock==EXCLUSIVE_LOCK );
  29030. /* TODO: Is it safe to use Pager.dbFileSize here? */
  29031. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  29032. newSize = szPage*(i64)nPage;
  29033. if( rc==SQLITE_OK && currentSize!=newSize ){
  29034. if( currentSize>newSize ){
  29035. rc = sqlite3OsTruncate(pPager->fd, newSize);
  29036. }else if( (currentSize+szPage)<=newSize ){
  29037. char *pTmp = pPager->pTmpSpace;
  29038. memset(pTmp, 0, szPage);
  29039. testcase( (newSize-szPage) == currentSize );
  29040. testcase( (newSize-szPage) > currentSize );
  29041. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  29042. }
  29043. if( rc==SQLITE_OK ){
  29044. pPager->dbFileSize = nPage;
  29045. }
  29046. }
  29047. }
  29048. return rc;
  29049. }
  29050. /*
  29051. ** Return a sanitized version of the sector-size of OS file pFile. The
  29052. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  29053. */
  29054. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  29055. int iRet = sqlite3OsSectorSize(pFile);
  29056. if( iRet<32 ){
  29057. iRet = 512;
  29058. }else if( iRet>MAX_SECTOR_SIZE ){
  29059. assert( MAX_SECTOR_SIZE>=512 );
  29060. iRet = MAX_SECTOR_SIZE;
  29061. }
  29062. return iRet;
  29063. }
  29064. /*
  29065. ** Set the value of the Pager.sectorSize variable for the given
  29066. ** pager based on the value returned by the xSectorSize method
  29067. ** of the open database file. The sector size will be used used
  29068. ** to determine the size and alignment of journal header and
  29069. ** master journal pointers within created journal files.
  29070. **
  29071. ** For temporary files the effective sector size is always 512 bytes.
  29072. **
  29073. ** Otherwise, for non-temporary files, the effective sector size is
  29074. ** the value returned by the xSectorSize() method rounded up to 32 if
  29075. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  29076. ** is greater than MAX_SECTOR_SIZE.
  29077. **
  29078. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  29079. ** the effective sector size to its minimum value (512). The purpose of
  29080. ** pPager->sectorSize is to define the "blast radius" of bytes that
  29081. ** might change if a crash occurs while writing to a single byte in
  29082. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  29083. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  29084. ** size. For backwards compatibility of the rollback journal file format,
  29085. ** we cannot reduce the effective sector size below 512.
  29086. */
  29087. static void setSectorSize(Pager *pPager){
  29088. assert( isOpen(pPager->fd) || pPager->tempFile );
  29089. if( pPager->tempFile
  29090. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  29091. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  29092. ){
  29093. /* Sector size doesn't matter for temporary files. Also, the file
  29094. ** may not have been opened yet, in which case the OsSectorSize()
  29095. ** call will segfault. */
  29096. pPager->sectorSize = 512;
  29097. }else{
  29098. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  29099. }
  29100. }
  29101. /*
  29102. ** Playback the journal and thus restore the database file to
  29103. ** the state it was in before we started making changes.
  29104. **
  29105. ** The journal file format is as follows:
  29106. **
  29107. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  29108. ** (2) 4 byte big-endian integer which is the number of valid page records
  29109. ** in the journal. If this value is 0xffffffff, then compute the
  29110. ** number of page records from the journal size.
  29111. ** (3) 4 byte big-endian integer which is the initial value for the
  29112. ** sanity checksum.
  29113. ** (4) 4 byte integer which is the number of pages to truncate the
  29114. ** database to during a rollback.
  29115. ** (5) 4 byte big-endian integer which is the sector size. The header
  29116. ** is this many bytes in size.
  29117. ** (6) 4 byte big-endian integer which is the page size.
  29118. ** (7) zero padding out to the next sector size.
  29119. ** (8) Zero or more pages instances, each as follows:
  29120. ** + 4 byte page number.
  29121. ** + pPager->pageSize bytes of data.
  29122. ** + 4 byte checksum
  29123. **
  29124. ** When we speak of the journal header, we mean the first 7 items above.
  29125. ** Each entry in the journal is an instance of the 8th item.
  29126. **
  29127. ** Call the value from the second bullet "nRec". nRec is the number of
  29128. ** valid page entries in the journal. In most cases, you can compute the
  29129. ** value of nRec from the size of the journal file. But if a power
  29130. ** failure occurred while the journal was being written, it could be the
  29131. ** case that the size of the journal file had already been increased but
  29132. ** the extra entries had not yet made it safely to disk. In such a case,
  29133. ** the value of nRec computed from the file size would be too large. For
  29134. ** that reason, we always use the nRec value in the header.
  29135. **
  29136. ** If the nRec value is 0xffffffff it means that nRec should be computed
  29137. ** from the file size. This value is used when the user selects the
  29138. ** no-sync option for the journal. A power failure could lead to corruption
  29139. ** in this case. But for things like temporary table (which will be
  29140. ** deleted when the power is restored) we don't care.
  29141. **
  29142. ** If the file opened as the journal file is not a well-formed
  29143. ** journal file then all pages up to the first corrupted page are rolled
  29144. ** back (or no pages if the journal header is corrupted). The journal file
  29145. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  29146. ** been encountered.
  29147. **
  29148. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  29149. ** and an error code is returned.
  29150. **
  29151. ** The isHot parameter indicates that we are trying to rollback a journal
  29152. ** that might be a hot journal. Or, it could be that the journal is
  29153. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  29154. ** If the journal really is hot, reset the pager cache prior rolling
  29155. ** back any content. If the journal is merely persistent, no reset is
  29156. ** needed.
  29157. */
  29158. static int pager_playback(Pager *pPager, int isHot){
  29159. sqlite3_vfs *pVfs = pPager->pVfs;
  29160. i64 szJ; /* Size of the journal file in bytes */
  29161. u32 nRec; /* Number of Records in the journal */
  29162. u32 u; /* Unsigned loop counter */
  29163. Pgno mxPg = 0; /* Size of the original file in pages */
  29164. int rc; /* Result code of a subroutine */
  29165. int res = 1; /* Value returned by sqlite3OsAccess() */
  29166. char *zMaster = 0; /* Name of master journal file if any */
  29167. int needPagerReset; /* True to reset page prior to first page rollback */
  29168. int nPlayback = 0; /* Total number of pages restored from journal */
  29169. /* Figure out how many records are in the journal. Abort early if
  29170. ** the journal is empty.
  29171. */
  29172. assert( isOpen(pPager->jfd) );
  29173. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  29174. if( rc!=SQLITE_OK ){
  29175. goto end_playback;
  29176. }
  29177. /* Read the master journal name from the journal, if it is present.
  29178. ** If a master journal file name is specified, but the file is not
  29179. ** present on disk, then the journal is not hot and does not need to be
  29180. ** played back.
  29181. **
  29182. ** TODO: Technically the following is an error because it assumes that
  29183. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  29184. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  29185. ** mxPathname is 512, which is the same as the minimum allowable value
  29186. ** for pageSize.
  29187. */
  29188. zMaster = pPager->pTmpSpace;
  29189. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  29190. if( rc==SQLITE_OK && zMaster[0] ){
  29191. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  29192. }
  29193. zMaster = 0;
  29194. if( rc!=SQLITE_OK || !res ){
  29195. goto end_playback;
  29196. }
  29197. pPager->journalOff = 0;
  29198. needPagerReset = isHot;
  29199. /* This loop terminates either when a readJournalHdr() or
  29200. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  29201. ** occurs.
  29202. */
  29203. while( 1 ){
  29204. /* Read the next journal header from the journal file. If there are
  29205. ** not enough bytes left in the journal file for a complete header, or
  29206. ** it is corrupted, then a process must have failed while writing it.
  29207. ** This indicates nothing more needs to be rolled back.
  29208. */
  29209. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  29210. if( rc!=SQLITE_OK ){
  29211. if( rc==SQLITE_DONE ){
  29212. rc = SQLITE_OK;
  29213. }
  29214. goto end_playback;
  29215. }
  29216. /* If nRec is 0xffffffff, then this journal was created by a process
  29217. ** working in no-sync mode. This means that the rest of the journal
  29218. ** file consists of pages, there are no more journal headers. Compute
  29219. ** the value of nRec based on this assumption.
  29220. */
  29221. if( nRec==0xffffffff ){
  29222. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  29223. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  29224. }
  29225. /* If nRec is 0 and this rollback is of a transaction created by this
  29226. ** process and if this is the final header in the journal, then it means
  29227. ** that this part of the journal was being filled but has not yet been
  29228. ** synced to disk. Compute the number of pages based on the remaining
  29229. ** size of the file.
  29230. **
  29231. ** The third term of the test was added to fix ticket #2565.
  29232. ** When rolling back a hot journal, nRec==0 always means that the next
  29233. ** chunk of the journal contains zero pages to be rolled back. But
  29234. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  29235. ** the journal, it means that the journal might contain additional
  29236. ** pages that need to be rolled back and that the number of pages
  29237. ** should be computed based on the journal file size.
  29238. */
  29239. if( nRec==0 && !isHot &&
  29240. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  29241. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  29242. }
  29243. /* If this is the first header read from the journal, truncate the
  29244. ** database file back to its original size.
  29245. */
  29246. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  29247. rc = pager_truncate(pPager, mxPg);
  29248. if( rc!=SQLITE_OK ){
  29249. goto end_playback;
  29250. }
  29251. pPager->dbSize = mxPg;
  29252. }
  29253. /* Copy original pages out of the journal and back into the
  29254. ** database file and/or page cache.
  29255. */
  29256. for(u=0; u<nRec; u++){
  29257. if( needPagerReset ){
  29258. pager_reset(pPager);
  29259. needPagerReset = 0;
  29260. }
  29261. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  29262. if( rc==SQLITE_OK ){
  29263. nPlayback++;
  29264. }else{
  29265. if( rc==SQLITE_DONE ){
  29266. pPager->journalOff = szJ;
  29267. break;
  29268. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  29269. /* If the journal has been truncated, simply stop reading and
  29270. ** processing the journal. This might happen if the journal was
  29271. ** not completely written and synced prior to a crash. In that
  29272. ** case, the database should have never been written in the
  29273. ** first place so it is OK to simply abandon the rollback. */
  29274. rc = SQLITE_OK;
  29275. goto end_playback;
  29276. }else{
  29277. /* If we are unable to rollback, quit and return the error
  29278. ** code. This will cause the pager to enter the error state
  29279. ** so that no further harm will be done. Perhaps the next
  29280. ** process to come along will be able to rollback the database.
  29281. */
  29282. goto end_playback;
  29283. }
  29284. }
  29285. }
  29286. }
  29287. /*NOTREACHED*/
  29288. assert( 0 );
  29289. end_playback:
  29290. /* Following a rollback, the database file should be back in its original
  29291. ** state prior to the start of the transaction, so invoke the
  29292. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  29293. ** assertion that the transaction counter was modified.
  29294. */
  29295. #ifdef SQLITE_DEBUG
  29296. if( pPager->fd->pMethods ){
  29297. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  29298. }
  29299. #endif
  29300. /* If this playback is happening automatically as a result of an IO or
  29301. ** malloc error that occurred after the change-counter was updated but
  29302. ** before the transaction was committed, then the change-counter
  29303. ** modification may just have been reverted. If this happens in exclusive
  29304. ** mode, then subsequent transactions performed by the connection will not
  29305. ** update the change-counter at all. This may lead to cache inconsistency
  29306. ** problems for other processes at some point in the future. So, just
  29307. ** in case this has happened, clear the changeCountDone flag now.
  29308. */
  29309. pPager->changeCountDone = pPager->tempFile;
  29310. if( rc==SQLITE_OK ){
  29311. zMaster = pPager->pTmpSpace;
  29312. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  29313. testcase( rc!=SQLITE_OK );
  29314. }
  29315. if( rc==SQLITE_OK
  29316. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  29317. ){
  29318. rc = sqlite3PagerSync(pPager);
  29319. }
  29320. if( rc==SQLITE_OK ){
  29321. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  29322. testcase( rc!=SQLITE_OK );
  29323. }
  29324. if( rc==SQLITE_OK && zMaster[0] && res ){
  29325. /* If there was a master journal and this routine will return success,
  29326. ** see if it is possible to delete the master journal.
  29327. */
  29328. rc = pager_delmaster(pPager, zMaster);
  29329. testcase( rc!=SQLITE_OK );
  29330. }
  29331. if( isHot && nPlayback ){
  29332. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  29333. nPlayback, pPager->zJournal);
  29334. }
  29335. /* The Pager.sectorSize variable may have been updated while rolling
  29336. ** back a journal created by a process with a different sector size
  29337. ** value. Reset it to the correct value for this process.
  29338. */
  29339. setSectorSize(pPager);
  29340. return rc;
  29341. }
  29342. /*
  29343. ** Read the content for page pPg out of the database file and into
  29344. ** pPg->pData. A shared lock or greater must be held on the database
  29345. ** file before this function is called.
  29346. **
  29347. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  29348. ** the value read from the database file.
  29349. **
  29350. ** If an IO error occurs, then the IO error is returned to the caller.
  29351. ** Otherwise, SQLITE_OK is returned.
  29352. */
  29353. static int readDbPage(PgHdr *pPg, u32 iFrame){
  29354. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  29355. Pgno pgno = pPg->pgno; /* Page number to read */
  29356. int rc = SQLITE_OK; /* Return code */
  29357. int pgsz = pPager->pageSize; /* Number of bytes to read */
  29358. assert( pPager->eState>=PAGER_READER && !MEMDB );
  29359. assert( isOpen(pPager->fd) );
  29360. #ifndef SQLITE_OMIT_WAL
  29361. if( iFrame ){
  29362. /* Try to pull the page from the write-ahead log. */
  29363. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  29364. }else
  29365. #endif
  29366. {
  29367. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  29368. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  29369. if( rc==SQLITE_IOERR_SHORT_READ ){
  29370. rc = SQLITE_OK;
  29371. }
  29372. }
  29373. if( pgno==1 ){
  29374. if( rc ){
  29375. /* If the read is unsuccessful, set the dbFileVers[] to something
  29376. ** that will never be a valid file version. dbFileVers[] is a copy
  29377. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  29378. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  29379. ** should be page numbers which are never 0xffffffff. So filling
  29380. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  29381. **
  29382. ** For an encrypted database, the situation is more complex: bytes
  29383. ** 24..39 of the database are white noise. But the probability of
  29384. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  29385. ** we should still be ok.
  29386. */
  29387. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  29388. }else{
  29389. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  29390. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  29391. }
  29392. }
  29393. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  29394. PAGER_INCR(sqlite3_pager_readdb_count);
  29395. PAGER_INCR(pPager->nRead);
  29396. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  29397. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  29398. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  29399. return rc;
  29400. }
  29401. /*
  29402. ** Update the value of the change-counter at offsets 24 and 92 in
  29403. ** the header and the sqlite version number at offset 96.
  29404. **
  29405. ** This is an unconditional update. See also the pager_incr_changecounter()
  29406. ** routine which only updates the change-counter if the update is actually
  29407. ** needed, as determined by the pPager->changeCountDone state variable.
  29408. */
  29409. static void pager_write_changecounter(PgHdr *pPg){
  29410. u32 change_counter;
  29411. /* Increment the value just read and write it back to byte 24. */
  29412. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  29413. put32bits(((char*)pPg->pData)+24, change_counter);
  29414. /* Also store the SQLite version number in bytes 96..99 and in
  29415. ** bytes 92..95 store the change counter for which the version number
  29416. ** is valid. */
  29417. put32bits(((char*)pPg->pData)+92, change_counter);
  29418. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  29419. }
  29420. #ifndef SQLITE_OMIT_WAL
  29421. /*
  29422. ** This function is invoked once for each page that has already been
  29423. ** written into the log file when a WAL transaction is rolled back.
  29424. ** Parameter iPg is the page number of said page. The pCtx argument
  29425. ** is actually a pointer to the Pager structure.
  29426. **
  29427. ** If page iPg is present in the cache, and has no outstanding references,
  29428. ** it is discarded. Otherwise, if there are one or more outstanding
  29429. ** references, the page content is reloaded from the database. If the
  29430. ** attempt to reload content from the database is required and fails,
  29431. ** return an SQLite error code. Otherwise, SQLITE_OK.
  29432. */
  29433. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  29434. int rc = SQLITE_OK;
  29435. Pager *pPager = (Pager *)pCtx;
  29436. PgHdr *pPg;
  29437. assert( pagerUseWal(pPager) );
  29438. pPg = sqlite3PagerLookup(pPager, iPg);
  29439. if( pPg ){
  29440. if( sqlite3PcachePageRefcount(pPg)==1 ){
  29441. sqlite3PcacheDrop(pPg);
  29442. }else{
  29443. u32 iFrame = 0;
  29444. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  29445. if( rc==SQLITE_OK ){
  29446. rc = readDbPage(pPg, iFrame);
  29447. }
  29448. if( rc==SQLITE_OK ){
  29449. pPager->xReiniter(pPg);
  29450. }
  29451. sqlite3PagerUnref(pPg);
  29452. }
  29453. }
  29454. /* Normally, if a transaction is rolled back, any backup processes are
  29455. ** updated as data is copied out of the rollback journal and into the
  29456. ** database. This is not generally possible with a WAL database, as
  29457. ** rollback involves simply truncating the log file. Therefore, if one
  29458. ** or more frames have already been written to the log (and therefore
  29459. ** also copied into the backup databases) as part of this transaction,
  29460. ** the backups must be restarted.
  29461. */
  29462. sqlite3BackupRestart(pPager->pBackup);
  29463. return rc;
  29464. }
  29465. /*
  29466. ** This function is called to rollback a transaction on a WAL database.
  29467. */
  29468. static int pagerRollbackWal(Pager *pPager){
  29469. int rc; /* Return Code */
  29470. PgHdr *pList; /* List of dirty pages to revert */
  29471. /* For all pages in the cache that are currently dirty or have already
  29472. ** been written (but not committed) to the log file, do one of the
  29473. ** following:
  29474. **
  29475. ** + Discard the cached page (if refcount==0), or
  29476. ** + Reload page content from the database (if refcount>0).
  29477. */
  29478. pPager->dbSize = pPager->dbOrigSize;
  29479. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  29480. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  29481. while( pList && rc==SQLITE_OK ){
  29482. PgHdr *pNext = pList->pDirty;
  29483. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  29484. pList = pNext;
  29485. }
  29486. return rc;
  29487. }
  29488. /*
  29489. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  29490. ** the contents of the list of pages headed by pList (connected by pDirty),
  29491. ** this function notifies any active backup processes that the pages have
  29492. ** changed.
  29493. **
  29494. ** The list of pages passed into this routine is always sorted by page number.
  29495. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  29496. */
  29497. static int pagerWalFrames(
  29498. Pager *pPager, /* Pager object */
  29499. PgHdr *pList, /* List of frames to log */
  29500. Pgno nTruncate, /* Database size after this commit */
  29501. int isCommit /* True if this is a commit */
  29502. ){
  29503. int rc; /* Return code */
  29504. int nList; /* Number of pages in pList */
  29505. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  29506. PgHdr *p; /* For looping over pages */
  29507. #endif
  29508. assert( pPager->pWal );
  29509. assert( pList );
  29510. #ifdef SQLITE_DEBUG
  29511. /* Verify that the page list is in accending order */
  29512. for(p=pList; p && p->pDirty; p=p->pDirty){
  29513. assert( p->pgno < p->pDirty->pgno );
  29514. }
  29515. #endif
  29516. assert( pList->pDirty==0 || isCommit );
  29517. if( isCommit ){
  29518. /* If a WAL transaction is being committed, there is no point in writing
  29519. ** any pages with page numbers greater than nTruncate into the WAL file.
  29520. ** They will never be read by any client. So remove them from the pDirty
  29521. ** list here. */
  29522. PgHdr *p;
  29523. PgHdr **ppNext = &pList;
  29524. nList = 0;
  29525. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  29526. if( p->pgno<=nTruncate ){
  29527. ppNext = &p->pDirty;
  29528. nList++;
  29529. }
  29530. }
  29531. assert( pList );
  29532. }else{
  29533. nList = 1;
  29534. }
  29535. pPager->aStat[PAGER_STAT_WRITE] += nList;
  29536. if( pList->pgno==1 ) pager_write_changecounter(pList);
  29537. rc = sqlite3WalFrames(pPager->pWal,
  29538. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  29539. );
  29540. if( rc==SQLITE_OK && pPager->pBackup ){
  29541. PgHdr *p;
  29542. for(p=pList; p; p=p->pDirty){
  29543. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  29544. }
  29545. }
  29546. #ifdef SQLITE_CHECK_PAGES
  29547. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  29548. for(p=pList; p; p=p->pDirty){
  29549. pager_set_pagehash(p);
  29550. }
  29551. #endif
  29552. return rc;
  29553. }
  29554. /*
  29555. ** Begin a read transaction on the WAL.
  29556. **
  29557. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  29558. ** makes a snapshot of the database at the current point in time and preserves
  29559. ** that snapshot for use by the reader in spite of concurrently changes by
  29560. ** other writers or checkpointers.
  29561. */
  29562. static int pagerBeginReadTransaction(Pager *pPager){
  29563. int rc; /* Return code */
  29564. int changed = 0; /* True if cache must be reset */
  29565. assert( pagerUseWal(pPager) );
  29566. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  29567. /* sqlite3WalEndReadTransaction() was not called for the previous
  29568. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  29569. ** are in locking_mode=NORMAL and EndRead() was previously called,
  29570. ** the duplicate call is harmless.
  29571. */
  29572. sqlite3WalEndReadTransaction(pPager->pWal);
  29573. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  29574. if( rc!=SQLITE_OK || changed ){
  29575. pager_reset(pPager);
  29576. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  29577. }
  29578. return rc;
  29579. }
  29580. #endif
  29581. /*
  29582. ** This function is called as part of the transition from PAGER_OPEN
  29583. ** to PAGER_READER state to determine the size of the database file
  29584. ** in pages (assuming the page size currently stored in Pager.pageSize).
  29585. **
  29586. ** If no error occurs, SQLITE_OK is returned and the size of the database
  29587. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  29588. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  29589. */
  29590. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  29591. Pgno nPage; /* Value to return via *pnPage */
  29592. /* Query the WAL sub-system for the database size. The WalDbsize()
  29593. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  29594. ** if the database size is not available. The database size is not
  29595. ** available from the WAL sub-system if the log file is empty or
  29596. ** contains no valid committed transactions.
  29597. */
  29598. assert( pPager->eState==PAGER_OPEN );
  29599. assert( pPager->eLock>=SHARED_LOCK );
  29600. nPage = sqlite3WalDbsize(pPager->pWal);
  29601. /* If the database size was not available from the WAL sub-system,
  29602. ** determine it based on the size of the database file. If the size
  29603. ** of the database file is not an integer multiple of the page-size,
  29604. ** round down to the nearest page. Except, any file larger than 0
  29605. ** bytes in size is considered to contain at least one page.
  29606. */
  29607. if( nPage==0 ){
  29608. i64 n = 0; /* Size of db file in bytes */
  29609. assert( isOpen(pPager->fd) || pPager->tempFile );
  29610. if( isOpen(pPager->fd) ){
  29611. int rc = sqlite3OsFileSize(pPager->fd, &n);
  29612. if( rc!=SQLITE_OK ){
  29613. return rc;
  29614. }
  29615. }
  29616. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  29617. }
  29618. /* If the current number of pages in the file is greater than the
  29619. ** configured maximum pager number, increase the allowed limit so
  29620. ** that the file can be read.
  29621. */
  29622. if( nPage>pPager->mxPgno ){
  29623. pPager->mxPgno = (Pgno)nPage;
  29624. }
  29625. *pnPage = nPage;
  29626. return SQLITE_OK;
  29627. }
  29628. #ifndef SQLITE_OMIT_WAL
  29629. /*
  29630. ** Check if the *-wal file that corresponds to the database opened by pPager
  29631. ** exists if the database is not empy, or verify that the *-wal file does
  29632. ** not exist (by deleting it) if the database file is empty.
  29633. **
  29634. ** If the database is not empty and the *-wal file exists, open the pager
  29635. ** in WAL mode. If the database is empty or if no *-wal file exists and
  29636. ** if no error occurs, make sure Pager.journalMode is not set to
  29637. ** PAGER_JOURNALMODE_WAL.
  29638. **
  29639. ** Return SQLITE_OK or an error code.
  29640. **
  29641. ** The caller must hold a SHARED lock on the database file to call this
  29642. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  29643. ** a WAL on a none-empty database, this ensures there is no race condition
  29644. ** between the xAccess() below and an xDelete() being executed by some
  29645. ** other connection.
  29646. */
  29647. static int pagerOpenWalIfPresent(Pager *pPager){
  29648. int rc = SQLITE_OK;
  29649. assert( pPager->eState==PAGER_OPEN );
  29650. assert( pPager->eLock>=SHARED_LOCK );
  29651. if( !pPager->tempFile ){
  29652. int isWal; /* True if WAL file exists */
  29653. Pgno nPage; /* Size of the database file */
  29654. rc = pagerPagecount(pPager, &nPage);
  29655. if( rc ) return rc;
  29656. if( nPage==0 ){
  29657. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  29658. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  29659. isWal = 0;
  29660. }else{
  29661. rc = sqlite3OsAccess(
  29662. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  29663. );
  29664. }
  29665. if( rc==SQLITE_OK ){
  29666. if( isWal ){
  29667. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  29668. rc = sqlite3PagerOpenWal(pPager, 0);
  29669. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  29670. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  29671. }
  29672. }
  29673. }
  29674. return rc;
  29675. }
  29676. #endif
  29677. /*
  29678. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  29679. ** the entire master journal file. The case pSavepoint==NULL occurs when
  29680. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  29681. ** savepoint.
  29682. **
  29683. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  29684. ** being rolled back), then the rollback consists of up to three stages,
  29685. ** performed in the order specified:
  29686. **
  29687. ** * Pages are played back from the main journal starting at byte
  29688. ** offset PagerSavepoint.iOffset and continuing to
  29689. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  29690. ** file if PagerSavepoint.iHdrOffset is zero.
  29691. **
  29692. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  29693. ** back starting from the journal header immediately following
  29694. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  29695. **
  29696. ** * Pages are then played back from the sub-journal file, starting
  29697. ** with the PagerSavepoint.iSubRec and continuing to the end of
  29698. ** the journal file.
  29699. **
  29700. ** Throughout the rollback process, each time a page is rolled back, the
  29701. ** corresponding bit is set in a bitvec structure (variable pDone in the
  29702. ** implementation below). This is used to ensure that a page is only
  29703. ** rolled back the first time it is encountered in either journal.
  29704. **
  29705. ** If pSavepoint is NULL, then pages are only played back from the main
  29706. ** journal file. There is no need for a bitvec in this case.
  29707. **
  29708. ** In either case, before playback commences the Pager.dbSize variable
  29709. ** is reset to the value that it held at the start of the savepoint
  29710. ** (or transaction). No page with a page-number greater than this value
  29711. ** is played back. If one is encountered it is simply skipped.
  29712. */
  29713. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  29714. i64 szJ; /* Effective size of the main journal */
  29715. i64 iHdrOff; /* End of first segment of main-journal records */
  29716. int rc = SQLITE_OK; /* Return code */
  29717. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  29718. assert( pPager->eState!=PAGER_ERROR );
  29719. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  29720. /* Allocate a bitvec to use to store the set of pages rolled back */
  29721. if( pSavepoint ){
  29722. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  29723. if( !pDone ){
  29724. return SQLITE_NOMEM;
  29725. }
  29726. }
  29727. /* Set the database size back to the value it was before the savepoint
  29728. ** being reverted was opened.
  29729. */
  29730. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  29731. pPager->changeCountDone = pPager->tempFile;
  29732. if( !pSavepoint && pagerUseWal(pPager) ){
  29733. return pagerRollbackWal(pPager);
  29734. }
  29735. /* Use pPager->journalOff as the effective size of the main rollback
  29736. ** journal. The actual file might be larger than this in
  29737. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  29738. ** past pPager->journalOff is off-limits to us.
  29739. */
  29740. szJ = pPager->journalOff;
  29741. assert( pagerUseWal(pPager)==0 || szJ==0 );
  29742. /* Begin by rolling back records from the main journal starting at
  29743. ** PagerSavepoint.iOffset and continuing to the next journal header.
  29744. ** There might be records in the main journal that have a page number
  29745. ** greater than the current database size (pPager->dbSize) but those
  29746. ** will be skipped automatically. Pages are added to pDone as they
  29747. ** are played back.
  29748. */
  29749. if( pSavepoint && !pagerUseWal(pPager) ){
  29750. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  29751. pPager->journalOff = pSavepoint->iOffset;
  29752. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  29753. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  29754. }
  29755. assert( rc!=SQLITE_DONE );
  29756. }else{
  29757. pPager->journalOff = 0;
  29758. }
  29759. /* Continue rolling back records out of the main journal starting at
  29760. ** the first journal header seen and continuing until the effective end
  29761. ** of the main journal file. Continue to skip out-of-range pages and
  29762. ** continue adding pages rolled back to pDone.
  29763. */
  29764. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  29765. u32 ii; /* Loop counter */
  29766. u32 nJRec = 0; /* Number of Journal Records */
  29767. u32 dummy;
  29768. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  29769. assert( rc!=SQLITE_DONE );
  29770. /*
  29771. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  29772. ** test is related to ticket #2565. See the discussion in the
  29773. ** pager_playback() function for additional information.
  29774. */
  29775. if( nJRec==0
  29776. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  29777. ){
  29778. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  29779. }
  29780. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  29781. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  29782. }
  29783. assert( rc!=SQLITE_DONE );
  29784. }
  29785. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  29786. /* Finally, rollback pages from the sub-journal. Page that were
  29787. ** previously rolled back out of the main journal (and are hence in pDone)
  29788. ** will be skipped. Out-of-range pages are also skipped.
  29789. */
  29790. if( pSavepoint ){
  29791. u32 ii; /* Loop counter */
  29792. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  29793. if( pagerUseWal(pPager) ){
  29794. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  29795. }
  29796. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  29797. assert( offset==(i64)ii*(4+pPager->pageSize) );
  29798. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  29799. }
  29800. assert( rc!=SQLITE_DONE );
  29801. }
  29802. sqlite3BitvecDestroy(pDone);
  29803. if( rc==SQLITE_OK ){
  29804. pPager->journalOff = szJ;
  29805. }
  29806. return rc;
  29807. }
  29808. /*
  29809. ** Change the maximum number of in-memory pages that are allowed.
  29810. */
  29811. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  29812. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  29813. }
  29814. /*
  29815. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  29816. */
  29817. static void pagerFixMaplimit(Pager *pPager){
  29818. #if SQLITE_MAX_MMAP_SIZE>0
  29819. sqlite3_file *fd = pPager->fd;
  29820. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  29821. sqlite3_int64 sz;
  29822. sz = pPager->szMmap;
  29823. pPager->bUseFetch = (sz>0);
  29824. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  29825. }
  29826. #endif
  29827. }
  29828. /*
  29829. ** Change the maximum size of any memory mapping made of the database file.
  29830. */
  29831. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  29832. pPager->szMmap = szMmap;
  29833. pagerFixMaplimit(pPager);
  29834. }
  29835. /*
  29836. ** Free as much memory as possible from the pager.
  29837. */
  29838. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  29839. sqlite3PcacheShrink(pPager->pPCache);
  29840. }
  29841. /*
  29842. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  29843. **
  29844. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  29845. ** of the database to damage due to OS crashes or power failures by
  29846. ** changing the number of syncs()s when writing the journals.
  29847. ** There are three levels:
  29848. **
  29849. ** OFF sqlite3OsSync() is never called. This is the default
  29850. ** for temporary and transient files.
  29851. **
  29852. ** NORMAL The journal is synced once before writes begin on the
  29853. ** database. This is normally adequate protection, but
  29854. ** it is theoretically possible, though very unlikely,
  29855. ** that an inopertune power failure could leave the journal
  29856. ** in a state which would cause damage to the database
  29857. ** when it is rolled back.
  29858. **
  29859. ** FULL The journal is synced twice before writes begin on the
  29860. ** database (with some additional information - the nRec field
  29861. ** of the journal header - being written in between the two
  29862. ** syncs). If we assume that writing a
  29863. ** single disk sector is atomic, then this mode provides
  29864. ** assurance that the journal will not be corrupted to the
  29865. ** point of causing damage to the database during rollback.
  29866. **
  29867. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  29868. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  29869. ** prior to the start of checkpoint and that the database file is synced
  29870. ** at the conclusion of the checkpoint if the entire content of the WAL
  29871. ** was written back into the database. But no sync operations occur for
  29872. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  29873. ** file is synced following each commit operation, in addition to the
  29874. ** syncs associated with NORMAL.
  29875. **
  29876. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  29877. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  29878. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  29879. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  29880. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  29881. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  29882. ** the xSync primitive is called and is relevant to all platforms.
  29883. **
  29884. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  29885. ** and FULL=3.
  29886. */
  29887. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  29888. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  29889. Pager *pPager, /* The pager to set safety level for */
  29890. unsigned pgFlags /* Various flags */
  29891. ){
  29892. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  29893. assert( level>=1 && level<=3 );
  29894. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  29895. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  29896. if( pPager->noSync ){
  29897. pPager->syncFlags = 0;
  29898. pPager->ckptSyncFlags = 0;
  29899. }else if( pgFlags & PAGER_FULLFSYNC ){
  29900. pPager->syncFlags = SQLITE_SYNC_FULL;
  29901. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  29902. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  29903. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  29904. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  29905. }else{
  29906. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  29907. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  29908. }
  29909. pPager->walSyncFlags = pPager->syncFlags;
  29910. if( pPager->fullSync ){
  29911. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  29912. }
  29913. if( pgFlags & PAGER_CACHESPILL ){
  29914. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  29915. }else{
  29916. pPager->doNotSpill |= SPILLFLAG_OFF;
  29917. }
  29918. }
  29919. #endif
  29920. /*
  29921. ** The following global variable is incremented whenever the library
  29922. ** attempts to open a temporary file. This information is used for
  29923. ** testing and analysis only.
  29924. */
  29925. #ifdef SQLITE_TEST
  29926. SQLITE_API int sqlite3_opentemp_count = 0;
  29927. #endif
  29928. /*
  29929. ** Open a temporary file.
  29930. **
  29931. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  29932. ** or some other error code if we fail. The OS will automatically
  29933. ** delete the temporary file when it is closed.
  29934. **
  29935. ** The flags passed to the VFS layer xOpen() call are those specified
  29936. ** by parameter vfsFlags ORed with the following:
  29937. **
  29938. ** SQLITE_OPEN_READWRITE
  29939. ** SQLITE_OPEN_CREATE
  29940. ** SQLITE_OPEN_EXCLUSIVE
  29941. ** SQLITE_OPEN_DELETEONCLOSE
  29942. */
  29943. static int pagerOpentemp(
  29944. Pager *pPager, /* The pager object */
  29945. sqlite3_file *pFile, /* Write the file descriptor here */
  29946. int vfsFlags /* Flags passed through to the VFS */
  29947. ){
  29948. int rc; /* Return code */
  29949. #ifdef SQLITE_TEST
  29950. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  29951. #endif
  29952. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  29953. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  29954. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  29955. assert( rc!=SQLITE_OK || isOpen(pFile) );
  29956. return rc;
  29957. }
  29958. /*
  29959. ** Set the busy handler function.
  29960. **
  29961. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  29962. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  29963. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  29964. ** lock. It does *not* invoke the busy handler when upgrading from
  29965. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  29966. ** (which occurs during hot-journal rollback). Summary:
  29967. **
  29968. ** Transition | Invokes xBusyHandler
  29969. ** --------------------------------------------------------
  29970. ** NO_LOCK -> SHARED_LOCK | Yes
  29971. ** SHARED_LOCK -> RESERVED_LOCK | No
  29972. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  29973. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  29974. **
  29975. ** If the busy-handler callback returns non-zero, the lock is
  29976. ** retried. If it returns zero, then the SQLITE_BUSY error is
  29977. ** returned to the caller of the pager API function.
  29978. */
  29979. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  29980. Pager *pPager, /* Pager object */
  29981. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  29982. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  29983. ){
  29984. pPager->xBusyHandler = xBusyHandler;
  29985. pPager->pBusyHandlerArg = pBusyHandlerArg;
  29986. if( isOpen(pPager->fd) ){
  29987. void **ap = (void **)&pPager->xBusyHandler;
  29988. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  29989. assert( ap[1]==pBusyHandlerArg );
  29990. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  29991. }
  29992. }
  29993. /*
  29994. ** Change the page size used by the Pager object. The new page size
  29995. ** is passed in *pPageSize.
  29996. **
  29997. ** If the pager is in the error state when this function is called, it
  29998. ** is a no-op. The value returned is the error state error code (i.e.
  29999. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  30000. **
  30001. ** Otherwise, if all of the following are true:
  30002. **
  30003. ** * the new page size (value of *pPageSize) is valid (a power
  30004. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  30005. **
  30006. ** * there are no outstanding page references, and
  30007. **
  30008. ** * the database is either not an in-memory database or it is
  30009. ** an in-memory database that currently consists of zero pages.
  30010. **
  30011. ** then the pager object page size is set to *pPageSize.
  30012. **
  30013. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  30014. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  30015. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  30016. ** In all other cases, SQLITE_OK is returned.
  30017. **
  30018. ** If the page size is not changed, either because one of the enumerated
  30019. ** conditions above is not true, the pager was in error state when this
  30020. ** function was called, or because the memory allocation attempt failed,
  30021. ** then *pPageSize is set to the old, retained page size before returning.
  30022. */
  30023. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  30024. int rc = SQLITE_OK;
  30025. /* It is not possible to do a full assert_pager_state() here, as this
  30026. ** function may be called from within PagerOpen(), before the state
  30027. ** of the Pager object is internally consistent.
  30028. **
  30029. ** At one point this function returned an error if the pager was in
  30030. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  30031. ** there is at least one outstanding page reference, this function
  30032. ** is a no-op for that case anyhow.
  30033. */
  30034. u32 pageSize = *pPageSize;
  30035. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  30036. if( (pPager->memDb==0 || pPager->dbSize==0)
  30037. && sqlite3PcacheRefCount(pPager->pPCache)==0
  30038. && pageSize && pageSize!=(u32)pPager->pageSize
  30039. ){
  30040. char *pNew = NULL; /* New temp space */
  30041. i64 nByte = 0;
  30042. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  30043. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  30044. }
  30045. if( rc==SQLITE_OK ){
  30046. pNew = (char *)sqlite3PageMalloc(pageSize);
  30047. if( !pNew ) rc = SQLITE_NOMEM;
  30048. }
  30049. if( rc==SQLITE_OK ){
  30050. pager_reset(pPager);
  30051. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  30052. pPager->pageSize = pageSize;
  30053. sqlite3PageFree(pPager->pTmpSpace);
  30054. pPager->pTmpSpace = pNew;
  30055. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  30056. }
  30057. }
  30058. *pPageSize = pPager->pageSize;
  30059. if( rc==SQLITE_OK ){
  30060. if( nReserve<0 ) nReserve = pPager->nReserve;
  30061. assert( nReserve>=0 && nReserve<1000 );
  30062. pPager->nReserve = (i16)nReserve;
  30063. pagerReportSize(pPager);
  30064. pagerFixMaplimit(pPager);
  30065. }
  30066. return rc;
  30067. }
  30068. /*
  30069. ** Return a pointer to the "temporary page" buffer held internally
  30070. ** by the pager. This is a buffer that is big enough to hold the
  30071. ** entire content of a database page. This buffer is used internally
  30072. ** during rollback and will be overwritten whenever a rollback
  30073. ** occurs. But other modules are free to use it too, as long as
  30074. ** no rollbacks are happening.
  30075. */
  30076. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  30077. return pPager->pTmpSpace;
  30078. }
  30079. /*
  30080. ** Attempt to set the maximum database page count if mxPage is positive.
  30081. ** Make no changes if mxPage is zero or negative. And never reduce the
  30082. ** maximum page count below the current size of the database.
  30083. **
  30084. ** Regardless of mxPage, return the current maximum page count.
  30085. */
  30086. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  30087. if( mxPage>0 ){
  30088. pPager->mxPgno = mxPage;
  30089. }
  30090. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  30091. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  30092. return pPager->mxPgno;
  30093. }
  30094. /*
  30095. ** The following set of routines are used to disable the simulated
  30096. ** I/O error mechanism. These routines are used to avoid simulated
  30097. ** errors in places where we do not care about errors.
  30098. **
  30099. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  30100. ** and generate no code.
  30101. */
  30102. #ifdef SQLITE_TEST
  30103. SQLITE_API extern int sqlite3_io_error_pending;
  30104. SQLITE_API extern int sqlite3_io_error_hit;
  30105. static int saved_cnt;
  30106. void disable_simulated_io_errors(void){
  30107. saved_cnt = sqlite3_io_error_pending;
  30108. sqlite3_io_error_pending = -1;
  30109. }
  30110. void enable_simulated_io_errors(void){
  30111. sqlite3_io_error_pending = saved_cnt;
  30112. }
  30113. #else
  30114. # define disable_simulated_io_errors()
  30115. # define enable_simulated_io_errors()
  30116. #endif
  30117. /*
  30118. ** Read the first N bytes from the beginning of the file into memory
  30119. ** that pDest points to.
  30120. **
  30121. ** If the pager was opened on a transient file (zFilename==""), or
  30122. ** opened on a file less than N bytes in size, the output buffer is
  30123. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  30124. ** function is used to read database headers, and a new transient or
  30125. ** zero sized database has a header than consists entirely of zeroes.
  30126. **
  30127. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  30128. ** the error code is returned to the caller and the contents of the
  30129. ** output buffer undefined.
  30130. */
  30131. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  30132. int rc = SQLITE_OK;
  30133. memset(pDest, 0, N);
  30134. assert( isOpen(pPager->fd) || pPager->tempFile );
  30135. /* This routine is only called by btree immediately after creating
  30136. ** the Pager object. There has not been an opportunity to transition
  30137. ** to WAL mode yet.
  30138. */
  30139. assert( !pagerUseWal(pPager) );
  30140. if( isOpen(pPager->fd) ){
  30141. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  30142. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  30143. if( rc==SQLITE_IOERR_SHORT_READ ){
  30144. rc = SQLITE_OK;
  30145. }
  30146. }
  30147. return rc;
  30148. }
  30149. /*
  30150. ** This function may only be called when a read-transaction is open on
  30151. ** the pager. It returns the total number of pages in the database.
  30152. **
  30153. ** However, if the file is between 1 and <page-size> bytes in size, then
  30154. ** this is considered a 1 page file.
  30155. */
  30156. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  30157. assert( pPager->eState>=PAGER_READER );
  30158. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  30159. *pnPage = (int)pPager->dbSize;
  30160. }
  30161. /*
  30162. ** Try to obtain a lock of type locktype on the database file. If
  30163. ** a similar or greater lock is already held, this function is a no-op
  30164. ** (returning SQLITE_OK immediately).
  30165. **
  30166. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  30167. ** the busy callback if the lock is currently not available. Repeat
  30168. ** until the busy callback returns false or until the attempt to
  30169. ** obtain the lock succeeds.
  30170. **
  30171. ** Return SQLITE_OK on success and an error code if we cannot obtain
  30172. ** the lock. If the lock is obtained successfully, set the Pager.state
  30173. ** variable to locktype before returning.
  30174. */
  30175. static int pager_wait_on_lock(Pager *pPager, int locktype){
  30176. int rc; /* Return code */
  30177. /* Check that this is either a no-op (because the requested lock is
  30178. ** already held, or one of the transistions that the busy-handler
  30179. ** may be invoked during, according to the comment above
  30180. ** sqlite3PagerSetBusyhandler().
  30181. */
  30182. assert( (pPager->eLock>=locktype)
  30183. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  30184. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  30185. );
  30186. do {
  30187. rc = pagerLockDb(pPager, locktype);
  30188. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  30189. return rc;
  30190. }
  30191. /*
  30192. ** Function assertTruncateConstraint(pPager) checks that one of the
  30193. ** following is true for all dirty pages currently in the page-cache:
  30194. **
  30195. ** a) The page number is less than or equal to the size of the
  30196. ** current database image, in pages, OR
  30197. **
  30198. ** b) if the page content were written at this time, it would not
  30199. ** be necessary to write the current content out to the sub-journal
  30200. ** (as determined by function subjRequiresPage()).
  30201. **
  30202. ** If the condition asserted by this function were not true, and the
  30203. ** dirty page were to be discarded from the cache via the pagerStress()
  30204. ** routine, pagerStress() would not write the current page content to
  30205. ** the database file. If a savepoint transaction were rolled back after
  30206. ** this happened, the correct behavior would be to restore the current
  30207. ** content of the page. However, since this content is not present in either
  30208. ** the database file or the portion of the rollback journal and
  30209. ** sub-journal rolled back the content could not be restored and the
  30210. ** database image would become corrupt. It is therefore fortunate that
  30211. ** this circumstance cannot arise.
  30212. */
  30213. #if defined(SQLITE_DEBUG)
  30214. static void assertTruncateConstraintCb(PgHdr *pPg){
  30215. assert( pPg->flags&PGHDR_DIRTY );
  30216. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  30217. }
  30218. static void assertTruncateConstraint(Pager *pPager){
  30219. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  30220. }
  30221. #else
  30222. # define assertTruncateConstraint(pPager)
  30223. #endif
  30224. /*
  30225. ** Truncate the in-memory database file image to nPage pages. This
  30226. ** function does not actually modify the database file on disk. It
  30227. ** just sets the internal state of the pager object so that the
  30228. ** truncation will be done when the current transaction is committed.
  30229. **
  30230. ** This function is only called right before committing a transaction.
  30231. ** Once this function has been called, the transaction must either be
  30232. ** rolled back or committed. It is not safe to call this function and
  30233. ** then continue writing to the database.
  30234. */
  30235. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  30236. assert( pPager->dbSize>=nPage );
  30237. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  30238. pPager->dbSize = nPage;
  30239. /* At one point the code here called assertTruncateConstraint() to
  30240. ** ensure that all pages being truncated away by this operation are,
  30241. ** if one or more savepoints are open, present in the savepoint
  30242. ** journal so that they can be restored if the savepoint is rolled
  30243. ** back. This is no longer necessary as this function is now only
  30244. ** called right before committing a transaction. So although the
  30245. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  30246. ** they cannot be rolled back. So the assertTruncateConstraint() call
  30247. ** is no longer correct. */
  30248. }
  30249. /*
  30250. ** This function is called before attempting a hot-journal rollback. It
  30251. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  30252. ** size of the journal file so that the pager_playback() routine knows
  30253. ** that the entire journal file has been synced.
  30254. **
  30255. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  30256. ** that if a power-failure occurs during the rollback, the process that
  30257. ** attempts rollback following system recovery sees the same journal
  30258. ** content as this process.
  30259. **
  30260. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  30261. ** an SQLite error code.
  30262. */
  30263. static int pagerSyncHotJournal(Pager *pPager){
  30264. int rc = SQLITE_OK;
  30265. if( !pPager->noSync ){
  30266. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  30267. }
  30268. if( rc==SQLITE_OK ){
  30269. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  30270. }
  30271. return rc;
  30272. }
  30273. /*
  30274. ** Obtain a reference to a memory mapped page object for page number pgno.
  30275. ** The new object will use the pointer pData, obtained from xFetch().
  30276. ** If successful, set *ppPage to point to the new page reference
  30277. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  30278. ** *ppPage to zero.
  30279. **
  30280. ** Page references obtained by calling this function should be released
  30281. ** by calling pagerReleaseMapPage().
  30282. */
  30283. static int pagerAcquireMapPage(
  30284. Pager *pPager, /* Pager object */
  30285. Pgno pgno, /* Page number */
  30286. void *pData, /* xFetch()'d data for this page */
  30287. PgHdr **ppPage /* OUT: Acquired page object */
  30288. ){
  30289. PgHdr *p; /* Memory mapped page to return */
  30290. if( pPager->pMmapFreelist ){
  30291. *ppPage = p = pPager->pMmapFreelist;
  30292. pPager->pMmapFreelist = p->pDirty;
  30293. p->pDirty = 0;
  30294. memset(p->pExtra, 0, pPager->nExtra);
  30295. }else{
  30296. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  30297. if( p==0 ){
  30298. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  30299. return SQLITE_NOMEM;
  30300. }
  30301. p->pExtra = (void *)&p[1];
  30302. p->flags = PGHDR_MMAP;
  30303. p->nRef = 1;
  30304. p->pPager = pPager;
  30305. }
  30306. assert( p->pExtra==(void *)&p[1] );
  30307. assert( p->pPage==0 );
  30308. assert( p->flags==PGHDR_MMAP );
  30309. assert( p->pPager==pPager );
  30310. assert( p->nRef==1 );
  30311. p->pgno = pgno;
  30312. p->pData = pData;
  30313. pPager->nMmapOut++;
  30314. return SQLITE_OK;
  30315. }
  30316. /*
  30317. ** Release a reference to page pPg. pPg must have been returned by an
  30318. ** earlier call to pagerAcquireMapPage().
  30319. */
  30320. static void pagerReleaseMapPage(PgHdr *pPg){
  30321. Pager *pPager = pPg->pPager;
  30322. pPager->nMmapOut--;
  30323. pPg->pDirty = pPager->pMmapFreelist;
  30324. pPager->pMmapFreelist = pPg;
  30325. assert( pPager->fd->pMethods->iVersion>=3 );
  30326. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  30327. }
  30328. /*
  30329. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  30330. */
  30331. static void pagerFreeMapHdrs(Pager *pPager){
  30332. PgHdr *p;
  30333. PgHdr *pNext;
  30334. for(p=pPager->pMmapFreelist; p; p=pNext){
  30335. pNext = p->pDirty;
  30336. sqlite3_free(p);
  30337. }
  30338. }
  30339. /*
  30340. ** Shutdown the page cache. Free all memory and close all files.
  30341. **
  30342. ** If a transaction was in progress when this routine is called, that
  30343. ** transaction is rolled back. All outstanding pages are invalidated
  30344. ** and their memory is freed. Any attempt to use a page associated
  30345. ** with this page cache after this function returns will likely
  30346. ** result in a coredump.
  30347. **
  30348. ** This function always succeeds. If a transaction is active an attempt
  30349. ** is made to roll it back. If an error occurs during the rollback
  30350. ** a hot journal may be left in the filesystem but no error is returned
  30351. ** to the caller.
  30352. */
  30353. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  30354. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  30355. assert( assert_pager_state(pPager) );
  30356. disable_simulated_io_errors();
  30357. sqlite3BeginBenignMalloc();
  30358. pagerFreeMapHdrs(pPager);
  30359. /* pPager->errCode = 0; */
  30360. pPager->exclusiveMode = 0;
  30361. #ifndef SQLITE_OMIT_WAL
  30362. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  30363. pPager->pWal = 0;
  30364. #endif
  30365. pager_reset(pPager);
  30366. if( MEMDB ){
  30367. pager_unlock(pPager);
  30368. }else{
  30369. /* If it is open, sync the journal file before calling UnlockAndRollback.
  30370. ** If this is not done, then an unsynced portion of the open journal
  30371. ** file may be played back into the database. If a power failure occurs
  30372. ** while this is happening, the database could become corrupt.
  30373. **
  30374. ** If an error occurs while trying to sync the journal, shift the pager
  30375. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  30376. ** database and close the journal file without attempting to roll it
  30377. ** back or finalize it. The next database user will have to do hot-journal
  30378. ** rollback before accessing the database file.
  30379. */
  30380. if( isOpen(pPager->jfd) ){
  30381. pager_error(pPager, pagerSyncHotJournal(pPager));
  30382. }
  30383. pagerUnlockAndRollback(pPager);
  30384. }
  30385. sqlite3EndBenignMalloc();
  30386. enable_simulated_io_errors();
  30387. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  30388. IOTRACE(("CLOSE %p\n", pPager))
  30389. sqlite3OsClose(pPager->jfd);
  30390. sqlite3OsClose(pPager->fd);
  30391. sqlite3PageFree(pTmp);
  30392. sqlite3PcacheClose(pPager->pPCache);
  30393. #ifdef SQLITE_HAS_CODEC
  30394. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  30395. #endif
  30396. assert( !pPager->aSavepoint && !pPager->pInJournal );
  30397. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  30398. sqlite3_free(pPager);
  30399. return SQLITE_OK;
  30400. }
  30401. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  30402. /*
  30403. ** Return the page number for page pPg.
  30404. */
  30405. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  30406. return pPg->pgno;
  30407. }
  30408. #endif
  30409. /*
  30410. ** Increment the reference count for page pPg.
  30411. */
  30412. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  30413. sqlite3PcacheRef(pPg);
  30414. }
  30415. /*
  30416. ** Sync the journal. In other words, make sure all the pages that have
  30417. ** been written to the journal have actually reached the surface of the
  30418. ** disk and can be restored in the event of a hot-journal rollback.
  30419. **
  30420. ** If the Pager.noSync flag is set, then this function is a no-op.
  30421. ** Otherwise, the actions required depend on the journal-mode and the
  30422. ** device characteristics of the file-system, as follows:
  30423. **
  30424. ** * If the journal file is an in-memory journal file, no action need
  30425. ** be taken.
  30426. **
  30427. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  30428. ** then the nRec field of the most recently written journal header
  30429. ** is updated to contain the number of journal records that have
  30430. ** been written following it. If the pager is operating in full-sync
  30431. ** mode, then the journal file is synced before this field is updated.
  30432. **
  30433. ** * If the device does not support the SEQUENTIAL property, then
  30434. ** journal file is synced.
  30435. **
  30436. ** Or, in pseudo-code:
  30437. **
  30438. ** if( NOT <in-memory journal> ){
  30439. ** if( NOT SAFE_APPEND ){
  30440. ** if( <full-sync mode> ) xSync(<journal file>);
  30441. ** <update nRec field>
  30442. ** }
  30443. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  30444. ** }
  30445. **
  30446. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  30447. ** page currently held in memory before returning SQLITE_OK. If an IO
  30448. ** error is encountered, then the IO error code is returned to the caller.
  30449. */
  30450. static int syncJournal(Pager *pPager, int newHdr){
  30451. int rc; /* Return code */
  30452. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  30453. || pPager->eState==PAGER_WRITER_DBMOD
  30454. );
  30455. assert( assert_pager_state(pPager) );
  30456. assert( !pagerUseWal(pPager) );
  30457. rc = sqlite3PagerExclusiveLock(pPager);
  30458. if( rc!=SQLITE_OK ) return rc;
  30459. if( !pPager->noSync ){
  30460. assert( !pPager->tempFile );
  30461. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  30462. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  30463. assert( isOpen(pPager->jfd) );
  30464. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  30465. /* This block deals with an obscure problem. If the last connection
  30466. ** that wrote to this database was operating in persistent-journal
  30467. ** mode, then the journal file may at this point actually be larger
  30468. ** than Pager.journalOff bytes. If the next thing in the journal
  30469. ** file happens to be a journal-header (written as part of the
  30470. ** previous connection's transaction), and a crash or power-failure
  30471. ** occurs after nRec is updated but before this connection writes
  30472. ** anything else to the journal file (or commits/rolls back its
  30473. ** transaction), then SQLite may become confused when doing the
  30474. ** hot-journal rollback following recovery. It may roll back all
  30475. ** of this connections data, then proceed to rolling back the old,
  30476. ** out-of-date data that follows it. Database corruption.
  30477. **
  30478. ** To work around this, if the journal file does appear to contain
  30479. ** a valid header following Pager.journalOff, then write a 0x00
  30480. ** byte to the start of it to prevent it from being recognized.
  30481. **
  30482. ** Variable iNextHdrOffset is set to the offset at which this
  30483. ** problematic header will occur, if it exists. aMagic is used
  30484. ** as a temporary buffer to inspect the first couple of bytes of
  30485. ** the potential journal header.
  30486. */
  30487. i64 iNextHdrOffset;
  30488. u8 aMagic[8];
  30489. u8 zHeader[sizeof(aJournalMagic)+4];
  30490. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  30491. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  30492. iNextHdrOffset = journalHdrOffset(pPager);
  30493. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  30494. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  30495. static const u8 zerobyte = 0;
  30496. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  30497. }
  30498. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  30499. return rc;
  30500. }
  30501. /* Write the nRec value into the journal file header. If in
  30502. ** full-synchronous mode, sync the journal first. This ensures that
  30503. ** all data has really hit the disk before nRec is updated to mark
  30504. ** it as a candidate for rollback.
  30505. **
  30506. ** This is not required if the persistent media supports the
  30507. ** SAFE_APPEND property. Because in this case it is not possible
  30508. ** for garbage data to be appended to the file, the nRec field
  30509. ** is populated with 0xFFFFFFFF when the journal header is written
  30510. ** and never needs to be updated.
  30511. */
  30512. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30513. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30514. IOTRACE(("JSYNC %p\n", pPager))
  30515. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  30516. if( rc!=SQLITE_OK ) return rc;
  30517. }
  30518. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  30519. rc = sqlite3OsWrite(
  30520. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  30521. );
  30522. if( rc!=SQLITE_OK ) return rc;
  30523. }
  30524. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  30525. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  30526. IOTRACE(("JSYNC %p\n", pPager))
  30527. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  30528. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  30529. );
  30530. if( rc!=SQLITE_OK ) return rc;
  30531. }
  30532. pPager->journalHdr = pPager->journalOff;
  30533. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  30534. pPager->nRec = 0;
  30535. rc = writeJournalHdr(pPager);
  30536. if( rc!=SQLITE_OK ) return rc;
  30537. }
  30538. }else{
  30539. pPager->journalHdr = pPager->journalOff;
  30540. }
  30541. }
  30542. /* Unless the pager is in noSync mode, the journal file was just
  30543. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  30544. ** all pages.
  30545. */
  30546. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  30547. pPager->eState = PAGER_WRITER_DBMOD;
  30548. assert( assert_pager_state(pPager) );
  30549. return SQLITE_OK;
  30550. }
  30551. /*
  30552. ** The argument is the first in a linked list of dirty pages connected
  30553. ** by the PgHdr.pDirty pointer. This function writes each one of the
  30554. ** in-memory pages in the list to the database file. The argument may
  30555. ** be NULL, representing an empty list. In this case this function is
  30556. ** a no-op.
  30557. **
  30558. ** The pager must hold at least a RESERVED lock when this function
  30559. ** is called. Before writing anything to the database file, this lock
  30560. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  30561. ** SQLITE_BUSY is returned and no data is written to the database file.
  30562. **
  30563. ** If the pager is a temp-file pager and the actual file-system file
  30564. ** is not yet open, it is created and opened before any data is
  30565. ** written out.
  30566. **
  30567. ** Once the lock has been upgraded and, if necessary, the file opened,
  30568. ** the pages are written out to the database file in list order. Writing
  30569. ** a page is skipped if it meets either of the following criteria:
  30570. **
  30571. ** * The page number is greater than Pager.dbSize, or
  30572. ** * The PGHDR_DONT_WRITE flag is set on the page.
  30573. **
  30574. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  30575. ** is updated accordingly. If page 1 is written out, then the value cached
  30576. ** in Pager.dbFileVers[] is updated to match the new value stored in
  30577. ** the database file.
  30578. **
  30579. ** If everything is successful, SQLITE_OK is returned. If an IO error
  30580. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  30581. ** be obtained, SQLITE_BUSY is returned.
  30582. */
  30583. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  30584. int rc = SQLITE_OK; /* Return code */
  30585. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  30586. assert( !pagerUseWal(pPager) );
  30587. assert( pPager->eState==PAGER_WRITER_DBMOD );
  30588. assert( pPager->eLock==EXCLUSIVE_LOCK );
  30589. /* If the file is a temp-file has not yet been opened, open it now. It
  30590. ** is not possible for rc to be other than SQLITE_OK if this branch
  30591. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  30592. */
  30593. if( !isOpen(pPager->fd) ){
  30594. assert( pPager->tempFile && rc==SQLITE_OK );
  30595. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  30596. }
  30597. /* Before the first write, give the VFS a hint of what the final
  30598. ** file size will be.
  30599. */
  30600. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  30601. if( rc==SQLITE_OK
  30602. && pPager->dbHintSize<pPager->dbSize
  30603. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  30604. ){
  30605. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  30606. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  30607. pPager->dbHintSize = pPager->dbSize;
  30608. }
  30609. while( rc==SQLITE_OK && pList ){
  30610. Pgno pgno = pList->pgno;
  30611. /* If there are dirty pages in the page cache with page numbers greater
  30612. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  30613. ** make the file smaller (presumably by auto-vacuum code). Do not write
  30614. ** any such pages to the file.
  30615. **
  30616. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  30617. ** set (set by sqlite3PagerDontWrite()).
  30618. */
  30619. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  30620. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  30621. char *pData; /* Data to write */
  30622. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  30623. if( pList->pgno==1 ) pager_write_changecounter(pList);
  30624. /* Encode the database */
  30625. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  30626. /* Write out the page data. */
  30627. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  30628. /* If page 1 was just written, update Pager.dbFileVers to match
  30629. ** the value now stored in the database file. If writing this
  30630. ** page caused the database file to grow, update dbFileSize.
  30631. */
  30632. if( pgno==1 ){
  30633. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  30634. }
  30635. if( pgno>pPager->dbFileSize ){
  30636. pPager->dbFileSize = pgno;
  30637. }
  30638. pPager->aStat[PAGER_STAT_WRITE]++;
  30639. /* Update any backup objects copying the contents of this pager. */
  30640. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  30641. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  30642. PAGERID(pPager), pgno, pager_pagehash(pList)));
  30643. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  30644. PAGER_INCR(sqlite3_pager_writedb_count);
  30645. }else{
  30646. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  30647. }
  30648. pager_set_pagehash(pList);
  30649. pList = pList->pDirty;
  30650. }
  30651. return rc;
  30652. }
  30653. /*
  30654. ** Ensure that the sub-journal file is open. If it is already open, this
  30655. ** function is a no-op.
  30656. **
  30657. ** SQLITE_OK is returned if everything goes according to plan. An
  30658. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  30659. ** fails.
  30660. */
  30661. static int openSubJournal(Pager *pPager){
  30662. int rc = SQLITE_OK;
  30663. if( !isOpen(pPager->sjfd) ){
  30664. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  30665. sqlite3MemJournalOpen(pPager->sjfd);
  30666. }else{
  30667. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  30668. }
  30669. }
  30670. return rc;
  30671. }
  30672. /*
  30673. ** Append a record of the current state of page pPg to the sub-journal.
  30674. ** It is the callers responsibility to use subjRequiresPage() to check
  30675. ** that it is really required before calling this function.
  30676. **
  30677. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  30678. ** for all open savepoints before returning.
  30679. **
  30680. ** This function returns SQLITE_OK if everything is successful, an IO
  30681. ** error code if the attempt to write to the sub-journal fails, or
  30682. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  30683. ** bitvec.
  30684. */
  30685. static int subjournalPage(PgHdr *pPg){
  30686. int rc = SQLITE_OK;
  30687. Pager *pPager = pPg->pPager;
  30688. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  30689. /* Open the sub-journal, if it has not already been opened */
  30690. assert( pPager->useJournal );
  30691. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  30692. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  30693. assert( pagerUseWal(pPager)
  30694. || pageInJournal(pPg)
  30695. || pPg->pgno>pPager->dbOrigSize
  30696. );
  30697. rc = openSubJournal(pPager);
  30698. /* If the sub-journal was opened successfully (or was already open),
  30699. ** write the journal record into the file. */
  30700. if( rc==SQLITE_OK ){
  30701. void *pData = pPg->pData;
  30702. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  30703. char *pData2;
  30704. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  30705. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  30706. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  30707. if( rc==SQLITE_OK ){
  30708. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  30709. }
  30710. }
  30711. }
  30712. if( rc==SQLITE_OK ){
  30713. pPager->nSubRec++;
  30714. assert( pPager->nSavepoint>0 );
  30715. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  30716. }
  30717. return rc;
  30718. }
  30719. /*
  30720. ** This function is called by the pcache layer when it has reached some
  30721. ** soft memory limit. The first argument is a pointer to a Pager object
  30722. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  30723. ** database). The second argument is a reference to a page that is
  30724. ** currently dirty but has no outstanding references. The page
  30725. ** is always associated with the Pager object passed as the first
  30726. ** argument.
  30727. **
  30728. ** The job of this function is to make pPg clean by writing its contents
  30729. ** out to the database file, if possible. This may involve syncing the
  30730. ** journal file.
  30731. **
  30732. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  30733. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  30734. ** page clean, the IO error code is returned. If the page cannot be
  30735. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  30736. ** is returned by sqlite3PcacheMakeClean() is not called.
  30737. */
  30738. static int pagerStress(void *p, PgHdr *pPg){
  30739. Pager *pPager = (Pager *)p;
  30740. int rc = SQLITE_OK;
  30741. assert( pPg->pPager==pPager );
  30742. assert( pPg->flags&PGHDR_DIRTY );
  30743. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  30744. ** journal (and adding a new header) is not allowed. This occurs
  30745. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  30746. ** pages belonging to the same sector.
  30747. **
  30748. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  30749. ** regardless of whether or not a sync is required. This is set during
  30750. ** a rollback or by user request, respectively.
  30751. **
  30752. ** Spilling is also prohibited when in an error state since that could
  30753. ** lead to database corruption. In the current implementaton it
  30754. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  30755. ** while in the error state, hence it is impossible for this routine to
  30756. ** be called in the error state. Nevertheless, we include a NEVER()
  30757. ** test for the error state as a safeguard against future changes.
  30758. */
  30759. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  30760. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  30761. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  30762. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  30763. if( pPager->doNotSpill
  30764. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  30765. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  30766. ){
  30767. return SQLITE_OK;
  30768. }
  30769. pPg->pDirty = 0;
  30770. if( pagerUseWal(pPager) ){
  30771. /* Write a single frame for this page to the log. */
  30772. if( subjRequiresPage(pPg) ){
  30773. rc = subjournalPage(pPg);
  30774. }
  30775. if( rc==SQLITE_OK ){
  30776. rc = pagerWalFrames(pPager, pPg, 0, 0);
  30777. }
  30778. }else{
  30779. /* Sync the journal file if required. */
  30780. if( pPg->flags&PGHDR_NEED_SYNC
  30781. || pPager->eState==PAGER_WRITER_CACHEMOD
  30782. ){
  30783. rc = syncJournal(pPager, 1);
  30784. }
  30785. /* If the page number of this page is larger than the current size of
  30786. ** the database image, it may need to be written to the sub-journal.
  30787. ** This is because the call to pager_write_pagelist() below will not
  30788. ** actually write data to the file in this case.
  30789. **
  30790. ** Consider the following sequence of events:
  30791. **
  30792. ** BEGIN;
  30793. ** <journal page X>
  30794. ** <modify page X>
  30795. ** SAVEPOINT sp;
  30796. ** <shrink database file to Y pages>
  30797. ** pagerStress(page X)
  30798. ** ROLLBACK TO sp;
  30799. **
  30800. ** If (X>Y), then when pagerStress is called page X will not be written
  30801. ** out to the database file, but will be dropped from the cache. Then,
  30802. ** following the "ROLLBACK TO sp" statement, reading page X will read
  30803. ** data from the database file. This will be the copy of page X as it
  30804. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  30805. ** was executed.
  30806. **
  30807. ** The solution is to write the current data for page X into the
  30808. ** sub-journal file now (if it is not already there), so that it will
  30809. ** be restored to its current value when the "ROLLBACK TO sp" is
  30810. ** executed.
  30811. */
  30812. if( NEVER(
  30813. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  30814. ) ){
  30815. rc = subjournalPage(pPg);
  30816. }
  30817. /* Write the contents of the page out to the database file. */
  30818. if( rc==SQLITE_OK ){
  30819. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  30820. rc = pager_write_pagelist(pPager, pPg);
  30821. }
  30822. }
  30823. /* Mark the page as clean. */
  30824. if( rc==SQLITE_OK ){
  30825. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  30826. sqlite3PcacheMakeClean(pPg);
  30827. }
  30828. return pager_error(pPager, rc);
  30829. }
  30830. /*
  30831. ** Allocate and initialize a new Pager object and put a pointer to it
  30832. ** in *ppPager. The pager should eventually be freed by passing it
  30833. ** to sqlite3PagerClose().
  30834. **
  30835. ** The zFilename argument is the path to the database file to open.
  30836. ** If zFilename is NULL then a randomly-named temporary file is created
  30837. ** and used as the file to be cached. Temporary files are be deleted
  30838. ** automatically when they are closed. If zFilename is ":memory:" then
  30839. ** all information is held in cache. It is never written to disk.
  30840. ** This can be used to implement an in-memory database.
  30841. **
  30842. ** The nExtra parameter specifies the number of bytes of space allocated
  30843. ** along with each page reference. This space is available to the user
  30844. ** via the sqlite3PagerGetExtra() API.
  30845. **
  30846. ** The flags argument is used to specify properties that affect the
  30847. ** operation of the pager. It should be passed some bitwise combination
  30848. ** of the PAGER_* flags.
  30849. **
  30850. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  30851. ** of the xOpen() method of the supplied VFS when opening files.
  30852. **
  30853. ** If the pager object is allocated and the specified file opened
  30854. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  30855. ** the new pager object. If an error occurs, *ppPager is set to NULL
  30856. ** and error code returned. This function may return SQLITE_NOMEM
  30857. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  30858. ** various SQLITE_IO_XXX errors.
  30859. */
  30860. SQLITE_PRIVATE int sqlite3PagerOpen(
  30861. sqlite3_vfs *pVfs, /* The virtual file system to use */
  30862. Pager **ppPager, /* OUT: Return the Pager structure here */
  30863. const char *zFilename, /* Name of the database file to open */
  30864. int nExtra, /* Extra bytes append to each in-memory page */
  30865. int flags, /* flags controlling this file */
  30866. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  30867. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  30868. ){
  30869. u8 *pPtr;
  30870. Pager *pPager = 0; /* Pager object to allocate and return */
  30871. int rc = SQLITE_OK; /* Return code */
  30872. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  30873. int memDb = 0; /* True if this is an in-memory file */
  30874. int readOnly = 0; /* True if this is a read-only file */
  30875. int journalFileSize; /* Bytes to allocate for each journal fd */
  30876. char *zPathname = 0; /* Full path to database file */
  30877. int nPathname = 0; /* Number of bytes in zPathname */
  30878. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  30879. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  30880. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  30881. const char *zUri = 0; /* URI args to copy */
  30882. int nUri = 0; /* Number of bytes of URI args at *zUri */
  30883. /* Figure out how much space is required for each journal file-handle
  30884. ** (there are two of them, the main journal and the sub-journal). This
  30885. ** is the maximum space required for an in-memory journal file handle
  30886. ** and a regular journal file-handle. Note that a "regular journal-handle"
  30887. ** may be a wrapper capable of caching the first portion of the journal
  30888. ** file in memory to implement the atomic-write optimization (see
  30889. ** source file journal.c).
  30890. */
  30891. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  30892. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  30893. }else{
  30894. journalFileSize = ROUND8(sqlite3MemJournalSize());
  30895. }
  30896. /* Set the output variable to NULL in case an error occurs. */
  30897. *ppPager = 0;
  30898. #ifndef SQLITE_OMIT_MEMORYDB
  30899. if( flags & PAGER_MEMORY ){
  30900. memDb = 1;
  30901. if( zFilename && zFilename[0] ){
  30902. zPathname = sqlite3DbStrDup(0, zFilename);
  30903. if( zPathname==0 ) return SQLITE_NOMEM;
  30904. nPathname = sqlite3Strlen30(zPathname);
  30905. zFilename = 0;
  30906. }
  30907. }
  30908. #endif
  30909. /* Compute and store the full pathname in an allocated buffer pointed
  30910. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  30911. ** leave both nPathname and zPathname set to 0.
  30912. */
  30913. if( zFilename && zFilename[0] ){
  30914. const char *z;
  30915. nPathname = pVfs->mxPathname+1;
  30916. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  30917. if( zPathname==0 ){
  30918. return SQLITE_NOMEM;
  30919. }
  30920. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  30921. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  30922. nPathname = sqlite3Strlen30(zPathname);
  30923. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  30924. while( *z ){
  30925. z += sqlite3Strlen30(z)+1;
  30926. z += sqlite3Strlen30(z)+1;
  30927. }
  30928. nUri = (int)(&z[1] - zUri);
  30929. assert( nUri>=0 );
  30930. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  30931. /* This branch is taken when the journal path required by
  30932. ** the database being opened will be more than pVfs->mxPathname
  30933. ** bytes in length. This means the database cannot be opened,
  30934. ** as it will not be possible to open the journal file or even
  30935. ** check for a hot-journal before reading.
  30936. */
  30937. rc = SQLITE_CANTOPEN_BKPT;
  30938. }
  30939. if( rc!=SQLITE_OK ){
  30940. sqlite3DbFree(0, zPathname);
  30941. return rc;
  30942. }
  30943. }
  30944. /* Allocate memory for the Pager structure, PCache object, the
  30945. ** three file descriptors, the database file name and the journal
  30946. ** file name. The layout in memory is as follows:
  30947. **
  30948. ** Pager object (sizeof(Pager) bytes)
  30949. ** PCache object (sqlite3PcacheSize() bytes)
  30950. ** Database file handle (pVfs->szOsFile bytes)
  30951. ** Sub-journal file handle (journalFileSize bytes)
  30952. ** Main journal file handle (journalFileSize bytes)
  30953. ** Database file name (nPathname+1 bytes)
  30954. ** Journal file name (nPathname+8+1 bytes)
  30955. */
  30956. pPtr = (u8 *)sqlite3MallocZero(
  30957. ROUND8(sizeof(*pPager)) + /* Pager structure */
  30958. ROUND8(pcacheSize) + /* PCache object */
  30959. ROUND8(pVfs->szOsFile) + /* The main db file */
  30960. journalFileSize * 2 + /* The two journal files */
  30961. nPathname + 1 + nUri + /* zFilename */
  30962. nPathname + 8 + 2 /* zJournal */
  30963. #ifndef SQLITE_OMIT_WAL
  30964. + nPathname + 4 + 2 /* zWal */
  30965. #endif
  30966. );
  30967. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  30968. if( !pPtr ){
  30969. sqlite3DbFree(0, zPathname);
  30970. return SQLITE_NOMEM;
  30971. }
  30972. pPager = (Pager*)(pPtr);
  30973. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  30974. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  30975. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  30976. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  30977. pPager->zFilename = (char*)(pPtr += journalFileSize);
  30978. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  30979. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  30980. if( zPathname ){
  30981. assert( nPathname>0 );
  30982. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  30983. memcpy(pPager->zFilename, zPathname, nPathname);
  30984. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  30985. memcpy(pPager->zJournal, zPathname, nPathname);
  30986. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  30987. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  30988. #ifndef SQLITE_OMIT_WAL
  30989. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  30990. memcpy(pPager->zWal, zPathname, nPathname);
  30991. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  30992. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  30993. #endif
  30994. sqlite3DbFree(0, zPathname);
  30995. }
  30996. pPager->pVfs = pVfs;
  30997. pPager->vfsFlags = vfsFlags;
  30998. /* Open the pager file.
  30999. */
  31000. if( zFilename && zFilename[0] ){
  31001. int fout = 0; /* VFS flags returned by xOpen() */
  31002. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  31003. assert( !memDb );
  31004. readOnly = (fout&SQLITE_OPEN_READONLY);
  31005. /* If the file was successfully opened for read/write access,
  31006. ** choose a default page size in case we have to create the
  31007. ** database file. The default page size is the maximum of:
  31008. **
  31009. ** + SQLITE_DEFAULT_PAGE_SIZE,
  31010. ** + The value returned by sqlite3OsSectorSize()
  31011. ** + The largest page size that can be written atomically.
  31012. */
  31013. if( rc==SQLITE_OK && !readOnly ){
  31014. setSectorSize(pPager);
  31015. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  31016. if( szPageDflt<pPager->sectorSize ){
  31017. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  31018. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  31019. }else{
  31020. szPageDflt = (u32)pPager->sectorSize;
  31021. }
  31022. }
  31023. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31024. {
  31025. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  31026. int ii;
  31027. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  31028. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  31029. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  31030. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  31031. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  31032. szPageDflt = ii;
  31033. }
  31034. }
  31035. }
  31036. #endif
  31037. }
  31038. }else{
  31039. /* If a temporary file is requested, it is not opened immediately.
  31040. ** In this case we accept the default page size and delay actually
  31041. ** opening the file until the first call to OsWrite().
  31042. **
  31043. ** This branch is also run for an in-memory database. An in-memory
  31044. ** database is the same as a temp-file that is never written out to
  31045. ** disk and uses an in-memory rollback journal.
  31046. */
  31047. tempFile = 1;
  31048. pPager->eState = PAGER_READER;
  31049. pPager->eLock = EXCLUSIVE_LOCK;
  31050. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  31051. }
  31052. /* The following call to PagerSetPagesize() serves to set the value of
  31053. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  31054. */
  31055. if( rc==SQLITE_OK ){
  31056. assert( pPager->memDb==0 );
  31057. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  31058. testcase( rc!=SQLITE_OK );
  31059. }
  31060. /* If an error occurred in either of the blocks above, free the
  31061. ** Pager structure and close the file.
  31062. */
  31063. if( rc!=SQLITE_OK ){
  31064. assert( !pPager->pTmpSpace );
  31065. sqlite3OsClose(pPager->fd);
  31066. sqlite3_free(pPager);
  31067. return rc;
  31068. }
  31069. /* Initialize the PCache object. */
  31070. assert( nExtra<1000 );
  31071. nExtra = ROUND8(nExtra);
  31072. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  31073. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  31074. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  31075. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  31076. pPager->useJournal = (u8)useJournal;
  31077. /* pPager->stmtOpen = 0; */
  31078. /* pPager->stmtInUse = 0; */
  31079. /* pPager->nRef = 0; */
  31080. /* pPager->stmtSize = 0; */
  31081. /* pPager->stmtJSize = 0; */
  31082. /* pPager->nPage = 0; */
  31083. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  31084. /* pPager->state = PAGER_UNLOCK; */
  31085. #if 0
  31086. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  31087. #endif
  31088. /* pPager->errMask = 0; */
  31089. pPager->tempFile = (u8)tempFile;
  31090. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  31091. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  31092. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  31093. pPager->exclusiveMode = (u8)tempFile;
  31094. pPager->changeCountDone = pPager->tempFile;
  31095. pPager->memDb = (u8)memDb;
  31096. pPager->readOnly = (u8)readOnly;
  31097. assert( useJournal || pPager->tempFile );
  31098. pPager->noSync = pPager->tempFile;
  31099. if( pPager->noSync ){
  31100. assert( pPager->fullSync==0 );
  31101. assert( pPager->syncFlags==0 );
  31102. assert( pPager->walSyncFlags==0 );
  31103. assert( pPager->ckptSyncFlags==0 );
  31104. }else{
  31105. pPager->fullSync = 1;
  31106. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  31107. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  31108. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  31109. }
  31110. /* pPager->pFirst = 0; */
  31111. /* pPager->pFirstSynced = 0; */
  31112. /* pPager->pLast = 0; */
  31113. pPager->nExtra = (u16)nExtra;
  31114. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  31115. assert( isOpen(pPager->fd) || tempFile );
  31116. setSectorSize(pPager);
  31117. if( !useJournal ){
  31118. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  31119. }else if( memDb ){
  31120. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  31121. }
  31122. /* pPager->xBusyHandler = 0; */
  31123. /* pPager->pBusyHandlerArg = 0; */
  31124. pPager->xReiniter = xReinit;
  31125. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  31126. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  31127. *ppPager = pPager;
  31128. return SQLITE_OK;
  31129. }
  31130. /*
  31131. ** This function is called after transitioning from PAGER_UNLOCK to
  31132. ** PAGER_SHARED state. It tests if there is a hot journal present in
  31133. ** the file-system for the given pager. A hot journal is one that
  31134. ** needs to be played back. According to this function, a hot-journal
  31135. ** file exists if the following criteria are met:
  31136. **
  31137. ** * The journal file exists in the file system, and
  31138. ** * No process holds a RESERVED or greater lock on the database file, and
  31139. ** * The database file itself is greater than 0 bytes in size, and
  31140. ** * The first byte of the journal file exists and is not 0x00.
  31141. **
  31142. ** If the current size of the database file is 0 but a journal file
  31143. ** exists, that is probably an old journal left over from a prior
  31144. ** database with the same name. In this case the journal file is
  31145. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  31146. ** is returned.
  31147. **
  31148. ** This routine does not check if there is a master journal filename
  31149. ** at the end of the file. If there is, and that master journal file
  31150. ** does not exist, then the journal file is not really hot. In this
  31151. ** case this routine will return a false-positive. The pager_playback()
  31152. ** routine will discover that the journal file is not really hot and
  31153. ** will not roll it back.
  31154. **
  31155. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  31156. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  31157. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  31158. ** to determine whether or not a hot-journal file exists, the IO error
  31159. ** code is returned and the value of *pExists is undefined.
  31160. */
  31161. static int hasHotJournal(Pager *pPager, int *pExists){
  31162. sqlite3_vfs * const pVfs = pPager->pVfs;
  31163. int rc = SQLITE_OK; /* Return code */
  31164. int exists = 1; /* True if a journal file is present */
  31165. int jrnlOpen = !!isOpen(pPager->jfd);
  31166. assert( pPager->useJournal );
  31167. assert( isOpen(pPager->fd) );
  31168. assert( pPager->eState==PAGER_OPEN );
  31169. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  31170. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  31171. ));
  31172. *pExists = 0;
  31173. if( !jrnlOpen ){
  31174. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  31175. }
  31176. if( rc==SQLITE_OK && exists ){
  31177. int locked = 0; /* True if some process holds a RESERVED lock */
  31178. /* Race condition here: Another process might have been holding the
  31179. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  31180. ** call above, but then delete the journal and drop the lock before
  31181. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  31182. ** is the case, this routine might think there is a hot journal when
  31183. ** in fact there is none. This results in a false-positive which will
  31184. ** be dealt with by the playback routine. Ticket #3883.
  31185. */
  31186. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  31187. if( rc==SQLITE_OK && !locked ){
  31188. Pgno nPage; /* Number of pages in database file */
  31189. /* Check the size of the database file. If it consists of 0 pages,
  31190. ** then delete the journal file. See the header comment above for
  31191. ** the reasoning here. Delete the obsolete journal file under
  31192. ** a RESERVED lock to avoid race conditions and to avoid violating
  31193. ** [H33020].
  31194. */
  31195. rc = pagerPagecount(pPager, &nPage);
  31196. if( rc==SQLITE_OK ){
  31197. if( nPage==0 ){
  31198. sqlite3BeginBenignMalloc();
  31199. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  31200. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  31201. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  31202. }
  31203. sqlite3EndBenignMalloc();
  31204. }else{
  31205. /* The journal file exists and no other connection has a reserved
  31206. ** or greater lock on the database file. Now check that there is
  31207. ** at least one non-zero bytes at the start of the journal file.
  31208. ** If there is, then we consider this journal to be hot. If not,
  31209. ** it can be ignored.
  31210. */
  31211. if( !jrnlOpen ){
  31212. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  31213. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  31214. }
  31215. if( rc==SQLITE_OK ){
  31216. u8 first = 0;
  31217. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  31218. if( rc==SQLITE_IOERR_SHORT_READ ){
  31219. rc = SQLITE_OK;
  31220. }
  31221. if( !jrnlOpen ){
  31222. sqlite3OsClose(pPager->jfd);
  31223. }
  31224. *pExists = (first!=0);
  31225. }else if( rc==SQLITE_CANTOPEN ){
  31226. /* If we cannot open the rollback journal file in order to see if
  31227. ** its has a zero header, that might be due to an I/O error, or
  31228. ** it might be due to the race condition described above and in
  31229. ** ticket #3883. Either way, assume that the journal is hot.
  31230. ** This might be a false positive. But if it is, then the
  31231. ** automatic journal playback and recovery mechanism will deal
  31232. ** with it under an EXCLUSIVE lock where we do not need to
  31233. ** worry so much with race conditions.
  31234. */
  31235. *pExists = 1;
  31236. rc = SQLITE_OK;
  31237. }
  31238. }
  31239. }
  31240. }
  31241. }
  31242. return rc;
  31243. }
  31244. /*
  31245. ** This function is called to obtain a shared lock on the database file.
  31246. ** It is illegal to call sqlite3PagerAcquire() until after this function
  31247. ** has been successfully called. If a shared-lock is already held when
  31248. ** this function is called, it is a no-op.
  31249. **
  31250. ** The following operations are also performed by this function.
  31251. **
  31252. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  31253. ** on the database file), then an attempt is made to obtain a
  31254. ** SHARED lock on the database file. Immediately after obtaining
  31255. ** the SHARED lock, the file-system is checked for a hot-journal,
  31256. ** which is played back if present. Following any hot-journal
  31257. ** rollback, the contents of the cache are validated by checking
  31258. ** the 'change-counter' field of the database file header and
  31259. ** discarded if they are found to be invalid.
  31260. **
  31261. ** 2) If the pager is running in exclusive-mode, and there are currently
  31262. ** no outstanding references to any pages, and is in the error state,
  31263. ** then an attempt is made to clear the error state by discarding
  31264. ** the contents of the page cache and rolling back any open journal
  31265. ** file.
  31266. **
  31267. ** If everything is successful, SQLITE_OK is returned. If an IO error
  31268. ** occurs while locking the database, checking for a hot-journal file or
  31269. ** rolling back a journal file, the IO error code is returned.
  31270. */
  31271. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  31272. int rc = SQLITE_OK; /* Return code */
  31273. /* This routine is only called from b-tree and only when there are no
  31274. ** outstanding pages. This implies that the pager state should either
  31275. ** be OPEN or READER. READER is only possible if the pager is or was in
  31276. ** exclusive access mode.
  31277. */
  31278. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  31279. assert( assert_pager_state(pPager) );
  31280. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  31281. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  31282. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  31283. int bHotJournal = 1; /* True if there exists a hot journal-file */
  31284. assert( !MEMDB );
  31285. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  31286. if( rc!=SQLITE_OK ){
  31287. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  31288. goto failed;
  31289. }
  31290. /* If a journal file exists, and there is no RESERVED lock on the
  31291. ** database file, then it either needs to be played back or deleted.
  31292. */
  31293. if( pPager->eLock<=SHARED_LOCK ){
  31294. rc = hasHotJournal(pPager, &bHotJournal);
  31295. }
  31296. if( rc!=SQLITE_OK ){
  31297. goto failed;
  31298. }
  31299. if( bHotJournal ){
  31300. if( pPager->readOnly ){
  31301. rc = SQLITE_READONLY_ROLLBACK;
  31302. goto failed;
  31303. }
  31304. /* Get an EXCLUSIVE lock on the database file. At this point it is
  31305. ** important that a RESERVED lock is not obtained on the way to the
  31306. ** EXCLUSIVE lock. If it were, another process might open the
  31307. ** database file, detect the RESERVED lock, and conclude that the
  31308. ** database is safe to read while this process is still rolling the
  31309. ** hot-journal back.
  31310. **
  31311. ** Because the intermediate RESERVED lock is not requested, any
  31312. ** other process attempting to access the database file will get to
  31313. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  31314. ** on the database file.
  31315. **
  31316. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  31317. ** downgraded to SHARED_LOCK before this function returns.
  31318. */
  31319. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  31320. if( rc!=SQLITE_OK ){
  31321. goto failed;
  31322. }
  31323. /* If it is not already open and the file exists on disk, open the
  31324. ** journal for read/write access. Write access is required because
  31325. ** in exclusive-access mode the file descriptor will be kept open
  31326. ** and possibly used for a transaction later on. Also, write-access
  31327. ** is usually required to finalize the journal in journal_mode=persist
  31328. ** mode (and also for journal_mode=truncate on some systems).
  31329. **
  31330. ** If the journal does not exist, it usually means that some
  31331. ** other connection managed to get in and roll it back before
  31332. ** this connection obtained the exclusive lock above. Or, it
  31333. ** may mean that the pager was in the error-state when this
  31334. ** function was called and the journal file does not exist.
  31335. */
  31336. if( !isOpen(pPager->jfd) ){
  31337. sqlite3_vfs * const pVfs = pPager->pVfs;
  31338. int bExists; /* True if journal file exists */
  31339. rc = sqlite3OsAccess(
  31340. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  31341. if( rc==SQLITE_OK && bExists ){
  31342. int fout = 0;
  31343. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  31344. assert( !pPager->tempFile );
  31345. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  31346. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31347. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  31348. rc = SQLITE_CANTOPEN_BKPT;
  31349. sqlite3OsClose(pPager->jfd);
  31350. }
  31351. }
  31352. }
  31353. /* Playback and delete the journal. Drop the database write
  31354. ** lock and reacquire the read lock. Purge the cache before
  31355. ** playing back the hot-journal so that we don't end up with
  31356. ** an inconsistent cache. Sync the hot journal before playing
  31357. ** it back since the process that crashed and left the hot journal
  31358. ** probably did not sync it and we are required to always sync
  31359. ** the journal before playing it back.
  31360. */
  31361. if( isOpen(pPager->jfd) ){
  31362. assert( rc==SQLITE_OK );
  31363. rc = pagerSyncHotJournal(pPager);
  31364. if( rc==SQLITE_OK ){
  31365. rc = pager_playback(pPager, 1);
  31366. pPager->eState = PAGER_OPEN;
  31367. }
  31368. }else if( !pPager->exclusiveMode ){
  31369. pagerUnlockDb(pPager, SHARED_LOCK);
  31370. }
  31371. if( rc!=SQLITE_OK ){
  31372. /* This branch is taken if an error occurs while trying to open
  31373. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  31374. ** pager_unlock() routine will be called before returning to unlock
  31375. ** the file. If the unlock attempt fails, then Pager.eLock must be
  31376. ** set to UNKNOWN_LOCK (see the comment above the #define for
  31377. ** UNKNOWN_LOCK above for an explanation).
  31378. **
  31379. ** In order to get pager_unlock() to do this, set Pager.eState to
  31380. ** PAGER_ERROR now. This is not actually counted as a transition
  31381. ** to ERROR state in the state diagram at the top of this file,
  31382. ** since we know that the same call to pager_unlock() will very
  31383. ** shortly transition the pager object to the OPEN state. Calling
  31384. ** assert_pager_state() would fail now, as it should not be possible
  31385. ** to be in ERROR state when there are zero outstanding page
  31386. ** references.
  31387. */
  31388. pager_error(pPager, rc);
  31389. goto failed;
  31390. }
  31391. assert( pPager->eState==PAGER_OPEN );
  31392. assert( (pPager->eLock==SHARED_LOCK)
  31393. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  31394. );
  31395. }
  31396. if( !pPager->tempFile && (
  31397. pPager->pBackup
  31398. || sqlite3PcachePagecount(pPager->pPCache)>0
  31399. || USEFETCH(pPager)
  31400. )){
  31401. /* The shared-lock has just been acquired on the database file
  31402. ** and there are already pages in the cache (from a previous
  31403. ** read or write transaction). Check to see if the database
  31404. ** has been modified. If the database has changed, flush the
  31405. ** cache.
  31406. **
  31407. ** Database changes is detected by looking at 15 bytes beginning
  31408. ** at offset 24 into the file. The first 4 of these 16 bytes are
  31409. ** a 32-bit counter that is incremented with each change. The
  31410. ** other bytes change randomly with each file change when
  31411. ** a codec is in use.
  31412. **
  31413. ** There is a vanishingly small chance that a change will not be
  31414. ** detected. The chance of an undetected change is so small that
  31415. ** it can be neglected.
  31416. */
  31417. Pgno nPage = 0;
  31418. char dbFileVers[sizeof(pPager->dbFileVers)];
  31419. rc = pagerPagecount(pPager, &nPage);
  31420. if( rc ) goto failed;
  31421. if( nPage>0 ){
  31422. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  31423. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  31424. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  31425. goto failed;
  31426. }
  31427. }else{
  31428. memset(dbFileVers, 0, sizeof(dbFileVers));
  31429. }
  31430. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  31431. pager_reset(pPager);
  31432. /* Unmap the database file. It is possible that external processes
  31433. ** may have truncated the database file and then extended it back
  31434. ** to its original size while this process was not holding a lock.
  31435. ** In this case there may exist a Pager.pMap mapping that appears
  31436. ** to be the right size but is not actually valid. Avoid this
  31437. ** possibility by unmapping the db here. */
  31438. if( USEFETCH(pPager) ){
  31439. sqlite3OsUnfetch(pPager->fd, 0, 0);
  31440. }
  31441. }
  31442. }
  31443. /* If there is a WAL file in the file-system, open this database in WAL
  31444. ** mode. Otherwise, the following function call is a no-op.
  31445. */
  31446. rc = pagerOpenWalIfPresent(pPager);
  31447. #ifndef SQLITE_OMIT_WAL
  31448. assert( pPager->pWal==0 || rc==SQLITE_OK );
  31449. #endif
  31450. }
  31451. if( pagerUseWal(pPager) ){
  31452. assert( rc==SQLITE_OK );
  31453. rc = pagerBeginReadTransaction(pPager);
  31454. }
  31455. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  31456. rc = pagerPagecount(pPager, &pPager->dbSize);
  31457. }
  31458. failed:
  31459. if( rc!=SQLITE_OK ){
  31460. assert( !MEMDB );
  31461. pager_unlock(pPager);
  31462. assert( pPager->eState==PAGER_OPEN );
  31463. }else{
  31464. pPager->eState = PAGER_READER;
  31465. }
  31466. return rc;
  31467. }
  31468. /*
  31469. ** If the reference count has reached zero, rollback any active
  31470. ** transaction and unlock the pager.
  31471. **
  31472. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  31473. ** the rollback journal, the unlock is not performed and there is
  31474. ** nothing to rollback, so this routine is a no-op.
  31475. */
  31476. static void pagerUnlockIfUnused(Pager *pPager){
  31477. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  31478. pagerUnlockAndRollback(pPager);
  31479. }
  31480. }
  31481. /*
  31482. ** Acquire a reference to page number pgno in pager pPager (a page
  31483. ** reference has type DbPage*). If the requested reference is
  31484. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  31485. **
  31486. ** If the requested page is already in the cache, it is returned.
  31487. ** Otherwise, a new page object is allocated and populated with data
  31488. ** read from the database file. In some cases, the pcache module may
  31489. ** choose not to allocate a new page object and may reuse an existing
  31490. ** object with no outstanding references.
  31491. **
  31492. ** The extra data appended to a page is always initialized to zeros the
  31493. ** first time a page is loaded into memory. If the page requested is
  31494. ** already in the cache when this function is called, then the extra
  31495. ** data is left as it was when the page object was last used.
  31496. **
  31497. ** If the database image is smaller than the requested page or if a
  31498. ** non-zero value is passed as the noContent parameter and the
  31499. ** requested page is not already stored in the cache, then no
  31500. ** actual disk read occurs. In this case the memory image of the
  31501. ** page is initialized to all zeros.
  31502. **
  31503. ** If noContent is true, it means that we do not care about the contents
  31504. ** of the page. This occurs in two scenarios:
  31505. **
  31506. ** a) When reading a free-list leaf page from the database, and
  31507. **
  31508. ** b) When a savepoint is being rolled back and we need to load
  31509. ** a new page into the cache to be filled with the data read
  31510. ** from the savepoint journal.
  31511. **
  31512. ** If noContent is true, then the data returned is zeroed instead of
  31513. ** being read from the database. Additionally, the bits corresponding
  31514. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  31515. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  31516. ** savepoints are set. This means if the page is made writable at any
  31517. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  31518. ** will not be journaled. This saves IO.
  31519. **
  31520. ** The acquisition might fail for several reasons. In all cases,
  31521. ** an appropriate error code is returned and *ppPage is set to NULL.
  31522. **
  31523. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  31524. ** to find a page in the in-memory cache first. If the page is not already
  31525. ** in memory, this routine goes to disk to read it in whereas Lookup()
  31526. ** just returns 0. This routine acquires a read-lock the first time it
  31527. ** has to go to disk, and could also playback an old journal if necessary.
  31528. ** Since Lookup() never goes to disk, it never has to deal with locks
  31529. ** or journal files.
  31530. */
  31531. SQLITE_PRIVATE int sqlite3PagerAcquire(
  31532. Pager *pPager, /* The pager open on the database file */
  31533. Pgno pgno, /* Page number to fetch */
  31534. DbPage **ppPage, /* Write a pointer to the page here */
  31535. int flags /* PAGER_GET_XXX flags */
  31536. ){
  31537. int rc = SQLITE_OK;
  31538. PgHdr *pPg = 0;
  31539. u32 iFrame = 0; /* Frame to read from WAL file */
  31540. const int noContent = (flags & PAGER_GET_NOCONTENT);
  31541. /* It is acceptable to use a read-only (mmap) page for any page except
  31542. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  31543. ** flag was specified by the caller. And so long as the db is not a
  31544. ** temporary or in-memory database. */
  31545. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  31546. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  31547. #ifdef SQLITE_HAS_CODEC
  31548. && pPager->xCodec==0
  31549. #endif
  31550. );
  31551. assert( pPager->eState>=PAGER_READER );
  31552. assert( assert_pager_state(pPager) );
  31553. assert( noContent==0 || bMmapOk==0 );
  31554. if( pgno==0 ){
  31555. return SQLITE_CORRUPT_BKPT;
  31556. }
  31557. /* If the pager is in the error state, return an error immediately.
  31558. ** Otherwise, request the page from the PCache layer. */
  31559. if( pPager->errCode!=SQLITE_OK ){
  31560. rc = pPager->errCode;
  31561. }else{
  31562. if( bMmapOk && pagerUseWal(pPager) ){
  31563. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  31564. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  31565. }
  31566. if( iFrame==0 && bMmapOk ){
  31567. void *pData = 0;
  31568. rc = sqlite3OsFetch(pPager->fd,
  31569. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  31570. );
  31571. if( rc==SQLITE_OK && pData ){
  31572. if( pPager->eState>PAGER_READER ){
  31573. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31574. }
  31575. if( pPg==0 ){
  31576. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  31577. }else{
  31578. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  31579. }
  31580. if( pPg ){
  31581. assert( rc==SQLITE_OK );
  31582. *ppPage = pPg;
  31583. return SQLITE_OK;
  31584. }
  31585. }
  31586. if( rc!=SQLITE_OK ){
  31587. goto pager_acquire_err;
  31588. }
  31589. }
  31590. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  31591. }
  31592. if( rc!=SQLITE_OK ){
  31593. /* Either the call to sqlite3PcacheFetch() returned an error or the
  31594. ** pager was already in the error-state when this function was called.
  31595. ** Set pPg to 0 and jump to the exception handler. */
  31596. pPg = 0;
  31597. goto pager_acquire_err;
  31598. }
  31599. assert( (*ppPage)->pgno==pgno );
  31600. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  31601. if( (*ppPage)->pPager && !noContent ){
  31602. /* In this case the pcache already contains an initialized copy of
  31603. ** the page. Return without further ado. */
  31604. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  31605. pPager->aStat[PAGER_STAT_HIT]++;
  31606. return SQLITE_OK;
  31607. }else{
  31608. /* The pager cache has created a new page. Its content needs to
  31609. ** be initialized. */
  31610. pPg = *ppPage;
  31611. pPg->pPager = pPager;
  31612. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  31613. ** number greater than this, or the unused locking-page, is requested. */
  31614. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  31615. rc = SQLITE_CORRUPT_BKPT;
  31616. goto pager_acquire_err;
  31617. }
  31618. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  31619. if( pgno>pPager->mxPgno ){
  31620. rc = SQLITE_FULL;
  31621. goto pager_acquire_err;
  31622. }
  31623. if( noContent ){
  31624. /* Failure to set the bits in the InJournal bit-vectors is benign.
  31625. ** It merely means that we might do some extra work to journal a
  31626. ** page that does not need to be journaled. Nevertheless, be sure
  31627. ** to test the case where a malloc error occurs while trying to set
  31628. ** a bit in a bit vector.
  31629. */
  31630. sqlite3BeginBenignMalloc();
  31631. if( pgno<=pPager->dbOrigSize ){
  31632. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  31633. testcase( rc==SQLITE_NOMEM );
  31634. }
  31635. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  31636. testcase( rc==SQLITE_NOMEM );
  31637. sqlite3EndBenignMalloc();
  31638. }
  31639. memset(pPg->pData, 0, pPager->pageSize);
  31640. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  31641. }else{
  31642. if( pagerUseWal(pPager) && bMmapOk==0 ){
  31643. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  31644. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  31645. }
  31646. assert( pPg->pPager==pPager );
  31647. pPager->aStat[PAGER_STAT_MISS]++;
  31648. rc = readDbPage(pPg, iFrame);
  31649. if( rc!=SQLITE_OK ){
  31650. goto pager_acquire_err;
  31651. }
  31652. }
  31653. pager_set_pagehash(pPg);
  31654. }
  31655. return SQLITE_OK;
  31656. pager_acquire_err:
  31657. assert( rc!=SQLITE_OK );
  31658. if( pPg ){
  31659. sqlite3PcacheDrop(pPg);
  31660. }
  31661. pagerUnlockIfUnused(pPager);
  31662. *ppPage = 0;
  31663. return rc;
  31664. }
  31665. /*
  31666. ** Acquire a page if it is already in the in-memory cache. Do
  31667. ** not read the page from disk. Return a pointer to the page,
  31668. ** or 0 if the page is not in cache.
  31669. **
  31670. ** See also sqlite3PagerGet(). The difference between this routine
  31671. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  31672. ** in the page if the page is not already in cache. This routine
  31673. ** returns NULL if the page is not in cache or if a disk I/O error
  31674. ** has ever happened.
  31675. */
  31676. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  31677. PgHdr *pPg = 0;
  31678. assert( pPager!=0 );
  31679. assert( pgno!=0 );
  31680. assert( pPager->pPCache!=0 );
  31681. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  31682. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  31683. return pPg;
  31684. }
  31685. /*
  31686. ** Release a page reference.
  31687. **
  31688. ** If the number of references to the page drop to zero, then the
  31689. ** page is added to the LRU list. When all references to all pages
  31690. ** are released, a rollback occurs and the lock on the database is
  31691. ** removed.
  31692. */
  31693. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  31694. if( pPg ){
  31695. Pager *pPager = pPg->pPager;
  31696. if( pPg->flags & PGHDR_MMAP ){
  31697. pagerReleaseMapPage(pPg);
  31698. }else{
  31699. sqlite3PcacheRelease(pPg);
  31700. }
  31701. pagerUnlockIfUnused(pPager);
  31702. }
  31703. }
  31704. /*
  31705. ** This function is called at the start of every write transaction.
  31706. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  31707. ** file when this routine is called.
  31708. **
  31709. ** Open the journal file for pager pPager and write a journal header
  31710. ** to the start of it. If there are active savepoints, open the sub-journal
  31711. ** as well. This function is only used when the journal file is being
  31712. ** opened to write a rollback log for a transaction. It is not used
  31713. ** when opening a hot journal file to roll it back.
  31714. **
  31715. ** If the journal file is already open (as it may be in exclusive mode),
  31716. ** then this function just writes a journal header to the start of the
  31717. ** already open file.
  31718. **
  31719. ** Whether or not the journal file is opened by this function, the
  31720. ** Pager.pInJournal bitvec structure is allocated.
  31721. **
  31722. ** Return SQLITE_OK if everything is successful. Otherwise, return
  31723. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  31724. ** an IO error code if opening or writing the journal file fails.
  31725. */
  31726. static int pager_open_journal(Pager *pPager){
  31727. int rc = SQLITE_OK; /* Return code */
  31728. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  31729. assert( pPager->eState==PAGER_WRITER_LOCKED );
  31730. assert( assert_pager_state(pPager) );
  31731. assert( pPager->pInJournal==0 );
  31732. /* If already in the error state, this function is a no-op. But on
  31733. ** the other hand, this routine is never called if we are already in
  31734. ** an error state. */
  31735. if( NEVER(pPager->errCode) ) return pPager->errCode;
  31736. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  31737. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  31738. if( pPager->pInJournal==0 ){
  31739. return SQLITE_NOMEM;
  31740. }
  31741. /* Open the journal file if it is not already open. */
  31742. if( !isOpen(pPager->jfd) ){
  31743. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  31744. sqlite3MemJournalOpen(pPager->jfd);
  31745. }else{
  31746. const int flags = /* VFS flags to open journal file */
  31747. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  31748. (pPager->tempFile ?
  31749. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  31750. (SQLITE_OPEN_MAIN_JOURNAL)
  31751. );
  31752. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  31753. rc = sqlite3JournalOpen(
  31754. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  31755. );
  31756. #else
  31757. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  31758. #endif
  31759. }
  31760. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  31761. }
  31762. /* Write the first journal header to the journal file and open
  31763. ** the sub-journal if necessary.
  31764. */
  31765. if( rc==SQLITE_OK ){
  31766. /* TODO: Check if all of these are really required. */
  31767. pPager->nRec = 0;
  31768. pPager->journalOff = 0;
  31769. pPager->setMaster = 0;
  31770. pPager->journalHdr = 0;
  31771. rc = writeJournalHdr(pPager);
  31772. }
  31773. }
  31774. if( rc!=SQLITE_OK ){
  31775. sqlite3BitvecDestroy(pPager->pInJournal);
  31776. pPager->pInJournal = 0;
  31777. }else{
  31778. assert( pPager->eState==PAGER_WRITER_LOCKED );
  31779. pPager->eState = PAGER_WRITER_CACHEMOD;
  31780. }
  31781. return rc;
  31782. }
  31783. /*
  31784. ** Begin a write-transaction on the specified pager object. If a
  31785. ** write-transaction has already been opened, this function is a no-op.
  31786. **
  31787. ** If the exFlag argument is false, then acquire at least a RESERVED
  31788. ** lock on the database file. If exFlag is true, then acquire at least
  31789. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  31790. ** functions need be called.
  31791. **
  31792. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  31793. ** within this transaction will be opened as an in-memory file. This
  31794. ** has no effect if the sub-journal is already opened (as it may be when
  31795. ** running in exclusive mode) or if the transaction does not require a
  31796. ** sub-journal. If the subjInMemory argument is zero, then any required
  31797. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  31798. ** or using a temporary file otherwise.
  31799. */
  31800. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  31801. int rc = SQLITE_OK;
  31802. if( pPager->errCode ) return pPager->errCode;
  31803. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  31804. pPager->subjInMemory = (u8)subjInMemory;
  31805. if( ALWAYS(pPager->eState==PAGER_READER) ){
  31806. assert( pPager->pInJournal==0 );
  31807. if( pagerUseWal(pPager) ){
  31808. /* If the pager is configured to use locking_mode=exclusive, and an
  31809. ** exclusive lock on the database is not already held, obtain it now.
  31810. */
  31811. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  31812. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  31813. if( rc!=SQLITE_OK ){
  31814. return rc;
  31815. }
  31816. sqlite3WalExclusiveMode(pPager->pWal, 1);
  31817. }
  31818. /* Grab the write lock on the log file. If successful, upgrade to
  31819. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  31820. ** The busy-handler is not invoked if another connection already
  31821. ** holds the write-lock. If possible, the upper layer will call it.
  31822. */
  31823. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  31824. }else{
  31825. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  31826. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  31827. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  31828. ** lock, but not when obtaining the RESERVED lock.
  31829. */
  31830. rc = pagerLockDb(pPager, RESERVED_LOCK);
  31831. if( rc==SQLITE_OK && exFlag ){
  31832. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  31833. }
  31834. }
  31835. if( rc==SQLITE_OK ){
  31836. /* Change to WRITER_LOCKED state.
  31837. **
  31838. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  31839. ** when it has an open transaction, but never to DBMOD or FINISHED.
  31840. ** This is because in those states the code to roll back savepoint
  31841. ** transactions may copy data from the sub-journal into the database
  31842. ** file as well as into the page cache. Which would be incorrect in
  31843. ** WAL mode.
  31844. */
  31845. pPager->eState = PAGER_WRITER_LOCKED;
  31846. pPager->dbHintSize = pPager->dbSize;
  31847. pPager->dbFileSize = pPager->dbSize;
  31848. pPager->dbOrigSize = pPager->dbSize;
  31849. pPager->journalOff = 0;
  31850. }
  31851. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  31852. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  31853. assert( assert_pager_state(pPager) );
  31854. }
  31855. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  31856. return rc;
  31857. }
  31858. /*
  31859. ** Mark a single data page as writeable. The page is written into the
  31860. ** main journal or sub-journal as required. If the page is written into
  31861. ** one of the journals, the corresponding bit is set in the
  31862. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  31863. ** of any open savepoints as appropriate.
  31864. */
  31865. static int pager_write(PgHdr *pPg){
  31866. void *pData = pPg->pData;
  31867. Pager *pPager = pPg->pPager;
  31868. int rc = SQLITE_OK;
  31869. /* This routine is not called unless a write-transaction has already
  31870. ** been started. The journal file may or may not be open at this point.
  31871. ** It is never called in the ERROR state.
  31872. */
  31873. assert( pPager->eState==PAGER_WRITER_LOCKED
  31874. || pPager->eState==PAGER_WRITER_CACHEMOD
  31875. || pPager->eState==PAGER_WRITER_DBMOD
  31876. );
  31877. assert( assert_pager_state(pPager) );
  31878. /* If an error has been previously detected, report the same error
  31879. ** again. This should not happen, but the check provides robustness. */
  31880. if( NEVER(pPager->errCode) ) return pPager->errCode;
  31881. /* Higher-level routines never call this function if database is not
  31882. ** writable. But check anyway, just for robustness. */
  31883. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  31884. CHECK_PAGE(pPg);
  31885. /* The journal file needs to be opened. Higher level routines have already
  31886. ** obtained the necessary locks to begin the write-transaction, but the
  31887. ** rollback journal might not yet be open. Open it now if this is the case.
  31888. **
  31889. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  31890. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  31891. ** an error might occur and the pager would end up in WRITER_LOCKED state
  31892. ** with pages marked as dirty in the cache.
  31893. */
  31894. if( pPager->eState==PAGER_WRITER_LOCKED ){
  31895. rc = pager_open_journal(pPager);
  31896. if( rc!=SQLITE_OK ) return rc;
  31897. }
  31898. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  31899. assert( assert_pager_state(pPager) );
  31900. /* Mark the page as dirty. If the page has already been written
  31901. ** to the journal then we can return right away.
  31902. */
  31903. sqlite3PcacheMakeDirty(pPg);
  31904. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  31905. assert( !pagerUseWal(pPager) );
  31906. }else{
  31907. /* The transaction journal now exists and we have a RESERVED or an
  31908. ** EXCLUSIVE lock on the main database file. Write the current page to
  31909. ** the transaction journal if it is not there already.
  31910. */
  31911. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  31912. assert( pagerUseWal(pPager)==0 );
  31913. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  31914. u32 cksum;
  31915. char *pData2;
  31916. i64 iOff = pPager->journalOff;
  31917. /* We should never write to the journal file the page that
  31918. ** contains the database locks. The following assert verifies
  31919. ** that we do not. */
  31920. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  31921. assert( pPager->journalHdr<=pPager->journalOff );
  31922. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  31923. cksum = pager_cksum(pPager, (u8*)pData2);
  31924. /* Even if an IO or diskfull error occurs while journalling the
  31925. ** page in the block above, set the need-sync flag for the page.
  31926. ** Otherwise, when the transaction is rolled back, the logic in
  31927. ** playback_one_page() will think that the page needs to be restored
  31928. ** in the database file. And if an IO error occurs while doing so,
  31929. ** then corruption may follow.
  31930. */
  31931. pPg->flags |= PGHDR_NEED_SYNC;
  31932. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  31933. if( rc!=SQLITE_OK ) return rc;
  31934. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  31935. if( rc!=SQLITE_OK ) return rc;
  31936. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  31937. if( rc!=SQLITE_OK ) return rc;
  31938. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  31939. pPager->journalOff, pPager->pageSize));
  31940. PAGER_INCR(sqlite3_pager_writej_count);
  31941. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  31942. PAGERID(pPager), pPg->pgno,
  31943. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  31944. pPager->journalOff += 8 + pPager->pageSize;
  31945. pPager->nRec++;
  31946. assert( pPager->pInJournal!=0 );
  31947. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  31948. testcase( rc==SQLITE_NOMEM );
  31949. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  31950. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  31951. if( rc!=SQLITE_OK ){
  31952. assert( rc==SQLITE_NOMEM );
  31953. return rc;
  31954. }
  31955. }else{
  31956. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  31957. pPg->flags |= PGHDR_NEED_SYNC;
  31958. }
  31959. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  31960. PAGERID(pPager), pPg->pgno,
  31961. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  31962. }
  31963. }
  31964. /* If the statement journal is open and the page is not in it,
  31965. ** then write the current page to the statement journal. Note that
  31966. ** the statement journal format differs from the standard journal format
  31967. ** in that it omits the checksums and the header.
  31968. */
  31969. if( subjRequiresPage(pPg) ){
  31970. rc = subjournalPage(pPg);
  31971. }
  31972. }
  31973. /* Update the database size and return.
  31974. */
  31975. if( pPager->dbSize<pPg->pgno ){
  31976. pPager->dbSize = pPg->pgno;
  31977. }
  31978. return rc;
  31979. }
  31980. /*
  31981. ** Mark a data page as writeable. This routine must be called before
  31982. ** making changes to a page. The caller must check the return value
  31983. ** of this function and be careful not to change any page data unless
  31984. ** this routine returns SQLITE_OK.
  31985. **
  31986. ** The difference between this function and pager_write() is that this
  31987. ** function also deals with the special case where 2 or more pages
  31988. ** fit on a single disk sector. In this case all co-resident pages
  31989. ** must have been written to the journal file before returning.
  31990. **
  31991. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  31992. ** as appropriate. Otherwise, SQLITE_OK.
  31993. */
  31994. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  31995. int rc = SQLITE_OK;
  31996. PgHdr *pPg = pDbPage;
  31997. Pager *pPager = pPg->pPager;
  31998. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  31999. assert( (pPg->flags & PGHDR_MMAP)==0 );
  32000. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  32001. assert( pPager->eState!=PAGER_ERROR );
  32002. assert( assert_pager_state(pPager) );
  32003. if( nPagePerSector>1 ){
  32004. Pgno nPageCount; /* Total number of pages in database file */
  32005. Pgno pg1; /* First page of the sector pPg is located on. */
  32006. int nPage = 0; /* Number of pages starting at pg1 to journal */
  32007. int ii; /* Loop counter */
  32008. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  32009. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  32010. ** a journal header to be written between the pages journaled by
  32011. ** this function.
  32012. */
  32013. assert( !MEMDB );
  32014. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  32015. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  32016. /* This trick assumes that both the page-size and sector-size are
  32017. ** an integer power of 2. It sets variable pg1 to the identifier
  32018. ** of the first page of the sector pPg is located on.
  32019. */
  32020. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  32021. nPageCount = pPager->dbSize;
  32022. if( pPg->pgno>nPageCount ){
  32023. nPage = (pPg->pgno - pg1)+1;
  32024. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  32025. nPage = nPageCount+1-pg1;
  32026. }else{
  32027. nPage = nPagePerSector;
  32028. }
  32029. assert(nPage>0);
  32030. assert(pg1<=pPg->pgno);
  32031. assert((pg1+nPage)>pPg->pgno);
  32032. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  32033. Pgno pg = pg1+ii;
  32034. PgHdr *pPage;
  32035. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  32036. if( pg!=PAGER_MJ_PGNO(pPager) ){
  32037. rc = sqlite3PagerGet(pPager, pg, &pPage);
  32038. if( rc==SQLITE_OK ){
  32039. rc = pager_write(pPage);
  32040. if( pPage->flags&PGHDR_NEED_SYNC ){
  32041. needSync = 1;
  32042. }
  32043. sqlite3PagerUnref(pPage);
  32044. }
  32045. }
  32046. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  32047. if( pPage->flags&PGHDR_NEED_SYNC ){
  32048. needSync = 1;
  32049. }
  32050. sqlite3PagerUnref(pPage);
  32051. }
  32052. }
  32053. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  32054. ** starting at pg1, then it needs to be set for all of them. Because
  32055. ** writing to any of these nPage pages may damage the others, the
  32056. ** journal file must contain sync()ed copies of all of them
  32057. ** before any of them can be written out to the database file.
  32058. */
  32059. if( rc==SQLITE_OK && needSync ){
  32060. assert( !MEMDB );
  32061. for(ii=0; ii<nPage; ii++){
  32062. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  32063. if( pPage ){
  32064. pPage->flags |= PGHDR_NEED_SYNC;
  32065. sqlite3PagerUnref(pPage);
  32066. }
  32067. }
  32068. }
  32069. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  32070. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  32071. }else{
  32072. rc = pager_write(pDbPage);
  32073. }
  32074. return rc;
  32075. }
  32076. /*
  32077. ** Return TRUE if the page given in the argument was previously passed
  32078. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  32079. ** to change the content of the page.
  32080. */
  32081. #ifndef NDEBUG
  32082. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  32083. return pPg->flags&PGHDR_DIRTY;
  32084. }
  32085. #endif
  32086. /*
  32087. ** A call to this routine tells the pager that it is not necessary to
  32088. ** write the information on page pPg back to the disk, even though
  32089. ** that page might be marked as dirty. This happens, for example, when
  32090. ** the page has been added as a leaf of the freelist and so its
  32091. ** content no longer matters.
  32092. **
  32093. ** The overlying software layer calls this routine when all of the data
  32094. ** on the given page is unused. The pager marks the page as clean so
  32095. ** that it does not get written to disk.
  32096. **
  32097. ** Tests show that this optimization can quadruple the speed of large
  32098. ** DELETE operations.
  32099. */
  32100. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  32101. Pager *pPager = pPg->pPager;
  32102. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  32103. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  32104. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  32105. pPg->flags |= PGHDR_DONT_WRITE;
  32106. pager_set_pagehash(pPg);
  32107. }
  32108. }
  32109. /*
  32110. ** This routine is called to increment the value of the database file
  32111. ** change-counter, stored as a 4-byte big-endian integer starting at
  32112. ** byte offset 24 of the pager file. The secondary change counter at
  32113. ** 92 is also updated, as is the SQLite version number at offset 96.
  32114. **
  32115. ** But this only happens if the pPager->changeCountDone flag is false.
  32116. ** To avoid excess churning of page 1, the update only happens once.
  32117. ** See also the pager_write_changecounter() routine that does an
  32118. ** unconditional update of the change counters.
  32119. **
  32120. ** If the isDirectMode flag is zero, then this is done by calling
  32121. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  32122. ** page data. In this case the file will be updated when the current
  32123. ** transaction is committed.
  32124. **
  32125. ** The isDirectMode flag may only be non-zero if the library was compiled
  32126. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  32127. ** if isDirect is non-zero, then the database file is updated directly
  32128. ** by writing an updated version of page 1 using a call to the
  32129. ** sqlite3OsWrite() function.
  32130. */
  32131. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  32132. int rc = SQLITE_OK;
  32133. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32134. || pPager->eState==PAGER_WRITER_DBMOD
  32135. );
  32136. assert( assert_pager_state(pPager) );
  32137. /* Declare and initialize constant integer 'isDirect'. If the
  32138. ** atomic-write optimization is enabled in this build, then isDirect
  32139. ** is initialized to the value passed as the isDirectMode parameter
  32140. ** to this function. Otherwise, it is always set to zero.
  32141. **
  32142. ** The idea is that if the atomic-write optimization is not
  32143. ** enabled at compile time, the compiler can omit the tests of
  32144. ** 'isDirect' below, as well as the block enclosed in the
  32145. ** "if( isDirect )" condition.
  32146. */
  32147. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  32148. # define DIRECT_MODE 0
  32149. assert( isDirectMode==0 );
  32150. UNUSED_PARAMETER(isDirectMode);
  32151. #else
  32152. # define DIRECT_MODE isDirectMode
  32153. #endif
  32154. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  32155. PgHdr *pPgHdr; /* Reference to page 1 */
  32156. assert( !pPager->tempFile && isOpen(pPager->fd) );
  32157. /* Open page 1 of the file for writing. */
  32158. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  32159. assert( pPgHdr==0 || rc==SQLITE_OK );
  32160. /* If page one was fetched successfully, and this function is not
  32161. ** operating in direct-mode, make page 1 writable. When not in
  32162. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  32163. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  32164. */
  32165. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  32166. rc = sqlite3PagerWrite(pPgHdr);
  32167. }
  32168. if( rc==SQLITE_OK ){
  32169. /* Actually do the update of the change counter */
  32170. pager_write_changecounter(pPgHdr);
  32171. /* If running in direct mode, write the contents of page 1 to the file. */
  32172. if( DIRECT_MODE ){
  32173. const void *zBuf;
  32174. assert( pPager->dbFileSize>0 );
  32175. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  32176. if( rc==SQLITE_OK ){
  32177. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  32178. pPager->aStat[PAGER_STAT_WRITE]++;
  32179. }
  32180. if( rc==SQLITE_OK ){
  32181. /* Update the pager's copy of the change-counter. Otherwise, the
  32182. ** next time a read transaction is opened the cache will be
  32183. ** flushed (as the change-counter values will not match). */
  32184. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  32185. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  32186. pPager->changeCountDone = 1;
  32187. }
  32188. }else{
  32189. pPager->changeCountDone = 1;
  32190. }
  32191. }
  32192. /* Release the page reference. */
  32193. sqlite3PagerUnref(pPgHdr);
  32194. }
  32195. return rc;
  32196. }
  32197. /*
  32198. ** Sync the database file to disk. This is a no-op for in-memory databases
  32199. ** or pages with the Pager.noSync flag set.
  32200. **
  32201. ** If successful, or if called on a pager for which it is a no-op, this
  32202. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  32203. */
  32204. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  32205. int rc = SQLITE_OK;
  32206. if( !pPager->noSync ){
  32207. assert( !MEMDB );
  32208. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  32209. }else if( isOpen(pPager->fd) ){
  32210. assert( !MEMDB );
  32211. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  32212. if( rc==SQLITE_NOTFOUND ){
  32213. rc = SQLITE_OK;
  32214. }
  32215. }
  32216. return rc;
  32217. }
  32218. /*
  32219. ** This function may only be called while a write-transaction is active in
  32220. ** rollback. If the connection is in WAL mode, this call is a no-op.
  32221. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  32222. ** the database file, an attempt is made to obtain one.
  32223. **
  32224. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  32225. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  32226. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  32227. ** returned.
  32228. */
  32229. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  32230. int rc = SQLITE_OK;
  32231. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32232. || pPager->eState==PAGER_WRITER_DBMOD
  32233. || pPager->eState==PAGER_WRITER_LOCKED
  32234. );
  32235. assert( assert_pager_state(pPager) );
  32236. if( 0==pagerUseWal(pPager) ){
  32237. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  32238. }
  32239. return rc;
  32240. }
  32241. /*
  32242. ** Sync the database file for the pager pPager. zMaster points to the name
  32243. ** of a master journal file that should be written into the individual
  32244. ** journal file. zMaster may be NULL, which is interpreted as no master
  32245. ** journal (a single database transaction).
  32246. **
  32247. ** This routine ensures that:
  32248. **
  32249. ** * The database file change-counter is updated,
  32250. ** * the journal is synced (unless the atomic-write optimization is used),
  32251. ** * all dirty pages are written to the database file,
  32252. ** * the database file is truncated (if required), and
  32253. ** * the database file synced.
  32254. **
  32255. ** The only thing that remains to commit the transaction is to finalize
  32256. ** (delete, truncate or zero the first part of) the journal file (or
  32257. ** delete the master journal file if specified).
  32258. **
  32259. ** Note that if zMaster==NULL, this does not overwrite a previous value
  32260. ** passed to an sqlite3PagerCommitPhaseOne() call.
  32261. **
  32262. ** If the final parameter - noSync - is true, then the database file itself
  32263. ** is not synced. The caller must call sqlite3PagerSync() directly to
  32264. ** sync the database file before calling CommitPhaseTwo() to delete the
  32265. ** journal file in this case.
  32266. */
  32267. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  32268. Pager *pPager, /* Pager object */
  32269. const char *zMaster, /* If not NULL, the master journal name */
  32270. int noSync /* True to omit the xSync on the db file */
  32271. ){
  32272. int rc = SQLITE_OK; /* Return code */
  32273. assert( pPager->eState==PAGER_WRITER_LOCKED
  32274. || pPager->eState==PAGER_WRITER_CACHEMOD
  32275. || pPager->eState==PAGER_WRITER_DBMOD
  32276. || pPager->eState==PAGER_ERROR
  32277. );
  32278. assert( assert_pager_state(pPager) );
  32279. /* If a prior error occurred, report that error again. */
  32280. if( NEVER(pPager->errCode) ) return pPager->errCode;
  32281. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  32282. pPager->zFilename, zMaster, pPager->dbSize));
  32283. /* If no database changes have been made, return early. */
  32284. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  32285. if( MEMDB ){
  32286. /* If this is an in-memory db, or no pages have been written to, or this
  32287. ** function has already been called, it is mostly a no-op. However, any
  32288. ** backup in progress needs to be restarted.
  32289. */
  32290. sqlite3BackupRestart(pPager->pBackup);
  32291. }else{
  32292. if( pagerUseWal(pPager) ){
  32293. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  32294. PgHdr *pPageOne = 0;
  32295. if( pList==0 ){
  32296. /* Must have at least one page for the WAL commit flag.
  32297. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  32298. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  32299. pList = pPageOne;
  32300. pList->pDirty = 0;
  32301. }
  32302. assert( rc==SQLITE_OK );
  32303. if( ALWAYS(pList) ){
  32304. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  32305. }
  32306. sqlite3PagerUnref(pPageOne);
  32307. if( rc==SQLITE_OK ){
  32308. sqlite3PcacheCleanAll(pPager->pPCache);
  32309. }
  32310. }else{
  32311. /* The following block updates the change-counter. Exactly how it
  32312. ** does this depends on whether or not the atomic-update optimization
  32313. ** was enabled at compile time, and if this transaction meets the
  32314. ** runtime criteria to use the operation:
  32315. **
  32316. ** * The file-system supports the atomic-write property for
  32317. ** blocks of size page-size, and
  32318. ** * This commit is not part of a multi-file transaction, and
  32319. ** * Exactly one page has been modified and store in the journal file.
  32320. **
  32321. ** If the optimization was not enabled at compile time, then the
  32322. ** pager_incr_changecounter() function is called to update the change
  32323. ** counter in 'indirect-mode'. If the optimization is compiled in but
  32324. ** is not applicable to this transaction, call sqlite3JournalCreate()
  32325. ** to make sure the journal file has actually been created, then call
  32326. ** pager_incr_changecounter() to update the change-counter in indirect
  32327. ** mode.
  32328. **
  32329. ** Otherwise, if the optimization is both enabled and applicable,
  32330. ** then call pager_incr_changecounter() to update the change-counter
  32331. ** in 'direct' mode. In this case the journal file will never be
  32332. ** created for this transaction.
  32333. */
  32334. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  32335. PgHdr *pPg;
  32336. assert( isOpen(pPager->jfd)
  32337. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  32338. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  32339. );
  32340. if( !zMaster && isOpen(pPager->jfd)
  32341. && pPager->journalOff==jrnlBufferSize(pPager)
  32342. && pPager->dbSize>=pPager->dbOrigSize
  32343. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  32344. ){
  32345. /* Update the db file change counter via the direct-write method. The
  32346. ** following call will modify the in-memory representation of page 1
  32347. ** to include the updated change counter and then write page 1
  32348. ** directly to the database file. Because of the atomic-write
  32349. ** property of the host file-system, this is safe.
  32350. */
  32351. rc = pager_incr_changecounter(pPager, 1);
  32352. }else{
  32353. rc = sqlite3JournalCreate(pPager->jfd);
  32354. if( rc==SQLITE_OK ){
  32355. rc = pager_incr_changecounter(pPager, 0);
  32356. }
  32357. }
  32358. #else
  32359. rc = pager_incr_changecounter(pPager, 0);
  32360. #endif
  32361. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32362. /* Write the master journal name into the journal file. If a master
  32363. ** journal file name has already been written to the journal file,
  32364. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  32365. */
  32366. rc = writeMasterJournal(pPager, zMaster);
  32367. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32368. /* Sync the journal file and write all dirty pages to the database.
  32369. ** If the atomic-update optimization is being used, this sync will not
  32370. ** create the journal file or perform any real IO.
  32371. **
  32372. ** Because the change-counter page was just modified, unless the
  32373. ** atomic-update optimization is used it is almost certain that the
  32374. ** journal requires a sync here. However, in locking_mode=exclusive
  32375. ** on a system under memory pressure it is just possible that this is
  32376. ** not the case. In this case it is likely enough that the redundant
  32377. ** xSync() call will be changed to a no-op by the OS anyhow.
  32378. */
  32379. rc = syncJournal(pPager, 0);
  32380. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32381. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  32382. if( rc!=SQLITE_OK ){
  32383. assert( rc!=SQLITE_IOERR_BLOCKED );
  32384. goto commit_phase_one_exit;
  32385. }
  32386. sqlite3PcacheCleanAll(pPager->pPCache);
  32387. /* If the file on disk is smaller than the database image, use
  32388. ** pager_truncate to grow the file here. This can happen if the database
  32389. ** image was extended as part of the current transaction and then the
  32390. ** last page in the db image moved to the free-list. In this case the
  32391. ** last page is never written out to disk, leaving the database file
  32392. ** undersized. Fix this now if it is the case. */
  32393. if( pPager->dbSize>pPager->dbFileSize ){
  32394. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  32395. assert( pPager->eState==PAGER_WRITER_DBMOD );
  32396. rc = pager_truncate(pPager, nNew);
  32397. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  32398. }
  32399. /* Finally, sync the database file. */
  32400. if( !noSync ){
  32401. rc = sqlite3PagerSync(pPager);
  32402. }
  32403. IOTRACE(("DBSYNC %p\n", pPager))
  32404. }
  32405. }
  32406. commit_phase_one_exit:
  32407. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  32408. pPager->eState = PAGER_WRITER_FINISHED;
  32409. }
  32410. return rc;
  32411. }
  32412. /*
  32413. ** When this function is called, the database file has been completely
  32414. ** updated to reflect the changes made by the current transaction and
  32415. ** synced to disk. The journal file still exists in the file-system
  32416. ** though, and if a failure occurs at this point it will eventually
  32417. ** be used as a hot-journal and the current transaction rolled back.
  32418. **
  32419. ** This function finalizes the journal file, either by deleting,
  32420. ** truncating or partially zeroing it, so that it cannot be used
  32421. ** for hot-journal rollback. Once this is done the transaction is
  32422. ** irrevocably committed.
  32423. **
  32424. ** If an error occurs, an IO error code is returned and the pager
  32425. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  32426. */
  32427. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  32428. int rc = SQLITE_OK; /* Return code */
  32429. /* This routine should not be called if a prior error has occurred.
  32430. ** But if (due to a coding error elsewhere in the system) it does get
  32431. ** called, just return the same error code without doing anything. */
  32432. if( NEVER(pPager->errCode) ) return pPager->errCode;
  32433. assert( pPager->eState==PAGER_WRITER_LOCKED
  32434. || pPager->eState==PAGER_WRITER_FINISHED
  32435. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  32436. );
  32437. assert( assert_pager_state(pPager) );
  32438. /* An optimization. If the database was not actually modified during
  32439. ** this transaction, the pager is running in exclusive-mode and is
  32440. ** using persistent journals, then this function is a no-op.
  32441. **
  32442. ** The start of the journal file currently contains a single journal
  32443. ** header with the nRec field set to 0. If such a journal is used as
  32444. ** a hot-journal during hot-journal rollback, 0 changes will be made
  32445. ** to the database file. So there is no need to zero the journal
  32446. ** header. Since the pager is in exclusive mode, there is no need
  32447. ** to drop any locks either.
  32448. */
  32449. if( pPager->eState==PAGER_WRITER_LOCKED
  32450. && pPager->exclusiveMode
  32451. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  32452. ){
  32453. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  32454. pPager->eState = PAGER_READER;
  32455. return SQLITE_OK;
  32456. }
  32457. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  32458. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  32459. return pager_error(pPager, rc);
  32460. }
  32461. /*
  32462. ** If a write transaction is open, then all changes made within the
  32463. ** transaction are reverted and the current write-transaction is closed.
  32464. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  32465. ** state if an error occurs.
  32466. **
  32467. ** If the pager is already in PAGER_ERROR state when this function is called,
  32468. ** it returns Pager.errCode immediately. No work is performed in this case.
  32469. **
  32470. ** Otherwise, in rollback mode, this function performs two functions:
  32471. **
  32472. ** 1) It rolls back the journal file, restoring all database file and
  32473. ** in-memory cache pages to the state they were in when the transaction
  32474. ** was opened, and
  32475. **
  32476. ** 2) It finalizes the journal file, so that it is not used for hot
  32477. ** rollback at any point in the future.
  32478. **
  32479. ** Finalization of the journal file (task 2) is only performed if the
  32480. ** rollback is successful.
  32481. **
  32482. ** In WAL mode, all cache-entries containing data modified within the
  32483. ** current transaction are either expelled from the cache or reverted to
  32484. ** their pre-transaction state by re-reading data from the database or
  32485. ** WAL files. The WAL transaction is then closed.
  32486. */
  32487. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  32488. int rc = SQLITE_OK; /* Return code */
  32489. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  32490. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  32491. ** the pager is already in the ERROR state, the rollback is not
  32492. ** attempted here. Instead, the error code is returned to the caller.
  32493. */
  32494. assert( assert_pager_state(pPager) );
  32495. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  32496. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  32497. if( pagerUseWal(pPager) ){
  32498. int rc2;
  32499. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  32500. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  32501. if( rc==SQLITE_OK ) rc = rc2;
  32502. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  32503. int eState = pPager->eState;
  32504. rc = pager_end_transaction(pPager, 0, 0);
  32505. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  32506. /* This can happen using journal_mode=off. Move the pager to the error
  32507. ** state to indicate that the contents of the cache may not be trusted.
  32508. ** Any active readers will get SQLITE_ABORT.
  32509. */
  32510. pPager->errCode = SQLITE_ABORT;
  32511. pPager->eState = PAGER_ERROR;
  32512. return rc;
  32513. }
  32514. }else{
  32515. rc = pager_playback(pPager, 0);
  32516. }
  32517. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  32518. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  32519. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  32520. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  32521. ** cache. So call pager_error() on the way out to make any error persistent.
  32522. */
  32523. return pager_error(pPager, rc);
  32524. }
  32525. /*
  32526. ** Return TRUE if the database file is opened read-only. Return FALSE
  32527. ** if the database is (in theory) writable.
  32528. */
  32529. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  32530. return pPager->readOnly;
  32531. }
  32532. /*
  32533. ** Return the number of references to the pager.
  32534. */
  32535. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  32536. return sqlite3PcacheRefCount(pPager->pPCache);
  32537. }
  32538. /*
  32539. ** Return the approximate number of bytes of memory currently
  32540. ** used by the pager and its associated cache.
  32541. */
  32542. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  32543. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  32544. + 5*sizeof(void*);
  32545. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  32546. + sqlite3MallocSize(pPager)
  32547. + pPager->pageSize;
  32548. }
  32549. /*
  32550. ** Return the number of references to the specified page.
  32551. */
  32552. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  32553. return sqlite3PcachePageRefcount(pPage);
  32554. }
  32555. #ifdef SQLITE_TEST
  32556. /*
  32557. ** This routine is used for testing and analysis only.
  32558. */
  32559. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  32560. static int a[11];
  32561. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  32562. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  32563. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  32564. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  32565. a[4] = pPager->eState;
  32566. a[5] = pPager->errCode;
  32567. a[6] = pPager->aStat[PAGER_STAT_HIT];
  32568. a[7] = pPager->aStat[PAGER_STAT_MISS];
  32569. a[8] = 0; /* Used to be pPager->nOvfl */
  32570. a[9] = pPager->nRead;
  32571. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  32572. return a;
  32573. }
  32574. #endif
  32575. /*
  32576. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  32577. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  32578. ** current cache hit or miss count, according to the value of eStat. If the
  32579. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  32580. ** returning.
  32581. */
  32582. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  32583. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  32584. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  32585. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  32586. );
  32587. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  32588. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  32589. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  32590. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  32591. if( reset ){
  32592. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  32593. }
  32594. }
  32595. /*
  32596. ** Return true if this is an in-memory pager.
  32597. */
  32598. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  32599. return MEMDB;
  32600. }
  32601. /*
  32602. ** Check that there are at least nSavepoint savepoints open. If there are
  32603. ** currently less than nSavepoints open, then open one or more savepoints
  32604. ** to make up the difference. If the number of savepoints is already
  32605. ** equal to nSavepoint, then this function is a no-op.
  32606. **
  32607. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  32608. ** occurs while opening the sub-journal file, then an IO error code is
  32609. ** returned. Otherwise, SQLITE_OK.
  32610. */
  32611. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  32612. int rc = SQLITE_OK; /* Return code */
  32613. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  32614. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  32615. assert( assert_pager_state(pPager) );
  32616. if( nSavepoint>nCurrent && pPager->useJournal ){
  32617. int ii; /* Iterator variable */
  32618. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  32619. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  32620. ** if the allocation fails. Otherwise, zero the new portion in case a
  32621. ** malloc failure occurs while populating it in the for(...) loop below.
  32622. */
  32623. aNew = (PagerSavepoint *)sqlite3Realloc(
  32624. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  32625. );
  32626. if( !aNew ){
  32627. return SQLITE_NOMEM;
  32628. }
  32629. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  32630. pPager->aSavepoint = aNew;
  32631. /* Populate the PagerSavepoint structures just allocated. */
  32632. for(ii=nCurrent; ii<nSavepoint; ii++){
  32633. aNew[ii].nOrig = pPager->dbSize;
  32634. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  32635. aNew[ii].iOffset = pPager->journalOff;
  32636. }else{
  32637. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  32638. }
  32639. aNew[ii].iSubRec = pPager->nSubRec;
  32640. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  32641. if( !aNew[ii].pInSavepoint ){
  32642. return SQLITE_NOMEM;
  32643. }
  32644. if( pagerUseWal(pPager) ){
  32645. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  32646. }
  32647. pPager->nSavepoint = ii+1;
  32648. }
  32649. assert( pPager->nSavepoint==nSavepoint );
  32650. assertTruncateConstraint(pPager);
  32651. }
  32652. return rc;
  32653. }
  32654. /*
  32655. ** This function is called to rollback or release (commit) a savepoint.
  32656. ** The savepoint to release or rollback need not be the most recently
  32657. ** created savepoint.
  32658. **
  32659. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  32660. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  32661. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  32662. ** that have occurred since the specified savepoint was created.
  32663. **
  32664. ** The savepoint to rollback or release is identified by parameter
  32665. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  32666. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  32667. ** on the most recently created savepoint. If iSavepoint is greater than
  32668. ** (Pager.nSavepoint-1), then this function is a no-op.
  32669. **
  32670. ** If a negative value is passed to this function, then the current
  32671. ** transaction is rolled back. This is different to calling
  32672. ** sqlite3PagerRollback() because this function does not terminate
  32673. ** the transaction or unlock the database, it just restores the
  32674. ** contents of the database to its original state.
  32675. **
  32676. ** In any case, all savepoints with an index greater than iSavepoint
  32677. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  32678. ** then savepoint iSavepoint is also destroyed.
  32679. **
  32680. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  32681. ** or an IO error code if an IO error occurs while rolling back a
  32682. ** savepoint. If no errors occur, SQLITE_OK is returned.
  32683. */
  32684. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  32685. int rc = pPager->errCode; /* Return code */
  32686. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  32687. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  32688. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  32689. int ii; /* Iterator variable */
  32690. int nNew; /* Number of remaining savepoints after this op. */
  32691. /* Figure out how many savepoints will still be active after this
  32692. ** operation. Store this value in nNew. Then free resources associated
  32693. ** with any savepoints that are destroyed by this operation.
  32694. */
  32695. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  32696. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  32697. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  32698. }
  32699. pPager->nSavepoint = nNew;
  32700. /* If this is a release of the outermost savepoint, truncate
  32701. ** the sub-journal to zero bytes in size. */
  32702. if( op==SAVEPOINT_RELEASE ){
  32703. if( nNew==0 && isOpen(pPager->sjfd) ){
  32704. /* Only truncate if it is an in-memory sub-journal. */
  32705. if( sqlite3IsMemJournal(pPager->sjfd) ){
  32706. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  32707. assert( rc==SQLITE_OK );
  32708. }
  32709. pPager->nSubRec = 0;
  32710. }
  32711. }
  32712. /* Else this is a rollback operation, playback the specified savepoint.
  32713. ** If this is a temp-file, it is possible that the journal file has
  32714. ** not yet been opened. In this case there have been no changes to
  32715. ** the database file, so the playback operation can be skipped.
  32716. */
  32717. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  32718. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  32719. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  32720. assert(rc!=SQLITE_DONE);
  32721. }
  32722. }
  32723. return rc;
  32724. }
  32725. /*
  32726. ** Return the full pathname of the database file.
  32727. **
  32728. ** Except, if the pager is in-memory only, then return an empty string if
  32729. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  32730. ** used to report the filename to the user, for compatibility with legacy
  32731. ** behavior. But when the Btree needs to know the filename for matching to
  32732. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  32733. ** participate in shared-cache.
  32734. */
  32735. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  32736. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  32737. }
  32738. /*
  32739. ** Return the VFS structure for the pager.
  32740. */
  32741. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  32742. return pPager->pVfs;
  32743. }
  32744. /*
  32745. ** Return the file handle for the database file associated
  32746. ** with the pager. This might return NULL if the file has
  32747. ** not yet been opened.
  32748. */
  32749. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  32750. return pPager->fd;
  32751. }
  32752. /*
  32753. ** Return the full pathname of the journal file.
  32754. */
  32755. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  32756. return pPager->zJournal;
  32757. }
  32758. /*
  32759. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  32760. ** if fsync()s are executed normally.
  32761. */
  32762. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  32763. return pPager->noSync;
  32764. }
  32765. #ifdef SQLITE_HAS_CODEC
  32766. /*
  32767. ** Set or retrieve the codec for this pager
  32768. */
  32769. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  32770. Pager *pPager,
  32771. void *(*xCodec)(void*,void*,Pgno,int),
  32772. void (*xCodecSizeChng)(void*,int,int),
  32773. void (*xCodecFree)(void*),
  32774. void *pCodec
  32775. ){
  32776. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  32777. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  32778. pPager->xCodecSizeChng = xCodecSizeChng;
  32779. pPager->xCodecFree = xCodecFree;
  32780. pPager->pCodec = pCodec;
  32781. pagerReportSize(pPager);
  32782. }
  32783. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  32784. return pPager->pCodec;
  32785. }
  32786. /*
  32787. ** This function is called by the wal module when writing page content
  32788. ** into the log file.
  32789. **
  32790. ** This function returns a pointer to a buffer containing the encrypted
  32791. ** page content. If a malloc fails, this function may return NULL.
  32792. */
  32793. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  32794. void *aData = 0;
  32795. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  32796. return aData;
  32797. }
  32798. /*
  32799. ** Return the current pager state
  32800. */
  32801. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  32802. return pPager->eState;
  32803. }
  32804. #endif /* SQLITE_HAS_CODEC */
  32805. #ifndef SQLITE_OMIT_AUTOVACUUM
  32806. /*
  32807. ** Move the page pPg to location pgno in the file.
  32808. **
  32809. ** There must be no references to the page previously located at
  32810. ** pgno (which we call pPgOld) though that page is allowed to be
  32811. ** in cache. If the page previously located at pgno is not already
  32812. ** in the rollback journal, it is not put there by by this routine.
  32813. **
  32814. ** References to the page pPg remain valid. Updating any
  32815. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  32816. ** allocated along with the page) is the responsibility of the caller.
  32817. **
  32818. ** A transaction must be active when this routine is called. It used to be
  32819. ** required that a statement transaction was not active, but this restriction
  32820. ** has been removed (CREATE INDEX needs to move a page when a statement
  32821. ** transaction is active).
  32822. **
  32823. ** If the fourth argument, isCommit, is non-zero, then this page is being
  32824. ** moved as part of a database reorganization just before the transaction
  32825. ** is being committed. In this case, it is guaranteed that the database page
  32826. ** pPg refers to will not be written to again within this transaction.
  32827. **
  32828. ** This function may return SQLITE_NOMEM or an IO error code if an error
  32829. ** occurs. Otherwise, it returns SQLITE_OK.
  32830. */
  32831. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  32832. PgHdr *pPgOld; /* The page being overwritten. */
  32833. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  32834. int rc; /* Return code */
  32835. Pgno origPgno; /* The original page number */
  32836. assert( pPg->nRef>0 );
  32837. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  32838. || pPager->eState==PAGER_WRITER_DBMOD
  32839. );
  32840. assert( assert_pager_state(pPager) );
  32841. /* In order to be able to rollback, an in-memory database must journal
  32842. ** the page we are moving from.
  32843. */
  32844. if( MEMDB ){
  32845. rc = sqlite3PagerWrite(pPg);
  32846. if( rc ) return rc;
  32847. }
  32848. /* If the page being moved is dirty and has not been saved by the latest
  32849. ** savepoint, then save the current contents of the page into the
  32850. ** sub-journal now. This is required to handle the following scenario:
  32851. **
  32852. ** BEGIN;
  32853. ** <journal page X, then modify it in memory>
  32854. ** SAVEPOINT one;
  32855. ** <Move page X to location Y>
  32856. ** ROLLBACK TO one;
  32857. **
  32858. ** If page X were not written to the sub-journal here, it would not
  32859. ** be possible to restore its contents when the "ROLLBACK TO one"
  32860. ** statement were is processed.
  32861. **
  32862. ** subjournalPage() may need to allocate space to store pPg->pgno into
  32863. ** one or more savepoint bitvecs. This is the reason this function
  32864. ** may return SQLITE_NOMEM.
  32865. */
  32866. if( pPg->flags&PGHDR_DIRTY
  32867. && subjRequiresPage(pPg)
  32868. && SQLITE_OK!=(rc = subjournalPage(pPg))
  32869. ){
  32870. return rc;
  32871. }
  32872. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  32873. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  32874. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  32875. /* If the journal needs to be sync()ed before page pPg->pgno can
  32876. ** be written to, store pPg->pgno in local variable needSyncPgno.
  32877. **
  32878. ** If the isCommit flag is set, there is no need to remember that
  32879. ** the journal needs to be sync()ed before database page pPg->pgno
  32880. ** can be written to. The caller has already promised not to write to it.
  32881. */
  32882. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  32883. needSyncPgno = pPg->pgno;
  32884. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  32885. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  32886. assert( pPg->flags&PGHDR_DIRTY );
  32887. }
  32888. /* If the cache contains a page with page-number pgno, remove it
  32889. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  32890. ** page pgno before the 'move' operation, it needs to be retained
  32891. ** for the page moved there.
  32892. */
  32893. pPg->flags &= ~PGHDR_NEED_SYNC;
  32894. pPgOld = pager_lookup(pPager, pgno);
  32895. assert( !pPgOld || pPgOld->nRef==1 );
  32896. if( pPgOld ){
  32897. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  32898. if( MEMDB ){
  32899. /* Do not discard pages from an in-memory database since we might
  32900. ** need to rollback later. Just move the page out of the way. */
  32901. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  32902. }else{
  32903. sqlite3PcacheDrop(pPgOld);
  32904. }
  32905. }
  32906. origPgno = pPg->pgno;
  32907. sqlite3PcacheMove(pPg, pgno);
  32908. sqlite3PcacheMakeDirty(pPg);
  32909. /* For an in-memory database, make sure the original page continues
  32910. ** to exist, in case the transaction needs to roll back. Use pPgOld
  32911. ** as the original page since it has already been allocated.
  32912. */
  32913. if( MEMDB ){
  32914. assert( pPgOld );
  32915. sqlite3PcacheMove(pPgOld, origPgno);
  32916. sqlite3PagerUnref(pPgOld);
  32917. }
  32918. if( needSyncPgno ){
  32919. /* If needSyncPgno is non-zero, then the journal file needs to be
  32920. ** sync()ed before any data is written to database file page needSyncPgno.
  32921. ** Currently, no such page exists in the page-cache and the
  32922. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  32923. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  32924. ** flag.
  32925. **
  32926. ** If the attempt to load the page into the page-cache fails, (due
  32927. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  32928. ** array. Otherwise, if the page is loaded and written again in
  32929. ** this transaction, it may be written to the database file before
  32930. ** it is synced into the journal file. This way, it may end up in
  32931. ** the journal file twice, but that is not a problem.
  32932. */
  32933. PgHdr *pPgHdr;
  32934. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  32935. if( rc!=SQLITE_OK ){
  32936. if( needSyncPgno<=pPager->dbOrigSize ){
  32937. assert( pPager->pTmpSpace!=0 );
  32938. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  32939. }
  32940. return rc;
  32941. }
  32942. pPgHdr->flags |= PGHDR_NEED_SYNC;
  32943. sqlite3PcacheMakeDirty(pPgHdr);
  32944. sqlite3PagerUnref(pPgHdr);
  32945. }
  32946. return SQLITE_OK;
  32947. }
  32948. #endif
  32949. /*
  32950. ** Return a pointer to the data for the specified page.
  32951. */
  32952. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  32953. assert( pPg->nRef>0 || pPg->pPager->memDb );
  32954. return pPg->pData;
  32955. }
  32956. /*
  32957. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  32958. ** allocated along with the specified page.
  32959. */
  32960. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  32961. return pPg->pExtra;
  32962. }
  32963. /*
  32964. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  32965. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  32966. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  32967. ** the locking-mode is set to the value specified.
  32968. **
  32969. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  32970. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  32971. ** locking-mode.
  32972. */
  32973. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  32974. assert( eMode==PAGER_LOCKINGMODE_QUERY
  32975. || eMode==PAGER_LOCKINGMODE_NORMAL
  32976. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  32977. assert( PAGER_LOCKINGMODE_QUERY<0 );
  32978. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  32979. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  32980. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  32981. pPager->exclusiveMode = (u8)eMode;
  32982. }
  32983. return (int)pPager->exclusiveMode;
  32984. }
  32985. /*
  32986. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  32987. **
  32988. ** PAGER_JOURNALMODE_DELETE
  32989. ** PAGER_JOURNALMODE_TRUNCATE
  32990. ** PAGER_JOURNALMODE_PERSIST
  32991. ** PAGER_JOURNALMODE_OFF
  32992. ** PAGER_JOURNALMODE_MEMORY
  32993. ** PAGER_JOURNALMODE_WAL
  32994. **
  32995. ** The journalmode is set to the value specified if the change is allowed.
  32996. ** The change may be disallowed for the following reasons:
  32997. **
  32998. ** * An in-memory database can only have its journal_mode set to _OFF
  32999. ** or _MEMORY.
  33000. **
  33001. ** * Temporary databases cannot have _WAL journalmode.
  33002. **
  33003. ** The returned indicate the current (possibly updated) journal-mode.
  33004. */
  33005. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  33006. u8 eOld = pPager->journalMode; /* Prior journalmode */
  33007. #ifdef SQLITE_DEBUG
  33008. /* The print_pager_state() routine is intended to be used by the debugger
  33009. ** only. We invoke it once here to suppress a compiler warning. */
  33010. print_pager_state(pPager);
  33011. #endif
  33012. /* The eMode parameter is always valid */
  33013. assert( eMode==PAGER_JOURNALMODE_DELETE
  33014. || eMode==PAGER_JOURNALMODE_TRUNCATE
  33015. || eMode==PAGER_JOURNALMODE_PERSIST
  33016. || eMode==PAGER_JOURNALMODE_OFF
  33017. || eMode==PAGER_JOURNALMODE_WAL
  33018. || eMode==PAGER_JOURNALMODE_MEMORY );
  33019. /* This routine is only called from the OP_JournalMode opcode, and
  33020. ** the logic there will never allow a temporary file to be changed
  33021. ** to WAL mode.
  33022. */
  33023. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  33024. /* Do allow the journalmode of an in-memory database to be set to
  33025. ** anything other than MEMORY or OFF
  33026. */
  33027. if( MEMDB ){
  33028. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  33029. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  33030. eMode = eOld;
  33031. }
  33032. }
  33033. if( eMode!=eOld ){
  33034. /* Change the journal mode. */
  33035. assert( pPager->eState!=PAGER_ERROR );
  33036. pPager->journalMode = (u8)eMode;
  33037. /* When transistioning from TRUNCATE or PERSIST to any other journal
  33038. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  33039. ** delete the journal file.
  33040. */
  33041. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  33042. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  33043. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  33044. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  33045. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  33046. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  33047. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  33048. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  33049. /* In this case we would like to delete the journal file. If it is
  33050. ** not possible, then that is not a problem. Deleting the journal file
  33051. ** here is an optimization only.
  33052. **
  33053. ** Before deleting the journal file, obtain a RESERVED lock on the
  33054. ** database file. This ensures that the journal file is not deleted
  33055. ** while it is in use by some other client.
  33056. */
  33057. sqlite3OsClose(pPager->jfd);
  33058. if( pPager->eLock>=RESERVED_LOCK ){
  33059. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  33060. }else{
  33061. int rc = SQLITE_OK;
  33062. int state = pPager->eState;
  33063. assert( state==PAGER_OPEN || state==PAGER_READER );
  33064. if( state==PAGER_OPEN ){
  33065. rc = sqlite3PagerSharedLock(pPager);
  33066. }
  33067. if( pPager->eState==PAGER_READER ){
  33068. assert( rc==SQLITE_OK );
  33069. rc = pagerLockDb(pPager, RESERVED_LOCK);
  33070. }
  33071. if( rc==SQLITE_OK ){
  33072. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  33073. }
  33074. if( rc==SQLITE_OK && state==PAGER_READER ){
  33075. pagerUnlockDb(pPager, SHARED_LOCK);
  33076. }else if( state==PAGER_OPEN ){
  33077. pager_unlock(pPager);
  33078. }
  33079. assert( state==pPager->eState );
  33080. }
  33081. }
  33082. }
  33083. /* Return the new journal mode */
  33084. return (int)pPager->journalMode;
  33085. }
  33086. /*
  33087. ** Return the current journal mode.
  33088. */
  33089. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  33090. return (int)pPager->journalMode;
  33091. }
  33092. /*
  33093. ** Return TRUE if the pager is in a state where it is OK to change the
  33094. ** journalmode. Journalmode changes can only happen when the database
  33095. ** is unmodified.
  33096. */
  33097. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  33098. assert( assert_pager_state(pPager) );
  33099. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  33100. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  33101. return 1;
  33102. }
  33103. /*
  33104. ** Get/set the size-limit used for persistent journal files.
  33105. **
  33106. ** Setting the size limit to -1 means no limit is enforced.
  33107. ** An attempt to set a limit smaller than -1 is a no-op.
  33108. */
  33109. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  33110. if( iLimit>=-1 ){
  33111. pPager->journalSizeLimit = iLimit;
  33112. sqlite3WalLimit(pPager->pWal, iLimit);
  33113. }
  33114. return pPager->journalSizeLimit;
  33115. }
  33116. /*
  33117. ** Return a pointer to the pPager->pBackup variable. The backup module
  33118. ** in backup.c maintains the content of this variable. This module
  33119. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  33120. ** sqlite3BackupUpdate() only.
  33121. */
  33122. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  33123. return &pPager->pBackup;
  33124. }
  33125. #ifndef SQLITE_OMIT_VACUUM
  33126. /*
  33127. ** Unless this is an in-memory or temporary database, clear the pager cache.
  33128. */
  33129. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  33130. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  33131. }
  33132. #endif
  33133. #ifndef SQLITE_OMIT_WAL
  33134. /*
  33135. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  33136. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  33137. ** or wal_blocking_checkpoint() API functions.
  33138. **
  33139. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  33140. */
  33141. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  33142. int rc = SQLITE_OK;
  33143. if( pPager->pWal ){
  33144. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  33145. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  33146. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  33147. pnLog, pnCkpt
  33148. );
  33149. }
  33150. return rc;
  33151. }
  33152. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  33153. return sqlite3WalCallback(pPager->pWal);
  33154. }
  33155. /*
  33156. ** Return true if the underlying VFS for the given pager supports the
  33157. ** primitives necessary for write-ahead logging.
  33158. */
  33159. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  33160. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  33161. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  33162. }
  33163. /*
  33164. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  33165. ** is obtained instead, immediately release it.
  33166. */
  33167. static int pagerExclusiveLock(Pager *pPager){
  33168. int rc; /* Return code */
  33169. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  33170. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  33171. if( rc!=SQLITE_OK ){
  33172. /* If the attempt to grab the exclusive lock failed, release the
  33173. ** pending lock that may have been obtained instead. */
  33174. pagerUnlockDb(pPager, SHARED_LOCK);
  33175. }
  33176. return rc;
  33177. }
  33178. /*
  33179. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  33180. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  33181. ** lock on the database file and use heap-memory to store the wal-index
  33182. ** in. Otherwise, use the normal shared-memory.
  33183. */
  33184. static int pagerOpenWal(Pager *pPager){
  33185. int rc = SQLITE_OK;
  33186. assert( pPager->pWal==0 && pPager->tempFile==0 );
  33187. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  33188. /* If the pager is already in exclusive-mode, the WAL module will use
  33189. ** heap-memory for the wal-index instead of the VFS shared-memory
  33190. ** implementation. Take the exclusive lock now, before opening the WAL
  33191. ** file, to make sure this is safe.
  33192. */
  33193. if( pPager->exclusiveMode ){
  33194. rc = pagerExclusiveLock(pPager);
  33195. }
  33196. /* Open the connection to the log file. If this operation fails,
  33197. ** (e.g. due to malloc() failure), return an error code.
  33198. */
  33199. if( rc==SQLITE_OK ){
  33200. rc = sqlite3WalOpen(pPager->pVfs,
  33201. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  33202. pPager->journalSizeLimit, &pPager->pWal
  33203. );
  33204. }
  33205. pagerFixMaplimit(pPager);
  33206. return rc;
  33207. }
  33208. /*
  33209. ** The caller must be holding a SHARED lock on the database file to call
  33210. ** this function.
  33211. **
  33212. ** If the pager passed as the first argument is open on a real database
  33213. ** file (not a temp file or an in-memory database), and the WAL file
  33214. ** is not already open, make an attempt to open it now. If successful,
  33215. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  33216. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  33217. ** not modified in either case.
  33218. **
  33219. ** If the pager is open on a temp-file (or in-memory database), or if
  33220. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  33221. ** without doing anything.
  33222. */
  33223. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  33224. Pager *pPager, /* Pager object */
  33225. int *pbOpen /* OUT: Set to true if call is a no-op */
  33226. ){
  33227. int rc = SQLITE_OK; /* Return code */
  33228. assert( assert_pager_state(pPager) );
  33229. assert( pPager->eState==PAGER_OPEN || pbOpen );
  33230. assert( pPager->eState==PAGER_READER || !pbOpen );
  33231. assert( pbOpen==0 || *pbOpen==0 );
  33232. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  33233. if( !pPager->tempFile && !pPager->pWal ){
  33234. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  33235. /* Close any rollback journal previously open */
  33236. sqlite3OsClose(pPager->jfd);
  33237. rc = pagerOpenWal(pPager);
  33238. if( rc==SQLITE_OK ){
  33239. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  33240. pPager->eState = PAGER_OPEN;
  33241. }
  33242. }else{
  33243. *pbOpen = 1;
  33244. }
  33245. return rc;
  33246. }
  33247. /*
  33248. ** This function is called to close the connection to the log file prior
  33249. ** to switching from WAL to rollback mode.
  33250. **
  33251. ** Before closing the log file, this function attempts to take an
  33252. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  33253. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  33254. ** If successful, the EXCLUSIVE lock is not released before returning.
  33255. */
  33256. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  33257. int rc = SQLITE_OK;
  33258. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  33259. /* If the log file is not already open, but does exist in the file-system,
  33260. ** it may need to be checkpointed before the connection can switch to
  33261. ** rollback mode. Open it now so this can happen.
  33262. */
  33263. if( !pPager->pWal ){
  33264. int logexists = 0;
  33265. rc = pagerLockDb(pPager, SHARED_LOCK);
  33266. if( rc==SQLITE_OK ){
  33267. rc = sqlite3OsAccess(
  33268. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  33269. );
  33270. }
  33271. if( rc==SQLITE_OK && logexists ){
  33272. rc = pagerOpenWal(pPager);
  33273. }
  33274. }
  33275. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  33276. ** the database file, the log and log-summary files will be deleted.
  33277. */
  33278. if( rc==SQLITE_OK && pPager->pWal ){
  33279. rc = pagerExclusiveLock(pPager);
  33280. if( rc==SQLITE_OK ){
  33281. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  33282. pPager->pageSize, (u8*)pPager->pTmpSpace);
  33283. pPager->pWal = 0;
  33284. pagerFixMaplimit(pPager);
  33285. }
  33286. }
  33287. return rc;
  33288. }
  33289. #endif /* !SQLITE_OMIT_WAL */
  33290. #ifdef SQLITE_ENABLE_ZIPVFS
  33291. /*
  33292. ** A read-lock must be held on the pager when this function is called. If
  33293. ** the pager is in WAL mode and the WAL file currently contains one or more
  33294. ** frames, return the size in bytes of the page images stored within the
  33295. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  33296. ** is empty, return 0.
  33297. */
  33298. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  33299. assert( pPager->eState==PAGER_READER );
  33300. return sqlite3WalFramesize(pPager->pWal);
  33301. }
  33302. #endif
  33303. #endif /* SQLITE_OMIT_DISKIO */
  33304. /************** End of pager.c ***********************************************/
  33305. /************** Begin file wal.c *********************************************/
  33306. /*
  33307. ** 2010 February 1
  33308. **
  33309. ** The author disclaims copyright to this source code. In place of
  33310. ** a legal notice, here is a blessing:
  33311. **
  33312. ** May you do good and not evil.
  33313. ** May you find forgiveness for yourself and forgive others.
  33314. ** May you share freely, never taking more than you give.
  33315. **
  33316. *************************************************************************
  33317. **
  33318. ** This file contains the implementation of a write-ahead log (WAL) used in
  33319. ** "journal_mode=WAL" mode.
  33320. **
  33321. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  33322. **
  33323. ** A WAL file consists of a header followed by zero or more "frames".
  33324. ** Each frame records the revised content of a single page from the
  33325. ** database file. All changes to the database are recorded by writing
  33326. ** frames into the WAL. Transactions commit when a frame is written that
  33327. ** contains a commit marker. A single WAL can and usually does record
  33328. ** multiple transactions. Periodically, the content of the WAL is
  33329. ** transferred back into the database file in an operation called a
  33330. ** "checkpoint".
  33331. **
  33332. ** A single WAL file can be used multiple times. In other words, the
  33333. ** WAL can fill up with frames and then be checkpointed and then new
  33334. ** frames can overwrite the old ones. A WAL always grows from beginning
  33335. ** toward the end. Checksums and counters attached to each frame are
  33336. ** used to determine which frames within the WAL are valid and which
  33337. ** are leftovers from prior checkpoints.
  33338. **
  33339. ** The WAL header is 32 bytes in size and consists of the following eight
  33340. ** big-endian 32-bit unsigned integer values:
  33341. **
  33342. ** 0: Magic number. 0x377f0682 or 0x377f0683
  33343. ** 4: File format version. Currently 3007000
  33344. ** 8: Database page size. Example: 1024
  33345. ** 12: Checkpoint sequence number
  33346. ** 16: Salt-1, random integer incremented with each checkpoint
  33347. ** 20: Salt-2, a different random integer changing with each ckpt
  33348. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  33349. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  33350. **
  33351. ** Immediately following the wal-header are zero or more frames. Each
  33352. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  33353. ** of page data. The frame-header is six big-endian 32-bit unsigned
  33354. ** integer values, as follows:
  33355. **
  33356. ** 0: Page number.
  33357. ** 4: For commit records, the size of the database image in pages
  33358. ** after the commit. For all other records, zero.
  33359. ** 8: Salt-1 (copied from the header)
  33360. ** 12: Salt-2 (copied from the header)
  33361. ** 16: Checksum-1.
  33362. ** 20: Checksum-2.
  33363. **
  33364. ** A frame is considered valid if and only if the following conditions are
  33365. ** true:
  33366. **
  33367. ** (1) The salt-1 and salt-2 values in the frame-header match
  33368. ** salt values in the wal-header
  33369. **
  33370. ** (2) The checksum values in the final 8 bytes of the frame-header
  33371. ** exactly match the checksum computed consecutively on the
  33372. ** WAL header and the first 8 bytes and the content of all frames
  33373. ** up to and including the current frame.
  33374. **
  33375. ** The checksum is computed using 32-bit big-endian integers if the
  33376. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  33377. ** is computed using little-endian if the magic number is 0x377f0682.
  33378. ** The checksum values are always stored in the frame header in a
  33379. ** big-endian format regardless of which byte order is used to compute
  33380. ** the checksum. The checksum is computed by interpreting the input as
  33381. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  33382. ** algorithm used for the checksum is as follows:
  33383. **
  33384. ** for i from 0 to n-1 step 2:
  33385. ** s0 += x[i] + s1;
  33386. ** s1 += x[i+1] + s0;
  33387. ** endfor
  33388. **
  33389. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  33390. ** in reverse order (the largest fibonacci weight occurs on the first element
  33391. ** of the sequence being summed.) The s1 value spans all 32-bit
  33392. ** terms of the sequence whereas s0 omits the final term.
  33393. **
  33394. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  33395. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  33396. ** The VFS.xSync operations serve as write barriers - all writes launched
  33397. ** before the xSync must complete before any write that launches after the
  33398. ** xSync begins.
  33399. **
  33400. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  33401. ** value is randomized. This prevents old and new frames in the WAL from
  33402. ** being considered valid at the same time and being checkpointing together
  33403. ** following a crash.
  33404. **
  33405. ** READER ALGORITHM
  33406. **
  33407. ** To read a page from the database (call it page number P), a reader
  33408. ** first checks the WAL to see if it contains page P. If so, then the
  33409. ** last valid instance of page P that is a followed by a commit frame
  33410. ** or is a commit frame itself becomes the value read. If the WAL
  33411. ** contains no copies of page P that are valid and which are a commit
  33412. ** frame or are followed by a commit frame, then page P is read from
  33413. ** the database file.
  33414. **
  33415. ** To start a read transaction, the reader records the index of the last
  33416. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  33417. ** for all subsequent read operations. New transactions can be appended
  33418. ** to the WAL, but as long as the reader uses its original mxFrame value
  33419. ** and ignores the newly appended content, it will see a consistent snapshot
  33420. ** of the database from a single point in time. This technique allows
  33421. ** multiple concurrent readers to view different versions of the database
  33422. ** content simultaneously.
  33423. **
  33424. ** The reader algorithm in the previous paragraphs works correctly, but
  33425. ** because frames for page P can appear anywhere within the WAL, the
  33426. ** reader has to scan the entire WAL looking for page P frames. If the
  33427. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  33428. ** and read performance suffers. To overcome this problem, a separate
  33429. ** data structure called the wal-index is maintained to expedite the
  33430. ** search for frames of a particular page.
  33431. **
  33432. ** WAL-INDEX FORMAT
  33433. **
  33434. ** Conceptually, the wal-index is shared memory, though VFS implementations
  33435. ** might choose to implement the wal-index using a mmapped file. Because
  33436. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  33437. ** on a network filesystem. All users of the database must be able to
  33438. ** share memory.
  33439. **
  33440. ** The wal-index is transient. After a crash, the wal-index can (and should
  33441. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  33442. ** to either truncate or zero the header of the wal-index when the last
  33443. ** connection to it closes. Because the wal-index is transient, it can
  33444. ** use an architecture-specific format; it does not have to be cross-platform.
  33445. ** Hence, unlike the database and WAL file formats which store all values
  33446. ** as big endian, the wal-index can store multi-byte values in the native
  33447. ** byte order of the host computer.
  33448. **
  33449. ** The purpose of the wal-index is to answer this question quickly: Given
  33450. ** a page number P and a maximum frame index M, return the index of the
  33451. ** last frame in the wal before frame M for page P in the WAL, or return
  33452. ** NULL if there are no frames for page P in the WAL prior to M.
  33453. **
  33454. ** The wal-index consists of a header region, followed by an one or
  33455. ** more index blocks.
  33456. **
  33457. ** The wal-index header contains the total number of frames within the WAL
  33458. ** in the mxFrame field.
  33459. **
  33460. ** Each index block except for the first contains information on
  33461. ** HASHTABLE_NPAGE frames. The first index block contains information on
  33462. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  33463. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  33464. ** first index block are the same size as all other index blocks in the
  33465. ** wal-index.
  33466. **
  33467. ** Each index block contains two sections, a page-mapping that contains the
  33468. ** database page number associated with each wal frame, and a hash-table
  33469. ** that allows readers to query an index block for a specific page number.
  33470. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  33471. ** for the first index block) 32-bit page numbers. The first entry in the
  33472. ** first index-block contains the database page number corresponding to the
  33473. ** first frame in the WAL file. The first entry in the second index block
  33474. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  33475. ** the log, and so on.
  33476. **
  33477. ** The last index block in a wal-index usually contains less than the full
  33478. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  33479. ** depending on the contents of the WAL file. This does not change the
  33480. ** allocated size of the page-mapping array - the page-mapping array merely
  33481. ** contains unused entries.
  33482. **
  33483. ** Even without using the hash table, the last frame for page P
  33484. ** can be found by scanning the page-mapping sections of each index block
  33485. ** starting with the last index block and moving toward the first, and
  33486. ** within each index block, starting at the end and moving toward the
  33487. ** beginning. The first entry that equals P corresponds to the frame
  33488. ** holding the content for that page.
  33489. **
  33490. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  33491. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  33492. ** hash table for each page number in the mapping section, so the hash
  33493. ** table is never more than half full. The expected number of collisions
  33494. ** prior to finding a match is 1. Each entry of the hash table is an
  33495. ** 1-based index of an entry in the mapping section of the same
  33496. ** index block. Let K be the 1-based index of the largest entry in
  33497. ** the mapping section. (For index blocks other than the last, K will
  33498. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  33499. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  33500. ** contain a value of 0.
  33501. **
  33502. ** To look for page P in the hash table, first compute a hash iKey on
  33503. ** P as follows:
  33504. **
  33505. ** iKey = (P * 383) % HASHTABLE_NSLOT
  33506. **
  33507. ** Then start scanning entries of the hash table, starting with iKey
  33508. ** (wrapping around to the beginning when the end of the hash table is
  33509. ** reached) until an unused hash slot is found. Let the first unused slot
  33510. ** be at index iUnused. (iUnused might be less than iKey if there was
  33511. ** wrap-around.) Because the hash table is never more than half full,
  33512. ** the search is guaranteed to eventually hit an unused entry. Let
  33513. ** iMax be the value between iKey and iUnused, closest to iUnused,
  33514. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  33515. ** no hash slot such that aHash[i]==p) then page P is not in the
  33516. ** current index block. Otherwise the iMax-th mapping entry of the
  33517. ** current index block corresponds to the last entry that references
  33518. ** page P.
  33519. **
  33520. ** A hash search begins with the last index block and moves toward the
  33521. ** first index block, looking for entries corresponding to page P. On
  33522. ** average, only two or three slots in each index block need to be
  33523. ** examined in order to either find the last entry for page P, or to
  33524. ** establish that no such entry exists in the block. Each index block
  33525. ** holds over 4000 entries. So two or three index blocks are sufficient
  33526. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  33527. ** comparisons (on average) suffice to either locate a frame in the
  33528. ** WAL or to establish that the frame does not exist in the WAL. This
  33529. ** is much faster than scanning the entire 10MB WAL.
  33530. **
  33531. ** Note that entries are added in order of increasing K. Hence, one
  33532. ** reader might be using some value K0 and a second reader that started
  33533. ** at a later time (after additional transactions were added to the WAL
  33534. ** and to the wal-index) might be using a different value K1, where K1>K0.
  33535. ** Both readers can use the same hash table and mapping section to get
  33536. ** the correct result. There may be entries in the hash table with
  33537. ** K>K0 but to the first reader, those entries will appear to be unused
  33538. ** slots in the hash table and so the first reader will get an answer as
  33539. ** if no values greater than K0 had ever been inserted into the hash table
  33540. ** in the first place - which is what reader one wants. Meanwhile, the
  33541. ** second reader using K1 will see additional values that were inserted
  33542. ** later, which is exactly what reader two wants.
  33543. **
  33544. ** When a rollback occurs, the value of K is decreased. Hash table entries
  33545. ** that correspond to frames greater than the new K value are removed
  33546. ** from the hash table at this point.
  33547. */
  33548. #ifndef SQLITE_OMIT_WAL
  33549. /*
  33550. ** Trace output macros
  33551. */
  33552. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  33553. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  33554. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  33555. #else
  33556. # define WALTRACE(X)
  33557. #endif
  33558. /*
  33559. ** The maximum (and only) versions of the wal and wal-index formats
  33560. ** that may be interpreted by this version of SQLite.
  33561. **
  33562. ** If a client begins recovering a WAL file and finds that (a) the checksum
  33563. ** values in the wal-header are correct and (b) the version field is not
  33564. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  33565. **
  33566. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  33567. ** checksum test is successful) and finds that the version field is not
  33568. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  33569. ** returns SQLITE_CANTOPEN.
  33570. */
  33571. #define WAL_MAX_VERSION 3007000
  33572. #define WALINDEX_MAX_VERSION 3007000
  33573. /*
  33574. ** Indices of various locking bytes. WAL_NREADER is the number
  33575. ** of available reader locks and should be at least 3.
  33576. */
  33577. #define WAL_WRITE_LOCK 0
  33578. #define WAL_ALL_BUT_WRITE 1
  33579. #define WAL_CKPT_LOCK 1
  33580. #define WAL_RECOVER_LOCK 2
  33581. #define WAL_READ_LOCK(I) (3+(I))
  33582. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  33583. /* Object declarations */
  33584. typedef struct WalIndexHdr WalIndexHdr;
  33585. typedef struct WalIterator WalIterator;
  33586. typedef struct WalCkptInfo WalCkptInfo;
  33587. /*
  33588. ** The following object holds a copy of the wal-index header content.
  33589. **
  33590. ** The actual header in the wal-index consists of two copies of this
  33591. ** object.
  33592. **
  33593. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  33594. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  33595. ** added in 3.7.1 when support for 64K pages was added.
  33596. */
  33597. struct WalIndexHdr {
  33598. u32 iVersion; /* Wal-index version */
  33599. u32 unused; /* Unused (padding) field */
  33600. u32 iChange; /* Counter incremented each transaction */
  33601. u8 isInit; /* 1 when initialized */
  33602. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  33603. u16 szPage; /* Database page size in bytes. 1==64K */
  33604. u32 mxFrame; /* Index of last valid frame in the WAL */
  33605. u32 nPage; /* Size of database in pages */
  33606. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  33607. u32 aSalt[2]; /* Two salt values copied from WAL header */
  33608. u32 aCksum[2]; /* Checksum over all prior fields */
  33609. };
  33610. /*
  33611. ** A copy of the following object occurs in the wal-index immediately
  33612. ** following the second copy of the WalIndexHdr. This object stores
  33613. ** information used by checkpoint.
  33614. **
  33615. ** nBackfill is the number of frames in the WAL that have been written
  33616. ** back into the database. (We call the act of moving content from WAL to
  33617. ** database "backfilling".) The nBackfill number is never greater than
  33618. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  33619. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  33620. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  33621. ** mxFrame back to zero when the WAL is reset.
  33622. **
  33623. ** There is one entry in aReadMark[] for each reader lock. If a reader
  33624. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  33625. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  33626. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  33627. ** a special case; its value is never used and it exists as a place-holder
  33628. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  33629. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  33630. ** directly from the database.
  33631. **
  33632. ** The value of aReadMark[K] may only be changed by a thread that
  33633. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  33634. ** aReadMark[K] cannot changed while there is a reader is using that mark
  33635. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  33636. **
  33637. ** The checkpointer may only transfer frames from WAL to database where
  33638. ** the frame numbers are less than or equal to every aReadMark[] that is
  33639. ** in use (that is, every aReadMark[j] for which there is a corresponding
  33640. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  33641. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  33642. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  33643. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  33644. ** in the WAL has been backfilled into the database) then new readers
  33645. ** will choose aReadMark[0] which has value 0 and hence such reader will
  33646. ** get all their all content directly from the database file and ignore
  33647. ** the WAL.
  33648. **
  33649. ** Writers normally append new frames to the end of the WAL. However,
  33650. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  33651. ** written back into the database) and if no readers are using the WAL
  33652. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  33653. ** the writer will first "reset" the WAL back to the beginning and start
  33654. ** writing new content beginning at frame 1.
  33655. **
  33656. ** We assume that 32-bit loads are atomic and so no locks are needed in
  33657. ** order to read from any aReadMark[] entries.
  33658. */
  33659. struct WalCkptInfo {
  33660. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  33661. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  33662. };
  33663. #define READMARK_NOT_USED 0xffffffff
  33664. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  33665. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  33666. ** only support mandatory file-locks, we do not read or write data
  33667. ** from the region of the file on which locks are applied.
  33668. */
  33669. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  33670. #define WALINDEX_LOCK_RESERVED 16
  33671. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  33672. /* Size of header before each frame in wal */
  33673. #define WAL_FRAME_HDRSIZE 24
  33674. /* Size of write ahead log header, including checksum. */
  33675. /* #define WAL_HDRSIZE 24 */
  33676. #define WAL_HDRSIZE 32
  33677. /* WAL magic value. Either this value, or the same value with the least
  33678. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  33679. ** big-endian format in the first 4 bytes of a WAL file.
  33680. **
  33681. ** If the LSB is set, then the checksums for each frame within the WAL
  33682. ** file are calculated by treating all data as an array of 32-bit
  33683. ** big-endian words. Otherwise, they are calculated by interpreting
  33684. ** all data as 32-bit little-endian words.
  33685. */
  33686. #define WAL_MAGIC 0x377f0682
  33687. /*
  33688. ** Return the offset of frame iFrame in the write-ahead log file,
  33689. ** assuming a database page size of szPage bytes. The offset returned
  33690. ** is to the start of the write-ahead log frame-header.
  33691. */
  33692. #define walFrameOffset(iFrame, szPage) ( \
  33693. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  33694. )
  33695. /*
  33696. ** An open write-ahead log file is represented by an instance of the
  33697. ** following object.
  33698. */
  33699. struct Wal {
  33700. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  33701. sqlite3_file *pDbFd; /* File handle for the database file */
  33702. sqlite3_file *pWalFd; /* File handle for WAL file */
  33703. u32 iCallback; /* Value to pass to log callback (or 0) */
  33704. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  33705. int nWiData; /* Size of array apWiData */
  33706. int szFirstBlock; /* Size of first block written to WAL file */
  33707. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  33708. u32 szPage; /* Database page size */
  33709. i16 readLock; /* Which read lock is being held. -1 for none */
  33710. u8 syncFlags; /* Flags to use to sync header writes */
  33711. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  33712. u8 writeLock; /* True if in a write transaction */
  33713. u8 ckptLock; /* True if holding a checkpoint lock */
  33714. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  33715. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  33716. u8 syncHeader; /* Fsync the WAL header if true */
  33717. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  33718. WalIndexHdr hdr; /* Wal-index header for current transaction */
  33719. const char *zWalName; /* Name of WAL file */
  33720. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  33721. #ifdef SQLITE_DEBUG
  33722. u8 lockError; /* True if a locking error has occurred */
  33723. #endif
  33724. };
  33725. /*
  33726. ** Candidate values for Wal.exclusiveMode.
  33727. */
  33728. #define WAL_NORMAL_MODE 0
  33729. #define WAL_EXCLUSIVE_MODE 1
  33730. #define WAL_HEAPMEMORY_MODE 2
  33731. /*
  33732. ** Possible values for WAL.readOnly
  33733. */
  33734. #define WAL_RDWR 0 /* Normal read/write connection */
  33735. #define WAL_RDONLY 1 /* The WAL file is readonly */
  33736. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  33737. /*
  33738. ** Each page of the wal-index mapping contains a hash-table made up of
  33739. ** an array of HASHTABLE_NSLOT elements of the following type.
  33740. */
  33741. typedef u16 ht_slot;
  33742. /*
  33743. ** This structure is used to implement an iterator that loops through
  33744. ** all frames in the WAL in database page order. Where two or more frames
  33745. ** correspond to the same database page, the iterator visits only the
  33746. ** frame most recently written to the WAL (in other words, the frame with
  33747. ** the largest index).
  33748. **
  33749. ** The internals of this structure are only accessed by:
  33750. **
  33751. ** walIteratorInit() - Create a new iterator,
  33752. ** walIteratorNext() - Step an iterator,
  33753. ** walIteratorFree() - Free an iterator.
  33754. **
  33755. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  33756. */
  33757. struct WalIterator {
  33758. int iPrior; /* Last result returned from the iterator */
  33759. int nSegment; /* Number of entries in aSegment[] */
  33760. struct WalSegment {
  33761. int iNext; /* Next slot in aIndex[] not yet returned */
  33762. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  33763. u32 *aPgno; /* Array of page numbers. */
  33764. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  33765. int iZero; /* Frame number associated with aPgno[0] */
  33766. } aSegment[1]; /* One for every 32KB page in the wal-index */
  33767. };
  33768. /*
  33769. ** Define the parameters of the hash tables in the wal-index file. There
  33770. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  33771. ** wal-index.
  33772. **
  33773. ** Changing any of these constants will alter the wal-index format and
  33774. ** create incompatibilities.
  33775. */
  33776. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  33777. #define HASHTABLE_HASH_1 383 /* Should be prime */
  33778. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  33779. /*
  33780. ** The block of page numbers associated with the first hash-table in a
  33781. ** wal-index is smaller than usual. This is so that there is a complete
  33782. ** hash-table on each aligned 32KB page of the wal-index.
  33783. */
  33784. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  33785. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  33786. #define WALINDEX_PGSZ ( \
  33787. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  33788. )
  33789. /*
  33790. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  33791. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  33792. ** numbered from zero.
  33793. **
  33794. ** If this call is successful, *ppPage is set to point to the wal-index
  33795. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  33796. ** then an SQLite error code is returned and *ppPage is set to 0.
  33797. */
  33798. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  33799. int rc = SQLITE_OK;
  33800. /* Enlarge the pWal->apWiData[] array if required */
  33801. if( pWal->nWiData<=iPage ){
  33802. int nByte = sizeof(u32*)*(iPage+1);
  33803. volatile u32 **apNew;
  33804. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  33805. if( !apNew ){
  33806. *ppPage = 0;
  33807. return SQLITE_NOMEM;
  33808. }
  33809. memset((void*)&apNew[pWal->nWiData], 0,
  33810. sizeof(u32*)*(iPage+1-pWal->nWiData));
  33811. pWal->apWiData = apNew;
  33812. pWal->nWiData = iPage+1;
  33813. }
  33814. /* Request a pointer to the required page from the VFS */
  33815. if( pWal->apWiData[iPage]==0 ){
  33816. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  33817. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  33818. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  33819. }else{
  33820. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  33821. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  33822. );
  33823. if( rc==SQLITE_READONLY ){
  33824. pWal->readOnly |= WAL_SHM_RDONLY;
  33825. rc = SQLITE_OK;
  33826. }
  33827. }
  33828. }
  33829. *ppPage = pWal->apWiData[iPage];
  33830. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  33831. return rc;
  33832. }
  33833. /*
  33834. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  33835. */
  33836. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  33837. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  33838. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  33839. }
  33840. /*
  33841. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  33842. */
  33843. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  33844. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  33845. return (volatile WalIndexHdr*)pWal->apWiData[0];
  33846. }
  33847. /*
  33848. ** The argument to this macro must be of type u32. On a little-endian
  33849. ** architecture, it returns the u32 value that results from interpreting
  33850. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  33851. ** returns the value that would be produced by intepreting the 4 bytes
  33852. ** of the input value as a little-endian integer.
  33853. */
  33854. #define BYTESWAP32(x) ( \
  33855. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  33856. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  33857. )
  33858. /*
  33859. ** Generate or extend an 8 byte checksum based on the data in
  33860. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  33861. ** initial values of 0 and 0 if aIn==NULL).
  33862. **
  33863. ** The checksum is written back into aOut[] before returning.
  33864. **
  33865. ** nByte must be a positive multiple of 8.
  33866. */
  33867. static void walChecksumBytes(
  33868. int nativeCksum, /* True for native byte-order, false for non-native */
  33869. u8 *a, /* Content to be checksummed */
  33870. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  33871. const u32 *aIn, /* Initial checksum value input */
  33872. u32 *aOut /* OUT: Final checksum value output */
  33873. ){
  33874. u32 s1, s2;
  33875. u32 *aData = (u32 *)a;
  33876. u32 *aEnd = (u32 *)&a[nByte];
  33877. if( aIn ){
  33878. s1 = aIn[0];
  33879. s2 = aIn[1];
  33880. }else{
  33881. s1 = s2 = 0;
  33882. }
  33883. assert( nByte>=8 );
  33884. assert( (nByte&0x00000007)==0 );
  33885. if( nativeCksum ){
  33886. do {
  33887. s1 += *aData++ + s2;
  33888. s2 += *aData++ + s1;
  33889. }while( aData<aEnd );
  33890. }else{
  33891. do {
  33892. s1 += BYTESWAP32(aData[0]) + s2;
  33893. s2 += BYTESWAP32(aData[1]) + s1;
  33894. aData += 2;
  33895. }while( aData<aEnd );
  33896. }
  33897. aOut[0] = s1;
  33898. aOut[1] = s2;
  33899. }
  33900. static void walShmBarrier(Wal *pWal){
  33901. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  33902. sqlite3OsShmBarrier(pWal->pDbFd);
  33903. }
  33904. }
  33905. /*
  33906. ** Write the header information in pWal->hdr into the wal-index.
  33907. **
  33908. ** The checksum on pWal->hdr is updated before it is written.
  33909. */
  33910. static void walIndexWriteHdr(Wal *pWal){
  33911. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  33912. const int nCksum = offsetof(WalIndexHdr, aCksum);
  33913. assert( pWal->writeLock );
  33914. pWal->hdr.isInit = 1;
  33915. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  33916. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  33917. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  33918. walShmBarrier(pWal);
  33919. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  33920. }
  33921. /*
  33922. ** This function encodes a single frame header and writes it to a buffer
  33923. ** supplied by the caller. A frame-header is made up of a series of
  33924. ** 4-byte big-endian integers, as follows:
  33925. **
  33926. ** 0: Page number.
  33927. ** 4: For commit records, the size of the database image in pages
  33928. ** after the commit. For all other records, zero.
  33929. ** 8: Salt-1 (copied from the wal-header)
  33930. ** 12: Salt-2 (copied from the wal-header)
  33931. ** 16: Checksum-1.
  33932. ** 20: Checksum-2.
  33933. */
  33934. static void walEncodeFrame(
  33935. Wal *pWal, /* The write-ahead log */
  33936. u32 iPage, /* Database page number for frame */
  33937. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  33938. u8 *aData, /* Pointer to page data */
  33939. u8 *aFrame /* OUT: Write encoded frame here */
  33940. ){
  33941. int nativeCksum; /* True for native byte-order checksums */
  33942. u32 *aCksum = pWal->hdr.aFrameCksum;
  33943. assert( WAL_FRAME_HDRSIZE==24 );
  33944. sqlite3Put4byte(&aFrame[0], iPage);
  33945. sqlite3Put4byte(&aFrame[4], nTruncate);
  33946. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  33947. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  33948. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  33949. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  33950. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  33951. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  33952. }
  33953. /*
  33954. ** Check to see if the frame with header in aFrame[] and content
  33955. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  33956. ** *pnTruncate and return true. Return if the frame is not valid.
  33957. */
  33958. static int walDecodeFrame(
  33959. Wal *pWal, /* The write-ahead log */
  33960. u32 *piPage, /* OUT: Database page number for frame */
  33961. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  33962. u8 *aData, /* Pointer to page data (for checksum) */
  33963. u8 *aFrame /* Frame data */
  33964. ){
  33965. int nativeCksum; /* True for native byte-order checksums */
  33966. u32 *aCksum = pWal->hdr.aFrameCksum;
  33967. u32 pgno; /* Page number of the frame */
  33968. assert( WAL_FRAME_HDRSIZE==24 );
  33969. /* A frame is only valid if the salt values in the frame-header
  33970. ** match the salt values in the wal-header.
  33971. */
  33972. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  33973. return 0;
  33974. }
  33975. /* A frame is only valid if the page number is creater than zero.
  33976. */
  33977. pgno = sqlite3Get4byte(&aFrame[0]);
  33978. if( pgno==0 ){
  33979. return 0;
  33980. }
  33981. /* A frame is only valid if a checksum of the WAL header,
  33982. ** all prior frams, the first 16 bytes of this frame-header,
  33983. ** and the frame-data matches the checksum in the last 8
  33984. ** bytes of this frame-header.
  33985. */
  33986. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  33987. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  33988. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  33989. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  33990. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  33991. ){
  33992. /* Checksum failed. */
  33993. return 0;
  33994. }
  33995. /* If we reach this point, the frame is valid. Return the page number
  33996. ** and the new database size.
  33997. */
  33998. *piPage = pgno;
  33999. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  34000. return 1;
  34001. }
  34002. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  34003. /*
  34004. ** Names of locks. This routine is used to provide debugging output and is not
  34005. ** a part of an ordinary build.
  34006. */
  34007. static const char *walLockName(int lockIdx){
  34008. if( lockIdx==WAL_WRITE_LOCK ){
  34009. return "WRITE-LOCK";
  34010. }else if( lockIdx==WAL_CKPT_LOCK ){
  34011. return "CKPT-LOCK";
  34012. }else if( lockIdx==WAL_RECOVER_LOCK ){
  34013. return "RECOVER-LOCK";
  34014. }else{
  34015. static char zName[15];
  34016. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  34017. lockIdx-WAL_READ_LOCK(0));
  34018. return zName;
  34019. }
  34020. }
  34021. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  34022. /*
  34023. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  34024. ** A lock cannot be moved directly between shared and exclusive - it must go
  34025. ** through the unlocked state first.
  34026. **
  34027. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  34028. */
  34029. static int walLockShared(Wal *pWal, int lockIdx){
  34030. int rc;
  34031. if( pWal->exclusiveMode ) return SQLITE_OK;
  34032. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  34033. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  34034. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  34035. walLockName(lockIdx), rc ? "failed" : "ok"));
  34036. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  34037. return rc;
  34038. }
  34039. static void walUnlockShared(Wal *pWal, int lockIdx){
  34040. if( pWal->exclusiveMode ) return;
  34041. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  34042. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  34043. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  34044. }
  34045. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  34046. int rc;
  34047. if( pWal->exclusiveMode ) return SQLITE_OK;
  34048. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  34049. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  34050. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  34051. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  34052. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  34053. return rc;
  34054. }
  34055. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  34056. if( pWal->exclusiveMode ) return;
  34057. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  34058. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  34059. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  34060. walLockName(lockIdx), n));
  34061. }
  34062. /*
  34063. ** Compute a hash on a page number. The resulting hash value must land
  34064. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  34065. ** the hash to the next value in the event of a collision.
  34066. */
  34067. static int walHash(u32 iPage){
  34068. assert( iPage>0 );
  34069. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  34070. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  34071. }
  34072. static int walNextHash(int iPriorHash){
  34073. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  34074. }
  34075. /*
  34076. ** Return pointers to the hash table and page number array stored on
  34077. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  34078. ** numbered starting from 0.
  34079. **
  34080. ** Set output variable *paHash to point to the start of the hash table
  34081. ** in the wal-index file. Set *piZero to one less than the frame
  34082. ** number of the first frame indexed by this hash table. If a
  34083. ** slot in the hash table is set to N, it refers to frame number
  34084. ** (*piZero+N) in the log.
  34085. **
  34086. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  34087. ** first frame indexed by the hash table, frame (*piZero+1).
  34088. */
  34089. static int walHashGet(
  34090. Wal *pWal, /* WAL handle */
  34091. int iHash, /* Find the iHash'th table */
  34092. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  34093. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  34094. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  34095. ){
  34096. int rc; /* Return code */
  34097. volatile u32 *aPgno;
  34098. rc = walIndexPage(pWal, iHash, &aPgno);
  34099. assert( rc==SQLITE_OK || iHash>0 );
  34100. if( rc==SQLITE_OK ){
  34101. u32 iZero;
  34102. volatile ht_slot *aHash;
  34103. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  34104. if( iHash==0 ){
  34105. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  34106. iZero = 0;
  34107. }else{
  34108. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  34109. }
  34110. *paPgno = &aPgno[-1];
  34111. *paHash = aHash;
  34112. *piZero = iZero;
  34113. }
  34114. return rc;
  34115. }
  34116. /*
  34117. ** Return the number of the wal-index page that contains the hash-table
  34118. ** and page-number array that contain entries corresponding to WAL frame
  34119. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  34120. ** are numbered starting from 0.
  34121. */
  34122. static int walFramePage(u32 iFrame){
  34123. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  34124. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  34125. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  34126. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  34127. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  34128. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  34129. );
  34130. return iHash;
  34131. }
  34132. /*
  34133. ** Return the page number associated with frame iFrame in this WAL.
  34134. */
  34135. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  34136. int iHash = walFramePage(iFrame);
  34137. if( iHash==0 ){
  34138. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  34139. }
  34140. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  34141. }
  34142. /*
  34143. ** Remove entries from the hash table that point to WAL slots greater
  34144. ** than pWal->hdr.mxFrame.
  34145. **
  34146. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  34147. ** to a rollback or savepoint.
  34148. **
  34149. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  34150. ** updated. Any later hash tables will be automatically cleared when
  34151. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  34152. ** actually needed.
  34153. */
  34154. static void walCleanupHash(Wal *pWal){
  34155. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  34156. volatile u32 *aPgno = 0; /* Page number array for hash table */
  34157. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  34158. int iLimit = 0; /* Zero values greater than this */
  34159. int nByte; /* Number of bytes to zero in aPgno[] */
  34160. int i; /* Used to iterate through aHash[] */
  34161. assert( pWal->writeLock );
  34162. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  34163. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  34164. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  34165. if( pWal->hdr.mxFrame==0 ) return;
  34166. /* Obtain pointers to the hash-table and page-number array containing
  34167. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  34168. ** that the page said hash-table and array reside on is already mapped.
  34169. */
  34170. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  34171. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  34172. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  34173. /* Zero all hash-table entries that correspond to frame numbers greater
  34174. ** than pWal->hdr.mxFrame.
  34175. */
  34176. iLimit = pWal->hdr.mxFrame - iZero;
  34177. assert( iLimit>0 );
  34178. for(i=0; i<HASHTABLE_NSLOT; i++){
  34179. if( aHash[i]>iLimit ){
  34180. aHash[i] = 0;
  34181. }
  34182. }
  34183. /* Zero the entries in the aPgno array that correspond to frames with
  34184. ** frame numbers greater than pWal->hdr.mxFrame.
  34185. */
  34186. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  34187. memset((void *)&aPgno[iLimit+1], 0, nByte);
  34188. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  34189. /* Verify that the every entry in the mapping region is still reachable
  34190. ** via the hash table even after the cleanup.
  34191. */
  34192. if( iLimit ){
  34193. int i; /* Loop counter */
  34194. int iKey; /* Hash key */
  34195. for(i=1; i<=iLimit; i++){
  34196. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  34197. if( aHash[iKey]==i ) break;
  34198. }
  34199. assert( aHash[iKey]==i );
  34200. }
  34201. }
  34202. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  34203. }
  34204. /*
  34205. ** Set an entry in the wal-index that will map database page number
  34206. ** pPage into WAL frame iFrame.
  34207. */
  34208. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  34209. int rc; /* Return code */
  34210. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  34211. volatile u32 *aPgno = 0; /* Page number array */
  34212. volatile ht_slot *aHash = 0; /* Hash table */
  34213. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  34214. /* Assuming the wal-index file was successfully mapped, populate the
  34215. ** page number array and hash table entry.
  34216. */
  34217. if( rc==SQLITE_OK ){
  34218. int iKey; /* Hash table key */
  34219. int idx; /* Value to write to hash-table slot */
  34220. int nCollide; /* Number of hash collisions */
  34221. idx = iFrame - iZero;
  34222. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  34223. /* If this is the first entry to be added to this hash-table, zero the
  34224. ** entire hash table and aPgno[] array before proceding.
  34225. */
  34226. if( idx==1 ){
  34227. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  34228. memset((void*)&aPgno[1], 0, nByte);
  34229. }
  34230. /* If the entry in aPgno[] is already set, then the previous writer
  34231. ** must have exited unexpectedly in the middle of a transaction (after
  34232. ** writing one or more dirty pages to the WAL to free up memory).
  34233. ** Remove the remnants of that writers uncommitted transaction from
  34234. ** the hash-table before writing any new entries.
  34235. */
  34236. if( aPgno[idx] ){
  34237. walCleanupHash(pWal);
  34238. assert( !aPgno[idx] );
  34239. }
  34240. /* Write the aPgno[] array entry and the hash-table slot. */
  34241. nCollide = idx;
  34242. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  34243. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  34244. }
  34245. aPgno[idx] = iPage;
  34246. aHash[iKey] = (ht_slot)idx;
  34247. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  34248. /* Verify that the number of entries in the hash table exactly equals
  34249. ** the number of entries in the mapping region.
  34250. */
  34251. {
  34252. int i; /* Loop counter */
  34253. int nEntry = 0; /* Number of entries in the hash table */
  34254. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  34255. assert( nEntry==idx );
  34256. }
  34257. /* Verify that the every entry in the mapping region is reachable
  34258. ** via the hash table. This turns out to be a really, really expensive
  34259. ** thing to check, so only do this occasionally - not on every
  34260. ** iteration.
  34261. */
  34262. if( (idx&0x3ff)==0 ){
  34263. int i; /* Loop counter */
  34264. for(i=1; i<=idx; i++){
  34265. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  34266. if( aHash[iKey]==i ) break;
  34267. }
  34268. assert( aHash[iKey]==i );
  34269. }
  34270. }
  34271. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  34272. }
  34273. return rc;
  34274. }
  34275. /*
  34276. ** Recover the wal-index by reading the write-ahead log file.
  34277. **
  34278. ** This routine first tries to establish an exclusive lock on the
  34279. ** wal-index to prevent other threads/processes from doing anything
  34280. ** with the WAL or wal-index while recovery is running. The
  34281. ** WAL_RECOVER_LOCK is also held so that other threads will know
  34282. ** that this thread is running recovery. If unable to establish
  34283. ** the necessary locks, this routine returns SQLITE_BUSY.
  34284. */
  34285. static int walIndexRecover(Wal *pWal){
  34286. int rc; /* Return Code */
  34287. i64 nSize; /* Size of log file */
  34288. u32 aFrameCksum[2] = {0, 0};
  34289. int iLock; /* Lock offset to lock for checkpoint */
  34290. int nLock; /* Number of locks to hold */
  34291. /* Obtain an exclusive lock on all byte in the locking range not already
  34292. ** locked by the caller. The caller is guaranteed to have locked the
  34293. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  34294. ** If successful, the same bytes that are locked here are unlocked before
  34295. ** this function returns.
  34296. */
  34297. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  34298. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  34299. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  34300. assert( pWal->writeLock );
  34301. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  34302. nLock = SQLITE_SHM_NLOCK - iLock;
  34303. rc = walLockExclusive(pWal, iLock, nLock);
  34304. if( rc ){
  34305. return rc;
  34306. }
  34307. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  34308. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  34309. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  34310. if( rc!=SQLITE_OK ){
  34311. goto recovery_error;
  34312. }
  34313. if( nSize>WAL_HDRSIZE ){
  34314. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  34315. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  34316. int szFrame; /* Number of bytes in buffer aFrame[] */
  34317. u8 *aData; /* Pointer to data part of aFrame buffer */
  34318. int iFrame; /* Index of last frame read */
  34319. i64 iOffset; /* Next offset to read from log file */
  34320. int szPage; /* Page size according to the log */
  34321. u32 magic; /* Magic value read from WAL header */
  34322. u32 version; /* Magic value read from WAL header */
  34323. int isValid; /* True if this frame is valid */
  34324. /* Read in the WAL header. */
  34325. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  34326. if( rc!=SQLITE_OK ){
  34327. goto recovery_error;
  34328. }
  34329. /* If the database page size is not a power of two, or is greater than
  34330. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  34331. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  34332. ** WAL file.
  34333. */
  34334. magic = sqlite3Get4byte(&aBuf[0]);
  34335. szPage = sqlite3Get4byte(&aBuf[8]);
  34336. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  34337. || szPage&(szPage-1)
  34338. || szPage>SQLITE_MAX_PAGE_SIZE
  34339. || szPage<512
  34340. ){
  34341. goto finished;
  34342. }
  34343. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  34344. pWal->szPage = szPage;
  34345. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  34346. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  34347. /* Verify that the WAL header checksum is correct */
  34348. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  34349. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  34350. );
  34351. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  34352. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  34353. ){
  34354. goto finished;
  34355. }
  34356. /* Verify that the version number on the WAL format is one that
  34357. ** are able to understand */
  34358. version = sqlite3Get4byte(&aBuf[4]);
  34359. if( version!=WAL_MAX_VERSION ){
  34360. rc = SQLITE_CANTOPEN_BKPT;
  34361. goto finished;
  34362. }
  34363. /* Malloc a buffer to read frames into. */
  34364. szFrame = szPage + WAL_FRAME_HDRSIZE;
  34365. aFrame = (u8 *)sqlite3_malloc(szFrame);
  34366. if( !aFrame ){
  34367. rc = SQLITE_NOMEM;
  34368. goto recovery_error;
  34369. }
  34370. aData = &aFrame[WAL_FRAME_HDRSIZE];
  34371. /* Read all frames from the log file. */
  34372. iFrame = 0;
  34373. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  34374. u32 pgno; /* Database page number for frame */
  34375. u32 nTruncate; /* dbsize field from frame header */
  34376. /* Read and decode the next log frame. */
  34377. iFrame++;
  34378. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  34379. if( rc!=SQLITE_OK ) break;
  34380. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  34381. if( !isValid ) break;
  34382. rc = walIndexAppend(pWal, iFrame, pgno);
  34383. if( rc!=SQLITE_OK ) break;
  34384. /* If nTruncate is non-zero, this is a commit record. */
  34385. if( nTruncate ){
  34386. pWal->hdr.mxFrame = iFrame;
  34387. pWal->hdr.nPage = nTruncate;
  34388. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  34389. testcase( szPage<=32768 );
  34390. testcase( szPage>=65536 );
  34391. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  34392. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  34393. }
  34394. }
  34395. sqlite3_free(aFrame);
  34396. }
  34397. finished:
  34398. if( rc==SQLITE_OK ){
  34399. volatile WalCkptInfo *pInfo;
  34400. int i;
  34401. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  34402. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  34403. walIndexWriteHdr(pWal);
  34404. /* Reset the checkpoint-header. This is safe because this thread is
  34405. ** currently holding locks that exclude all other readers, writers and
  34406. ** checkpointers.
  34407. */
  34408. pInfo = walCkptInfo(pWal);
  34409. pInfo->nBackfill = 0;
  34410. pInfo->aReadMark[0] = 0;
  34411. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  34412. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  34413. /* If more than one frame was recovered from the log file, report an
  34414. ** event via sqlite3_log(). This is to help with identifying performance
  34415. ** problems caused by applications routinely shutting down without
  34416. ** checkpointing the log file.
  34417. */
  34418. if( pWal->hdr.nPage ){
  34419. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  34420. "recovered %d frames from WAL file %s",
  34421. pWal->hdr.mxFrame, pWal->zWalName
  34422. );
  34423. }
  34424. }
  34425. recovery_error:
  34426. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  34427. walUnlockExclusive(pWal, iLock, nLock);
  34428. return rc;
  34429. }
  34430. /*
  34431. ** Close an open wal-index.
  34432. */
  34433. static void walIndexClose(Wal *pWal, int isDelete){
  34434. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  34435. int i;
  34436. for(i=0; i<pWal->nWiData; i++){
  34437. sqlite3_free((void *)pWal->apWiData[i]);
  34438. pWal->apWiData[i] = 0;
  34439. }
  34440. }else{
  34441. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  34442. }
  34443. }
  34444. /*
  34445. ** Open a connection to the WAL file zWalName. The database file must
  34446. ** already be opened on connection pDbFd. The buffer that zWalName points
  34447. ** to must remain valid for the lifetime of the returned Wal* handle.
  34448. **
  34449. ** A SHARED lock should be held on the database file when this function
  34450. ** is called. The purpose of this SHARED lock is to prevent any other
  34451. ** client from unlinking the WAL or wal-index file. If another process
  34452. ** were to do this just after this client opened one of these files, the
  34453. ** system would be badly broken.
  34454. **
  34455. ** If the log file is successfully opened, SQLITE_OK is returned and
  34456. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  34457. ** an SQLite error code is returned and *ppWal is left unmodified.
  34458. */
  34459. SQLITE_PRIVATE int sqlite3WalOpen(
  34460. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  34461. sqlite3_file *pDbFd, /* The open database file */
  34462. const char *zWalName, /* Name of the WAL file */
  34463. int bNoShm, /* True to run in heap-memory mode */
  34464. i64 mxWalSize, /* Truncate WAL to this size on reset */
  34465. Wal **ppWal /* OUT: Allocated Wal handle */
  34466. ){
  34467. int rc; /* Return Code */
  34468. Wal *pRet; /* Object to allocate and return */
  34469. int flags; /* Flags passed to OsOpen() */
  34470. assert( zWalName && zWalName[0] );
  34471. assert( pDbFd );
  34472. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  34473. ** this source file. Verify that the #defines of the locking byte offsets
  34474. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  34475. */
  34476. #ifdef WIN_SHM_BASE
  34477. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  34478. #endif
  34479. #ifdef UNIX_SHM_BASE
  34480. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  34481. #endif
  34482. /* Allocate an instance of struct Wal to return. */
  34483. *ppWal = 0;
  34484. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  34485. if( !pRet ){
  34486. return SQLITE_NOMEM;
  34487. }
  34488. pRet->pVfs = pVfs;
  34489. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  34490. pRet->pDbFd = pDbFd;
  34491. pRet->readLock = -1;
  34492. pRet->mxWalSize = mxWalSize;
  34493. pRet->zWalName = zWalName;
  34494. pRet->syncHeader = 1;
  34495. pRet->padToSectorBoundary = 1;
  34496. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  34497. /* Open file handle on the write-ahead log file. */
  34498. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  34499. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  34500. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  34501. pRet->readOnly = WAL_RDONLY;
  34502. }
  34503. if( rc!=SQLITE_OK ){
  34504. walIndexClose(pRet, 0);
  34505. sqlite3OsClose(pRet->pWalFd);
  34506. sqlite3_free(pRet);
  34507. }else{
  34508. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  34509. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  34510. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  34511. pRet->padToSectorBoundary = 0;
  34512. }
  34513. *ppWal = pRet;
  34514. WALTRACE(("WAL%d: opened\n", pRet));
  34515. }
  34516. return rc;
  34517. }
  34518. /*
  34519. ** Change the size to which the WAL file is trucated on each reset.
  34520. */
  34521. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  34522. if( pWal ) pWal->mxWalSize = iLimit;
  34523. }
  34524. /*
  34525. ** Find the smallest page number out of all pages held in the WAL that
  34526. ** has not been returned by any prior invocation of this method on the
  34527. ** same WalIterator object. Write into *piFrame the frame index where
  34528. ** that page was last written into the WAL. Write into *piPage the page
  34529. ** number.
  34530. **
  34531. ** Return 0 on success. If there are no pages in the WAL with a page
  34532. ** number larger than *piPage, then return 1.
  34533. */
  34534. static int walIteratorNext(
  34535. WalIterator *p, /* Iterator */
  34536. u32 *piPage, /* OUT: The page number of the next page */
  34537. u32 *piFrame /* OUT: Wal frame index of next page */
  34538. ){
  34539. u32 iMin; /* Result pgno must be greater than iMin */
  34540. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  34541. int i; /* For looping through segments */
  34542. iMin = p->iPrior;
  34543. assert( iMin<0xffffffff );
  34544. for(i=p->nSegment-1; i>=0; i--){
  34545. struct WalSegment *pSegment = &p->aSegment[i];
  34546. while( pSegment->iNext<pSegment->nEntry ){
  34547. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  34548. if( iPg>iMin ){
  34549. if( iPg<iRet ){
  34550. iRet = iPg;
  34551. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  34552. }
  34553. break;
  34554. }
  34555. pSegment->iNext++;
  34556. }
  34557. }
  34558. *piPage = p->iPrior = iRet;
  34559. return (iRet==0xFFFFFFFF);
  34560. }
  34561. /*
  34562. ** This function merges two sorted lists into a single sorted list.
  34563. **
  34564. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  34565. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  34566. ** is guaranteed for all J<K:
  34567. **
  34568. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  34569. ** aContent[aRight[J]] < aContent[aRight[K]]
  34570. **
  34571. ** This routine overwrites aRight[] with a new (probably longer) sequence
  34572. ** of indices such that the aRight[] contains every index that appears in
  34573. ** either aLeft[] or the old aRight[] and such that the second condition
  34574. ** above is still met.
  34575. **
  34576. ** The aContent[aLeft[X]] values will be unique for all X. And the
  34577. ** aContent[aRight[X]] values will be unique too. But there might be
  34578. ** one or more combinations of X and Y such that
  34579. **
  34580. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  34581. **
  34582. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  34583. */
  34584. static void walMerge(
  34585. const u32 *aContent, /* Pages in wal - keys for the sort */
  34586. ht_slot *aLeft, /* IN: Left hand input list */
  34587. int nLeft, /* IN: Elements in array *paLeft */
  34588. ht_slot **paRight, /* IN/OUT: Right hand input list */
  34589. int *pnRight, /* IN/OUT: Elements in *paRight */
  34590. ht_slot *aTmp /* Temporary buffer */
  34591. ){
  34592. int iLeft = 0; /* Current index in aLeft */
  34593. int iRight = 0; /* Current index in aRight */
  34594. int iOut = 0; /* Current index in output buffer */
  34595. int nRight = *pnRight;
  34596. ht_slot *aRight = *paRight;
  34597. assert( nLeft>0 && nRight>0 );
  34598. while( iRight<nRight || iLeft<nLeft ){
  34599. ht_slot logpage;
  34600. Pgno dbpage;
  34601. if( (iLeft<nLeft)
  34602. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  34603. ){
  34604. logpage = aLeft[iLeft++];
  34605. }else{
  34606. logpage = aRight[iRight++];
  34607. }
  34608. dbpage = aContent[logpage];
  34609. aTmp[iOut++] = logpage;
  34610. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  34611. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  34612. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  34613. }
  34614. *paRight = aLeft;
  34615. *pnRight = iOut;
  34616. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  34617. }
  34618. /*
  34619. ** Sort the elements in list aList using aContent[] as the sort key.
  34620. ** Remove elements with duplicate keys, preferring to keep the
  34621. ** larger aList[] values.
  34622. **
  34623. ** The aList[] entries are indices into aContent[]. The values in
  34624. ** aList[] are to be sorted so that for all J<K:
  34625. **
  34626. ** aContent[aList[J]] < aContent[aList[K]]
  34627. **
  34628. ** For any X and Y such that
  34629. **
  34630. ** aContent[aList[X]] == aContent[aList[Y]]
  34631. **
  34632. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  34633. ** the smaller.
  34634. */
  34635. static void walMergesort(
  34636. const u32 *aContent, /* Pages in wal */
  34637. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  34638. ht_slot *aList, /* IN/OUT: List to sort */
  34639. int *pnList /* IN/OUT: Number of elements in aList[] */
  34640. ){
  34641. struct Sublist {
  34642. int nList; /* Number of elements in aList */
  34643. ht_slot *aList; /* Pointer to sub-list content */
  34644. };
  34645. const int nList = *pnList; /* Size of input list */
  34646. int nMerge = 0; /* Number of elements in list aMerge */
  34647. ht_slot *aMerge = 0; /* List to be merged */
  34648. int iList; /* Index into input list */
  34649. int iSub = 0; /* Index into aSub array */
  34650. struct Sublist aSub[13]; /* Array of sub-lists */
  34651. memset(aSub, 0, sizeof(aSub));
  34652. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  34653. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  34654. for(iList=0; iList<nList; iList++){
  34655. nMerge = 1;
  34656. aMerge = &aList[iList];
  34657. for(iSub=0; iList & (1<<iSub); iSub++){
  34658. struct Sublist *p = &aSub[iSub];
  34659. assert( p->aList && p->nList<=(1<<iSub) );
  34660. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  34661. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  34662. }
  34663. aSub[iSub].aList = aMerge;
  34664. aSub[iSub].nList = nMerge;
  34665. }
  34666. for(iSub++; iSub<ArraySize(aSub); iSub++){
  34667. if( nList & (1<<iSub) ){
  34668. struct Sublist *p = &aSub[iSub];
  34669. assert( p->nList<=(1<<iSub) );
  34670. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  34671. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  34672. }
  34673. }
  34674. assert( aMerge==aList );
  34675. *pnList = nMerge;
  34676. #ifdef SQLITE_DEBUG
  34677. {
  34678. int i;
  34679. for(i=1; i<*pnList; i++){
  34680. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  34681. }
  34682. }
  34683. #endif
  34684. }
  34685. /*
  34686. ** Free an iterator allocated by walIteratorInit().
  34687. */
  34688. static void walIteratorFree(WalIterator *p){
  34689. sqlite3ScratchFree(p);
  34690. }
  34691. /*
  34692. ** Construct a WalInterator object that can be used to loop over all
  34693. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  34694. ** lock.
  34695. **
  34696. ** On success, make *pp point to the newly allocated WalInterator object
  34697. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  34698. ** returns an error, the value of *pp is undefined.
  34699. **
  34700. ** The calling routine should invoke walIteratorFree() to destroy the
  34701. ** WalIterator object when it has finished with it.
  34702. */
  34703. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  34704. WalIterator *p; /* Return value */
  34705. int nSegment; /* Number of segments to merge */
  34706. u32 iLast; /* Last frame in log */
  34707. int nByte; /* Number of bytes to allocate */
  34708. int i; /* Iterator variable */
  34709. ht_slot *aTmp; /* Temp space used by merge-sort */
  34710. int rc = SQLITE_OK; /* Return Code */
  34711. /* This routine only runs while holding the checkpoint lock. And
  34712. ** it only runs if there is actually content in the log (mxFrame>0).
  34713. */
  34714. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  34715. iLast = pWal->hdr.mxFrame;
  34716. /* Allocate space for the WalIterator object. */
  34717. nSegment = walFramePage(iLast) + 1;
  34718. nByte = sizeof(WalIterator)
  34719. + (nSegment-1)*sizeof(struct WalSegment)
  34720. + iLast*sizeof(ht_slot);
  34721. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  34722. if( !p ){
  34723. return SQLITE_NOMEM;
  34724. }
  34725. memset(p, 0, nByte);
  34726. p->nSegment = nSegment;
  34727. /* Allocate temporary space used by the merge-sort routine. This block
  34728. ** of memory will be freed before this function returns.
  34729. */
  34730. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  34731. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  34732. );
  34733. if( !aTmp ){
  34734. rc = SQLITE_NOMEM;
  34735. }
  34736. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  34737. volatile ht_slot *aHash;
  34738. u32 iZero;
  34739. volatile u32 *aPgno;
  34740. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  34741. if( rc==SQLITE_OK ){
  34742. int j; /* Counter variable */
  34743. int nEntry; /* Number of entries in this segment */
  34744. ht_slot *aIndex; /* Sorted index for this segment */
  34745. aPgno++;
  34746. if( (i+1)==nSegment ){
  34747. nEntry = (int)(iLast - iZero);
  34748. }else{
  34749. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  34750. }
  34751. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  34752. iZero++;
  34753. for(j=0; j<nEntry; j++){
  34754. aIndex[j] = (ht_slot)j;
  34755. }
  34756. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  34757. p->aSegment[i].iZero = iZero;
  34758. p->aSegment[i].nEntry = nEntry;
  34759. p->aSegment[i].aIndex = aIndex;
  34760. p->aSegment[i].aPgno = (u32 *)aPgno;
  34761. }
  34762. }
  34763. sqlite3ScratchFree(aTmp);
  34764. if( rc!=SQLITE_OK ){
  34765. walIteratorFree(p);
  34766. }
  34767. *pp = p;
  34768. return rc;
  34769. }
  34770. /*
  34771. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  34772. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  34773. ** busy-handler function. Invoke it and retry the lock until either the
  34774. ** lock is successfully obtained or the busy-handler returns 0.
  34775. */
  34776. static int walBusyLock(
  34777. Wal *pWal, /* WAL connection */
  34778. int (*xBusy)(void*), /* Function to call when busy */
  34779. void *pBusyArg, /* Context argument for xBusyHandler */
  34780. int lockIdx, /* Offset of first byte to lock */
  34781. int n /* Number of bytes to lock */
  34782. ){
  34783. int rc;
  34784. do {
  34785. rc = walLockExclusive(pWal, lockIdx, n);
  34786. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  34787. return rc;
  34788. }
  34789. /*
  34790. ** The cache of the wal-index header must be valid to call this function.
  34791. ** Return the page-size in bytes used by the database.
  34792. */
  34793. static int walPagesize(Wal *pWal){
  34794. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  34795. }
  34796. /*
  34797. ** Copy as much content as we can from the WAL back into the database file
  34798. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  34799. **
  34800. ** The amount of information copies from WAL to database might be limited
  34801. ** by active readers. This routine will never overwrite a database page
  34802. ** that a concurrent reader might be using.
  34803. **
  34804. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  34805. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  34806. ** checkpoints are always run by a background thread or background
  34807. ** process, foreground threads will never block on a lengthy fsync call.
  34808. **
  34809. ** Fsync is called on the WAL before writing content out of the WAL and
  34810. ** into the database. This ensures that if the new content is persistent
  34811. ** in the WAL and can be recovered following a power-loss or hard reset.
  34812. **
  34813. ** Fsync is also called on the database file if (and only if) the entire
  34814. ** WAL content is copied into the database file. This second fsync makes
  34815. ** it safe to delete the WAL since the new content will persist in the
  34816. ** database file.
  34817. **
  34818. ** This routine uses and updates the nBackfill field of the wal-index header.
  34819. ** This is the only routine tha will increase the value of nBackfill.
  34820. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  34821. ** its value.)
  34822. **
  34823. ** The caller must be holding sufficient locks to ensure that no other
  34824. ** checkpoint is running (in any other thread or process) at the same
  34825. ** time.
  34826. */
  34827. static int walCheckpoint(
  34828. Wal *pWal, /* Wal connection */
  34829. int eMode, /* One of PASSIVE, FULL or RESTART */
  34830. int (*xBusyCall)(void*), /* Function to call when busy */
  34831. void *pBusyArg, /* Context argument for xBusyHandler */
  34832. int sync_flags, /* Flags for OsSync() (or 0) */
  34833. u8 *zBuf /* Temporary buffer to use */
  34834. ){
  34835. int rc; /* Return code */
  34836. int szPage; /* Database page-size */
  34837. WalIterator *pIter = 0; /* Wal iterator context */
  34838. u32 iDbpage = 0; /* Next database page to write */
  34839. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  34840. u32 mxSafeFrame; /* Max frame that can be backfilled */
  34841. u32 mxPage; /* Max database page to write */
  34842. int i; /* Loop counter */
  34843. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  34844. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  34845. szPage = walPagesize(pWal);
  34846. testcase( szPage<=32768 );
  34847. testcase( szPage>=65536 );
  34848. pInfo = walCkptInfo(pWal);
  34849. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  34850. /* Allocate the iterator */
  34851. rc = walIteratorInit(pWal, &pIter);
  34852. if( rc!=SQLITE_OK ){
  34853. return rc;
  34854. }
  34855. assert( pIter );
  34856. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  34857. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  34858. ** safe to write into the database. Frames beyond mxSafeFrame might
  34859. ** overwrite database pages that are in use by active readers and thus
  34860. ** cannot be backfilled from the WAL.
  34861. */
  34862. mxSafeFrame = pWal->hdr.mxFrame;
  34863. mxPage = pWal->hdr.nPage;
  34864. for(i=1; i<WAL_NREADER; i++){
  34865. u32 y = pInfo->aReadMark[i];
  34866. if( mxSafeFrame>y ){
  34867. assert( y<=pWal->hdr.mxFrame );
  34868. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  34869. if( rc==SQLITE_OK ){
  34870. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  34871. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  34872. }else if( rc==SQLITE_BUSY ){
  34873. mxSafeFrame = y;
  34874. xBusy = 0;
  34875. }else{
  34876. goto walcheckpoint_out;
  34877. }
  34878. }
  34879. }
  34880. if( pInfo->nBackfill<mxSafeFrame
  34881. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  34882. ){
  34883. i64 nSize; /* Current size of database file */
  34884. u32 nBackfill = pInfo->nBackfill;
  34885. /* Sync the WAL to disk */
  34886. if( sync_flags ){
  34887. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  34888. }
  34889. /* If the database may grow as a result of this checkpoint, hint
  34890. ** about the eventual size of the db file to the VFS layer.
  34891. */
  34892. if( rc==SQLITE_OK ){
  34893. i64 nReq = ((i64)mxPage * szPage);
  34894. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  34895. if( rc==SQLITE_OK && nSize<nReq ){
  34896. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  34897. }
  34898. }
  34899. /* Iterate through the contents of the WAL, copying data to the db file. */
  34900. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  34901. i64 iOffset;
  34902. assert( walFramePgno(pWal, iFrame)==iDbpage );
  34903. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  34904. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  34905. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  34906. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  34907. if( rc!=SQLITE_OK ) break;
  34908. iOffset = (iDbpage-1)*(i64)szPage;
  34909. testcase( IS_BIG_INT(iOffset) );
  34910. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  34911. if( rc!=SQLITE_OK ) break;
  34912. }
  34913. /* If work was actually accomplished... */
  34914. if( rc==SQLITE_OK ){
  34915. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  34916. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  34917. testcase( IS_BIG_INT(szDb) );
  34918. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  34919. if( rc==SQLITE_OK && sync_flags ){
  34920. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  34921. }
  34922. }
  34923. if( rc==SQLITE_OK ){
  34924. pInfo->nBackfill = mxSafeFrame;
  34925. }
  34926. }
  34927. /* Release the reader lock held while backfilling */
  34928. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  34929. }
  34930. if( rc==SQLITE_BUSY ){
  34931. /* Reset the return code so as not to report a checkpoint failure
  34932. ** just because there are active readers. */
  34933. rc = SQLITE_OK;
  34934. }
  34935. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  34936. ** file has been copied into the database file, then block until all
  34937. ** readers have finished using the wal file. This ensures that the next
  34938. ** process to write to the database restarts the wal file.
  34939. */
  34940. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  34941. assert( pWal->writeLock );
  34942. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  34943. rc = SQLITE_BUSY;
  34944. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  34945. assert( mxSafeFrame==pWal->hdr.mxFrame );
  34946. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  34947. if( rc==SQLITE_OK ){
  34948. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  34949. }
  34950. }
  34951. }
  34952. walcheckpoint_out:
  34953. walIteratorFree(pIter);
  34954. return rc;
  34955. }
  34956. /*
  34957. ** If the WAL file is currently larger than nMax bytes in size, truncate
  34958. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  34959. */
  34960. static void walLimitSize(Wal *pWal, i64 nMax){
  34961. i64 sz;
  34962. int rx;
  34963. sqlite3BeginBenignMalloc();
  34964. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  34965. if( rx==SQLITE_OK && (sz > nMax ) ){
  34966. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  34967. }
  34968. sqlite3EndBenignMalloc();
  34969. if( rx ){
  34970. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  34971. }
  34972. }
  34973. /*
  34974. ** Close a connection to a log file.
  34975. */
  34976. SQLITE_PRIVATE int sqlite3WalClose(
  34977. Wal *pWal, /* Wal to close */
  34978. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  34979. int nBuf,
  34980. u8 *zBuf /* Buffer of at least nBuf bytes */
  34981. ){
  34982. int rc = SQLITE_OK;
  34983. if( pWal ){
  34984. int isDelete = 0; /* True to unlink wal and wal-index files */
  34985. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  34986. ** ordinary, rollback-mode locking methods, this guarantees that the
  34987. ** connection associated with this log file is the only connection to
  34988. ** the database. In this case checkpoint the database and unlink both
  34989. ** the wal and wal-index files.
  34990. **
  34991. ** The EXCLUSIVE lock is not released before returning.
  34992. */
  34993. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  34994. if( rc==SQLITE_OK ){
  34995. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  34996. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  34997. }
  34998. rc = sqlite3WalCheckpoint(
  34999. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  35000. );
  35001. if( rc==SQLITE_OK ){
  35002. int bPersist = -1;
  35003. sqlite3OsFileControlHint(
  35004. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  35005. );
  35006. if( bPersist!=1 ){
  35007. /* Try to delete the WAL file if the checkpoint completed and
  35008. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  35009. ** mode (!bPersist) */
  35010. isDelete = 1;
  35011. }else if( pWal->mxWalSize>=0 ){
  35012. /* Try to truncate the WAL file to zero bytes if the checkpoint
  35013. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  35014. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  35015. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  35016. ** to zero bytes as truncating to the journal_size_limit might
  35017. ** leave a corrupt WAL file on disk. */
  35018. walLimitSize(pWal, 0);
  35019. }
  35020. }
  35021. }
  35022. walIndexClose(pWal, isDelete);
  35023. sqlite3OsClose(pWal->pWalFd);
  35024. if( isDelete ){
  35025. sqlite3BeginBenignMalloc();
  35026. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  35027. sqlite3EndBenignMalloc();
  35028. }
  35029. WALTRACE(("WAL%p: closed\n", pWal));
  35030. sqlite3_free((void *)pWal->apWiData);
  35031. sqlite3_free(pWal);
  35032. }
  35033. return rc;
  35034. }
  35035. /*
  35036. ** Try to read the wal-index header. Return 0 on success and 1 if
  35037. ** there is a problem.
  35038. **
  35039. ** The wal-index is in shared memory. Another thread or process might
  35040. ** be writing the header at the same time this procedure is trying to
  35041. ** read it, which might result in inconsistency. A dirty read is detected
  35042. ** by verifying that both copies of the header are the same and also by
  35043. ** a checksum on the header.
  35044. **
  35045. ** If and only if the read is consistent and the header is different from
  35046. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  35047. ** and *pChanged is set to 1.
  35048. **
  35049. ** If the checksum cannot be verified return non-zero. If the header
  35050. ** is read successfully and the checksum verified, return zero.
  35051. */
  35052. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  35053. u32 aCksum[2]; /* Checksum on the header content */
  35054. WalIndexHdr h1, h2; /* Two copies of the header content */
  35055. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  35056. /* The first page of the wal-index must be mapped at this point. */
  35057. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  35058. /* Read the header. This might happen concurrently with a write to the
  35059. ** same area of shared memory on a different CPU in a SMP,
  35060. ** meaning it is possible that an inconsistent snapshot is read
  35061. ** from the file. If this happens, return non-zero.
  35062. **
  35063. ** There are two copies of the header at the beginning of the wal-index.
  35064. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  35065. ** Memory barriers are used to prevent the compiler or the hardware from
  35066. ** reordering the reads and writes.
  35067. */
  35068. aHdr = walIndexHdr(pWal);
  35069. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  35070. walShmBarrier(pWal);
  35071. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  35072. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  35073. return 1; /* Dirty read */
  35074. }
  35075. if( h1.isInit==0 ){
  35076. return 1; /* Malformed header - probably all zeros */
  35077. }
  35078. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  35079. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  35080. return 1; /* Checksum does not match */
  35081. }
  35082. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  35083. *pChanged = 1;
  35084. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  35085. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  35086. testcase( pWal->szPage<=32768 );
  35087. testcase( pWal->szPage>=65536 );
  35088. }
  35089. /* The header was successfully read. Return zero. */
  35090. return 0;
  35091. }
  35092. /*
  35093. ** Read the wal-index header from the wal-index and into pWal->hdr.
  35094. ** If the wal-header appears to be corrupt, try to reconstruct the
  35095. ** wal-index from the WAL before returning.
  35096. **
  35097. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  35098. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  35099. ** to 0.
  35100. **
  35101. ** If the wal-index header is successfully read, return SQLITE_OK.
  35102. ** Otherwise an SQLite error code.
  35103. */
  35104. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  35105. int rc; /* Return code */
  35106. int badHdr; /* True if a header read failed */
  35107. volatile u32 *page0; /* Chunk of wal-index containing header */
  35108. /* Ensure that page 0 of the wal-index (the page that contains the
  35109. ** wal-index header) is mapped. Return early if an error occurs here.
  35110. */
  35111. assert( pChanged );
  35112. rc = walIndexPage(pWal, 0, &page0);
  35113. if( rc!=SQLITE_OK ){
  35114. return rc;
  35115. };
  35116. assert( page0 || pWal->writeLock==0 );
  35117. /* If the first page of the wal-index has been mapped, try to read the
  35118. ** wal-index header immediately, without holding any lock. This usually
  35119. ** works, but may fail if the wal-index header is corrupt or currently
  35120. ** being modified by another thread or process.
  35121. */
  35122. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  35123. /* If the first attempt failed, it might have been due to a race
  35124. ** with a writer. So get a WRITE lock and try again.
  35125. */
  35126. assert( badHdr==0 || pWal->writeLock==0 );
  35127. if( badHdr ){
  35128. if( pWal->readOnly & WAL_SHM_RDONLY ){
  35129. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  35130. walUnlockShared(pWal, WAL_WRITE_LOCK);
  35131. rc = SQLITE_READONLY_RECOVERY;
  35132. }
  35133. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  35134. pWal->writeLock = 1;
  35135. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  35136. badHdr = walIndexTryHdr(pWal, pChanged);
  35137. if( badHdr ){
  35138. /* If the wal-index header is still malformed even while holding
  35139. ** a WRITE lock, it can only mean that the header is corrupted and
  35140. ** needs to be reconstructed. So run recovery to do exactly that.
  35141. */
  35142. rc = walIndexRecover(pWal);
  35143. *pChanged = 1;
  35144. }
  35145. }
  35146. pWal->writeLock = 0;
  35147. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35148. }
  35149. }
  35150. /* If the header is read successfully, check the version number to make
  35151. ** sure the wal-index was not constructed with some future format that
  35152. ** this version of SQLite cannot understand.
  35153. */
  35154. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  35155. rc = SQLITE_CANTOPEN_BKPT;
  35156. }
  35157. return rc;
  35158. }
  35159. /*
  35160. ** This is the value that walTryBeginRead returns when it needs to
  35161. ** be retried.
  35162. */
  35163. #define WAL_RETRY (-1)
  35164. /*
  35165. ** Attempt to start a read transaction. This might fail due to a race or
  35166. ** other transient condition. When that happens, it returns WAL_RETRY to
  35167. ** indicate to the caller that it is safe to retry immediately.
  35168. **
  35169. ** On success return SQLITE_OK. On a permanent failure (such an
  35170. ** I/O error or an SQLITE_BUSY because another process is running
  35171. ** recovery) return a positive error code.
  35172. **
  35173. ** The useWal parameter is true to force the use of the WAL and disable
  35174. ** the case where the WAL is bypassed because it has been completely
  35175. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  35176. ** to make a copy of the wal-index header into pWal->hdr. If the
  35177. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  35178. ** to the caller that the local paget cache is obsolete and needs to be
  35179. ** flushed.) When useWal==1, the wal-index header is assumed to already
  35180. ** be loaded and the pChanged parameter is unused.
  35181. **
  35182. ** The caller must set the cnt parameter to the number of prior calls to
  35183. ** this routine during the current read attempt that returned WAL_RETRY.
  35184. ** This routine will start taking more aggressive measures to clear the
  35185. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  35186. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  35187. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  35188. ** and is not honoring the locking protocol. There is a vanishingly small
  35189. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  35190. ** bad luck when there is lots of contention for the wal-index, but that
  35191. ** possibility is so small that it can be safely neglected, we believe.
  35192. **
  35193. ** On success, this routine obtains a read lock on
  35194. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  35195. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  35196. ** that means the Wal does not hold any read lock. The reader must not
  35197. ** access any database page that is modified by a WAL frame up to and
  35198. ** including frame number aReadMark[pWal->readLock]. The reader will
  35199. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  35200. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  35201. ** completely and get all content directly from the database file.
  35202. ** If the useWal parameter is 1 then the WAL will never be ignored and
  35203. ** this routine will always set pWal->readLock>0 on success.
  35204. ** When the read transaction is completed, the caller must release the
  35205. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  35206. **
  35207. ** This routine uses the nBackfill and aReadMark[] fields of the header
  35208. ** to select a particular WAL_READ_LOCK() that strives to let the
  35209. ** checkpoint process do as much work as possible. This routine might
  35210. ** update values of the aReadMark[] array in the header, but if it does
  35211. ** so it takes care to hold an exclusive lock on the corresponding
  35212. ** WAL_READ_LOCK() while changing values.
  35213. */
  35214. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  35215. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  35216. u32 mxReadMark; /* Largest aReadMark[] value */
  35217. int mxI; /* Index of largest aReadMark[] value */
  35218. int i; /* Loop counter */
  35219. int rc = SQLITE_OK; /* Return code */
  35220. assert( pWal->readLock<0 ); /* Not currently locked */
  35221. /* Take steps to avoid spinning forever if there is a protocol error.
  35222. **
  35223. ** Circumstances that cause a RETRY should only last for the briefest
  35224. ** instances of time. No I/O or other system calls are done while the
  35225. ** locks are held, so the locks should not be held for very long. But
  35226. ** if we are unlucky, another process that is holding a lock might get
  35227. ** paged out or take a page-fault that is time-consuming to resolve,
  35228. ** during the few nanoseconds that it is holding the lock. In that case,
  35229. ** it might take longer than normal for the lock to free.
  35230. **
  35231. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  35232. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  35233. ** is more of a scheduler yield than an actual delay. But on the 10th
  35234. ** an subsequent retries, the delays start becoming longer and longer,
  35235. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  35236. ** The total delay time before giving up is less than 1 second.
  35237. */
  35238. if( cnt>5 ){
  35239. int nDelay = 1; /* Pause time in microseconds */
  35240. if( cnt>100 ){
  35241. VVA_ONLY( pWal->lockError = 1; )
  35242. return SQLITE_PROTOCOL;
  35243. }
  35244. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  35245. sqlite3OsSleep(pWal->pVfs, nDelay);
  35246. }
  35247. if( !useWal ){
  35248. rc = walIndexReadHdr(pWal, pChanged);
  35249. if( rc==SQLITE_BUSY ){
  35250. /* If there is not a recovery running in another thread or process
  35251. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  35252. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  35253. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  35254. ** would be technically correct. But the race is benign since with
  35255. ** WAL_RETRY this routine will be called again and will probably be
  35256. ** right on the second iteration.
  35257. */
  35258. if( pWal->apWiData[0]==0 ){
  35259. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  35260. ** We assume this is a transient condition, so return WAL_RETRY. The
  35261. ** xShmMap() implementation used by the default unix and win32 VFS
  35262. ** modules may return SQLITE_BUSY due to a race condition in the
  35263. ** code that determines whether or not the shared-memory region
  35264. ** must be zeroed before the requested page is returned.
  35265. */
  35266. rc = WAL_RETRY;
  35267. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  35268. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  35269. rc = WAL_RETRY;
  35270. }else if( rc==SQLITE_BUSY ){
  35271. rc = SQLITE_BUSY_RECOVERY;
  35272. }
  35273. }
  35274. if( rc!=SQLITE_OK ){
  35275. return rc;
  35276. }
  35277. }
  35278. pInfo = walCkptInfo(pWal);
  35279. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  35280. /* The WAL has been completely backfilled (or it is empty).
  35281. ** and can be safely ignored.
  35282. */
  35283. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  35284. walShmBarrier(pWal);
  35285. if( rc==SQLITE_OK ){
  35286. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  35287. /* It is not safe to allow the reader to continue here if frames
  35288. ** may have been appended to the log before READ_LOCK(0) was obtained.
  35289. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  35290. ** which implies that the database file contains a trustworthy
  35291. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  35292. ** happening, this is usually correct.
  35293. **
  35294. ** However, if frames have been appended to the log (or if the log
  35295. ** is wrapped and written for that matter) before the READ_LOCK(0)
  35296. ** is obtained, that is not necessarily true. A checkpointer may
  35297. ** have started to backfill the appended frames but crashed before
  35298. ** it finished. Leaving a corrupt image in the database file.
  35299. */
  35300. walUnlockShared(pWal, WAL_READ_LOCK(0));
  35301. return WAL_RETRY;
  35302. }
  35303. pWal->readLock = 0;
  35304. return SQLITE_OK;
  35305. }else if( rc!=SQLITE_BUSY ){
  35306. return rc;
  35307. }
  35308. }
  35309. /* If we get this far, it means that the reader will want to use
  35310. ** the WAL to get at content from recent commits. The job now is
  35311. ** to select one of the aReadMark[] entries that is closest to
  35312. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  35313. */
  35314. mxReadMark = 0;
  35315. mxI = 0;
  35316. for(i=1; i<WAL_NREADER; i++){
  35317. u32 thisMark = pInfo->aReadMark[i];
  35318. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  35319. assert( thisMark!=READMARK_NOT_USED );
  35320. mxReadMark = thisMark;
  35321. mxI = i;
  35322. }
  35323. }
  35324. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  35325. {
  35326. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  35327. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  35328. ){
  35329. for(i=1; i<WAL_NREADER; i++){
  35330. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  35331. if( rc==SQLITE_OK ){
  35332. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  35333. mxI = i;
  35334. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  35335. break;
  35336. }else if( rc!=SQLITE_BUSY ){
  35337. return rc;
  35338. }
  35339. }
  35340. }
  35341. if( mxI==0 ){
  35342. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  35343. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  35344. }
  35345. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  35346. if( rc ){
  35347. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  35348. }
  35349. /* Now that the read-lock has been obtained, check that neither the
  35350. ** value in the aReadMark[] array or the contents of the wal-index
  35351. ** header have changed.
  35352. **
  35353. ** It is necessary to check that the wal-index header did not change
  35354. ** between the time it was read and when the shared-lock was obtained
  35355. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  35356. ** that the log file may have been wrapped by a writer, or that frames
  35357. ** that occur later in the log than pWal->hdr.mxFrame may have been
  35358. ** copied into the database by a checkpointer. If either of these things
  35359. ** happened, then reading the database with the current value of
  35360. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  35361. ** instead.
  35362. **
  35363. ** This does not guarantee that the copy of the wal-index header is up to
  35364. ** date before proceeding. That would not be possible without somehow
  35365. ** blocking writers. It only guarantees that a dangerous checkpoint or
  35366. ** log-wrap (either of which would require an exclusive lock on
  35367. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  35368. */
  35369. walShmBarrier(pWal);
  35370. if( pInfo->aReadMark[mxI]!=mxReadMark
  35371. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  35372. ){
  35373. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  35374. return WAL_RETRY;
  35375. }else{
  35376. assert( mxReadMark<=pWal->hdr.mxFrame );
  35377. pWal->readLock = (i16)mxI;
  35378. }
  35379. }
  35380. return rc;
  35381. }
  35382. /*
  35383. ** Begin a read transaction on the database.
  35384. **
  35385. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  35386. ** it takes a snapshot of the state of the WAL and wal-index for the current
  35387. ** instant in time. The current thread will continue to use this snapshot.
  35388. ** Other threads might append new content to the WAL and wal-index but
  35389. ** that extra content is ignored by the current thread.
  35390. **
  35391. ** If the database contents have changes since the previous read
  35392. ** transaction, then *pChanged is set to 1 before returning. The
  35393. ** Pager layer will use this to know that is cache is stale and
  35394. ** needs to be flushed.
  35395. */
  35396. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  35397. int rc; /* Return code */
  35398. int cnt = 0; /* Number of TryBeginRead attempts */
  35399. do{
  35400. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  35401. }while( rc==WAL_RETRY );
  35402. testcase( (rc&0xff)==SQLITE_BUSY );
  35403. testcase( (rc&0xff)==SQLITE_IOERR );
  35404. testcase( rc==SQLITE_PROTOCOL );
  35405. testcase( rc==SQLITE_OK );
  35406. return rc;
  35407. }
  35408. /*
  35409. ** Finish with a read transaction. All this does is release the
  35410. ** read-lock.
  35411. */
  35412. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  35413. sqlite3WalEndWriteTransaction(pWal);
  35414. if( pWal->readLock>=0 ){
  35415. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  35416. pWal->readLock = -1;
  35417. }
  35418. }
  35419. /*
  35420. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  35421. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  35422. ** to zero.
  35423. **
  35424. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  35425. ** error does occur, the final value of *piRead is undefined.
  35426. */
  35427. SQLITE_PRIVATE int sqlite3WalFindFrame(
  35428. Wal *pWal, /* WAL handle */
  35429. Pgno pgno, /* Database page number to read data for */
  35430. u32 *piRead /* OUT: Frame number (or zero) */
  35431. ){
  35432. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  35433. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  35434. int iHash; /* Used to loop through N hash tables */
  35435. /* This routine is only be called from within a read transaction. */
  35436. assert( pWal->readLock>=0 || pWal->lockError );
  35437. /* If the "last page" field of the wal-index header snapshot is 0, then
  35438. ** no data will be read from the wal under any circumstances. Return early
  35439. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  35440. ** then the WAL is ignored by the reader so return early, as if the
  35441. ** WAL were empty.
  35442. */
  35443. if( iLast==0 || pWal->readLock==0 ){
  35444. *piRead = 0;
  35445. return SQLITE_OK;
  35446. }
  35447. /* Search the hash table or tables for an entry matching page number
  35448. ** pgno. Each iteration of the following for() loop searches one
  35449. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  35450. **
  35451. ** This code might run concurrently to the code in walIndexAppend()
  35452. ** that adds entries to the wal-index (and possibly to this hash
  35453. ** table). This means the value just read from the hash
  35454. ** slot (aHash[iKey]) may have been added before or after the
  35455. ** current read transaction was opened. Values added after the
  35456. ** read transaction was opened may have been written incorrectly -
  35457. ** i.e. these slots may contain garbage data. However, we assume
  35458. ** that any slots written before the current read transaction was
  35459. ** opened remain unmodified.
  35460. **
  35461. ** For the reasons above, the if(...) condition featured in the inner
  35462. ** loop of the following block is more stringent that would be required
  35463. ** if we had exclusive access to the hash-table:
  35464. **
  35465. ** (aPgno[iFrame]==pgno):
  35466. ** This condition filters out normal hash-table collisions.
  35467. **
  35468. ** (iFrame<=iLast):
  35469. ** This condition filters out entries that were added to the hash
  35470. ** table after the current read-transaction had started.
  35471. */
  35472. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  35473. volatile ht_slot *aHash; /* Pointer to hash table */
  35474. volatile u32 *aPgno; /* Pointer to array of page numbers */
  35475. u32 iZero; /* Frame number corresponding to aPgno[0] */
  35476. int iKey; /* Hash slot index */
  35477. int nCollide; /* Number of hash collisions remaining */
  35478. int rc; /* Error code */
  35479. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  35480. if( rc!=SQLITE_OK ){
  35481. return rc;
  35482. }
  35483. nCollide = HASHTABLE_NSLOT;
  35484. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  35485. u32 iFrame = aHash[iKey] + iZero;
  35486. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  35487. /* assert( iFrame>iRead ); -- not true if there is corruption */
  35488. iRead = iFrame;
  35489. }
  35490. if( (nCollide--)==0 ){
  35491. return SQLITE_CORRUPT_BKPT;
  35492. }
  35493. }
  35494. }
  35495. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  35496. /* If expensive assert() statements are available, do a linear search
  35497. ** of the wal-index file content. Make sure the results agree with the
  35498. ** result obtained using the hash indexes above. */
  35499. {
  35500. u32 iRead2 = 0;
  35501. u32 iTest;
  35502. for(iTest=iLast; iTest>0; iTest--){
  35503. if( walFramePgno(pWal, iTest)==pgno ){
  35504. iRead2 = iTest;
  35505. break;
  35506. }
  35507. }
  35508. assert( iRead==iRead2 );
  35509. }
  35510. #endif
  35511. *piRead = iRead;
  35512. return SQLITE_OK;
  35513. }
  35514. /*
  35515. ** Read the contents of frame iRead from the wal file into buffer pOut
  35516. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  35517. ** error code otherwise.
  35518. */
  35519. SQLITE_PRIVATE int sqlite3WalReadFrame(
  35520. Wal *pWal, /* WAL handle */
  35521. u32 iRead, /* Frame to read */
  35522. int nOut, /* Size of buffer pOut in bytes */
  35523. u8 *pOut /* Buffer to write page data to */
  35524. ){
  35525. int sz;
  35526. i64 iOffset;
  35527. sz = pWal->hdr.szPage;
  35528. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  35529. testcase( sz<=32768 );
  35530. testcase( sz>=65536 );
  35531. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  35532. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  35533. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  35534. }
  35535. /*
  35536. ** Return the size of the database in pages (or zero, if unknown).
  35537. */
  35538. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  35539. if( pWal && ALWAYS(pWal->readLock>=0) ){
  35540. return pWal->hdr.nPage;
  35541. }
  35542. return 0;
  35543. }
  35544. /*
  35545. ** This function starts a write transaction on the WAL.
  35546. **
  35547. ** A read transaction must have already been started by a prior call
  35548. ** to sqlite3WalBeginReadTransaction().
  35549. **
  35550. ** If another thread or process has written into the database since
  35551. ** the read transaction was started, then it is not possible for this
  35552. ** thread to write as doing so would cause a fork. So this routine
  35553. ** returns SQLITE_BUSY in that case and no write transaction is started.
  35554. **
  35555. ** There can only be a single writer active at a time.
  35556. */
  35557. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  35558. int rc;
  35559. /* Cannot start a write transaction without first holding a read
  35560. ** transaction. */
  35561. assert( pWal->readLock>=0 );
  35562. if( pWal->readOnly ){
  35563. return SQLITE_READONLY;
  35564. }
  35565. /* Only one writer allowed at a time. Get the write lock. Return
  35566. ** SQLITE_BUSY if unable.
  35567. */
  35568. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35569. if( rc ){
  35570. return rc;
  35571. }
  35572. pWal->writeLock = 1;
  35573. /* If another connection has written to the database file since the
  35574. ** time the read transaction on this connection was started, then
  35575. ** the write is disallowed.
  35576. */
  35577. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  35578. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35579. pWal->writeLock = 0;
  35580. rc = SQLITE_BUSY_SNAPSHOT;
  35581. }
  35582. return rc;
  35583. }
  35584. /*
  35585. ** End a write transaction. The commit has already been done. This
  35586. ** routine merely releases the lock.
  35587. */
  35588. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  35589. if( pWal->writeLock ){
  35590. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  35591. pWal->writeLock = 0;
  35592. pWal->truncateOnCommit = 0;
  35593. }
  35594. return SQLITE_OK;
  35595. }
  35596. /*
  35597. ** If any data has been written (but not committed) to the log file, this
  35598. ** function moves the write-pointer back to the start of the transaction.
  35599. **
  35600. ** Additionally, the callback function is invoked for each frame written
  35601. ** to the WAL since the start of the transaction. If the callback returns
  35602. ** other than SQLITE_OK, it is not invoked again and the error code is
  35603. ** returned to the caller.
  35604. **
  35605. ** Otherwise, if the callback function does not return an error, this
  35606. ** function returns SQLITE_OK.
  35607. */
  35608. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  35609. int rc = SQLITE_OK;
  35610. if( ALWAYS(pWal->writeLock) ){
  35611. Pgno iMax = pWal->hdr.mxFrame;
  35612. Pgno iFrame;
  35613. /* Restore the clients cache of the wal-index header to the state it
  35614. ** was in before the client began writing to the database.
  35615. */
  35616. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  35617. for(iFrame=pWal->hdr.mxFrame+1;
  35618. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  35619. iFrame++
  35620. ){
  35621. /* This call cannot fail. Unless the page for which the page number
  35622. ** is passed as the second argument is (a) in the cache and
  35623. ** (b) has an outstanding reference, then xUndo is either a no-op
  35624. ** (if (a) is false) or simply expels the page from the cache (if (b)
  35625. ** is false).
  35626. **
  35627. ** If the upper layer is doing a rollback, it is guaranteed that there
  35628. ** are no outstanding references to any page other than page 1. And
  35629. ** page 1 is never written to the log until the transaction is
  35630. ** committed. As a result, the call to xUndo may not fail.
  35631. */
  35632. assert( walFramePgno(pWal, iFrame)!=1 );
  35633. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  35634. }
  35635. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  35636. }
  35637. assert( rc==SQLITE_OK );
  35638. return rc;
  35639. }
  35640. /*
  35641. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  35642. ** values. This function populates the array with values required to
  35643. ** "rollback" the write position of the WAL handle back to the current
  35644. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  35645. */
  35646. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  35647. assert( pWal->writeLock );
  35648. aWalData[0] = pWal->hdr.mxFrame;
  35649. aWalData[1] = pWal->hdr.aFrameCksum[0];
  35650. aWalData[2] = pWal->hdr.aFrameCksum[1];
  35651. aWalData[3] = pWal->nCkpt;
  35652. }
  35653. /*
  35654. ** Move the write position of the WAL back to the point identified by
  35655. ** the values in the aWalData[] array. aWalData must point to an array
  35656. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  35657. ** by a call to WalSavepoint().
  35658. */
  35659. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  35660. int rc = SQLITE_OK;
  35661. assert( pWal->writeLock );
  35662. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  35663. if( aWalData[3]!=pWal->nCkpt ){
  35664. /* This savepoint was opened immediately after the write-transaction
  35665. ** was started. Right after that, the writer decided to wrap around
  35666. ** to the start of the log. Update the savepoint values to match.
  35667. */
  35668. aWalData[0] = 0;
  35669. aWalData[3] = pWal->nCkpt;
  35670. }
  35671. if( aWalData[0]<pWal->hdr.mxFrame ){
  35672. pWal->hdr.mxFrame = aWalData[0];
  35673. pWal->hdr.aFrameCksum[0] = aWalData[1];
  35674. pWal->hdr.aFrameCksum[1] = aWalData[2];
  35675. walCleanupHash(pWal);
  35676. }
  35677. return rc;
  35678. }
  35679. /*
  35680. ** This function is called just before writing a set of frames to the log
  35681. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  35682. ** to the current log file, it is possible to overwrite the start of the
  35683. ** existing log file with the new frames (i.e. "reset" the log). If so,
  35684. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  35685. ** unchanged.
  35686. **
  35687. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  35688. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  35689. ** if an error occurs.
  35690. */
  35691. static int walRestartLog(Wal *pWal){
  35692. int rc = SQLITE_OK;
  35693. int cnt;
  35694. if( pWal->readLock==0 ){
  35695. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  35696. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  35697. if( pInfo->nBackfill>0 ){
  35698. u32 salt1;
  35699. sqlite3_randomness(4, &salt1);
  35700. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  35701. if( rc==SQLITE_OK ){
  35702. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  35703. ** readers are currently using the WAL), then the transactions
  35704. ** frames will overwrite the start of the existing log. Update the
  35705. ** wal-index header to reflect this.
  35706. **
  35707. ** In theory it would be Ok to update the cache of the header only
  35708. ** at this point. But updating the actual wal-index header is also
  35709. ** safe and means there is no special case for sqlite3WalUndo()
  35710. ** to handle if this transaction is rolled back.
  35711. */
  35712. int i; /* Loop counter */
  35713. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  35714. pWal->nCkpt++;
  35715. pWal->hdr.mxFrame = 0;
  35716. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  35717. aSalt[1] = salt1;
  35718. walIndexWriteHdr(pWal);
  35719. pInfo->nBackfill = 0;
  35720. pInfo->aReadMark[1] = 0;
  35721. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  35722. assert( pInfo->aReadMark[0]==0 );
  35723. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  35724. }else if( rc!=SQLITE_BUSY ){
  35725. return rc;
  35726. }
  35727. }
  35728. walUnlockShared(pWal, WAL_READ_LOCK(0));
  35729. pWal->readLock = -1;
  35730. cnt = 0;
  35731. do{
  35732. int notUsed;
  35733. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  35734. }while( rc==WAL_RETRY );
  35735. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  35736. testcase( (rc&0xff)==SQLITE_IOERR );
  35737. testcase( rc==SQLITE_PROTOCOL );
  35738. testcase( rc==SQLITE_OK );
  35739. }
  35740. return rc;
  35741. }
  35742. /*
  35743. ** Information about the current state of the WAL file and where
  35744. ** the next fsync should occur - passed from sqlite3WalFrames() into
  35745. ** walWriteToLog().
  35746. */
  35747. typedef struct WalWriter {
  35748. Wal *pWal; /* The complete WAL information */
  35749. sqlite3_file *pFd; /* The WAL file to which we write */
  35750. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  35751. int syncFlags; /* Flags for the fsync */
  35752. int szPage; /* Size of one page */
  35753. } WalWriter;
  35754. /*
  35755. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  35756. ** Do a sync when crossing the p->iSyncPoint boundary.
  35757. **
  35758. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  35759. ** first write the part before iSyncPoint, then sync, then write the
  35760. ** rest.
  35761. */
  35762. static int walWriteToLog(
  35763. WalWriter *p, /* WAL to write to */
  35764. void *pContent, /* Content to be written */
  35765. int iAmt, /* Number of bytes to write */
  35766. sqlite3_int64 iOffset /* Start writing at this offset */
  35767. ){
  35768. int rc;
  35769. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  35770. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  35771. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  35772. if( rc ) return rc;
  35773. iOffset += iFirstAmt;
  35774. iAmt -= iFirstAmt;
  35775. pContent = (void*)(iFirstAmt + (char*)pContent);
  35776. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  35777. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  35778. if( iAmt==0 || rc ) return rc;
  35779. }
  35780. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  35781. return rc;
  35782. }
  35783. /*
  35784. ** Write out a single frame of the WAL
  35785. */
  35786. static int walWriteOneFrame(
  35787. WalWriter *p, /* Where to write the frame */
  35788. PgHdr *pPage, /* The page of the frame to be written */
  35789. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  35790. sqlite3_int64 iOffset /* Byte offset at which to write */
  35791. ){
  35792. int rc; /* Result code from subfunctions */
  35793. void *pData; /* Data actually written */
  35794. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  35795. #if defined(SQLITE_HAS_CODEC)
  35796. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  35797. #else
  35798. pData = pPage->pData;
  35799. #endif
  35800. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  35801. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  35802. if( rc ) return rc;
  35803. /* Write the page data */
  35804. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  35805. return rc;
  35806. }
  35807. /*
  35808. ** Write a set of frames to the log. The caller must hold the write-lock
  35809. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  35810. */
  35811. SQLITE_PRIVATE int sqlite3WalFrames(
  35812. Wal *pWal, /* Wal handle to write to */
  35813. int szPage, /* Database page-size in bytes */
  35814. PgHdr *pList, /* List of dirty pages to write */
  35815. Pgno nTruncate, /* Database size after this commit */
  35816. int isCommit, /* True if this is a commit */
  35817. int sync_flags /* Flags to pass to OsSync() (or 0) */
  35818. ){
  35819. int rc; /* Used to catch return codes */
  35820. u32 iFrame; /* Next frame address */
  35821. PgHdr *p; /* Iterator to run through pList with. */
  35822. PgHdr *pLast = 0; /* Last frame in list */
  35823. int nExtra = 0; /* Number of extra copies of last page */
  35824. int szFrame; /* The size of a single frame */
  35825. i64 iOffset; /* Next byte to write in WAL file */
  35826. WalWriter w; /* The writer */
  35827. assert( pList );
  35828. assert( pWal->writeLock );
  35829. /* If this frame set completes a transaction, then nTruncate>0. If
  35830. ** nTruncate==0 then this frame set does not complete the transaction. */
  35831. assert( (isCommit!=0)==(nTruncate!=0) );
  35832. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  35833. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  35834. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  35835. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  35836. }
  35837. #endif
  35838. /* See if it is possible to write these frames into the start of the
  35839. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  35840. */
  35841. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  35842. return rc;
  35843. }
  35844. /* If this is the first frame written into the log, write the WAL
  35845. ** header to the start of the WAL file. See comments at the top of
  35846. ** this source file for a description of the WAL header format.
  35847. */
  35848. iFrame = pWal->hdr.mxFrame;
  35849. if( iFrame==0 ){
  35850. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  35851. u32 aCksum[2]; /* Checksum for wal-header */
  35852. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  35853. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  35854. sqlite3Put4byte(&aWalHdr[8], szPage);
  35855. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  35856. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  35857. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  35858. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  35859. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  35860. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  35861. pWal->szPage = szPage;
  35862. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  35863. pWal->hdr.aFrameCksum[0] = aCksum[0];
  35864. pWal->hdr.aFrameCksum[1] = aCksum[1];
  35865. pWal->truncateOnCommit = 1;
  35866. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  35867. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  35868. if( rc!=SQLITE_OK ){
  35869. return rc;
  35870. }
  35871. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  35872. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  35873. ** an out-of-order write following a WAL restart could result in
  35874. ** database corruption. See the ticket:
  35875. **
  35876. ** http://localhost:591/sqlite/info/ff5be73dee
  35877. */
  35878. if( pWal->syncHeader && sync_flags ){
  35879. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  35880. if( rc ) return rc;
  35881. }
  35882. }
  35883. assert( (int)pWal->szPage==szPage );
  35884. /* Setup information needed to write frames into the WAL */
  35885. w.pWal = pWal;
  35886. w.pFd = pWal->pWalFd;
  35887. w.iSyncPoint = 0;
  35888. w.syncFlags = sync_flags;
  35889. w.szPage = szPage;
  35890. iOffset = walFrameOffset(iFrame+1, szPage);
  35891. szFrame = szPage + WAL_FRAME_HDRSIZE;
  35892. /* Write all frames into the log file exactly once */
  35893. for(p=pList; p; p=p->pDirty){
  35894. int nDbSize; /* 0 normally. Positive == commit flag */
  35895. iFrame++;
  35896. assert( iOffset==walFrameOffset(iFrame, szPage) );
  35897. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  35898. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  35899. if( rc ) return rc;
  35900. pLast = p;
  35901. iOffset += szFrame;
  35902. }
  35903. /* If this is the end of a transaction, then we might need to pad
  35904. ** the transaction and/or sync the WAL file.
  35905. **
  35906. ** Padding and syncing only occur if this set of frames complete a
  35907. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  35908. ** or synchonous==OFF, then no padding or syncing are needed.
  35909. **
  35910. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  35911. ** needed and only the sync is done. If padding is needed, then the
  35912. ** final frame is repeated (with its commit mark) until the next sector
  35913. ** boundary is crossed. Only the part of the WAL prior to the last
  35914. ** sector boundary is synced; the part of the last frame that extends
  35915. ** past the sector boundary is written after the sync.
  35916. */
  35917. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  35918. if( pWal->padToSectorBoundary ){
  35919. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  35920. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  35921. while( iOffset<w.iSyncPoint ){
  35922. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  35923. if( rc ) return rc;
  35924. iOffset += szFrame;
  35925. nExtra++;
  35926. }
  35927. }else{
  35928. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  35929. }
  35930. }
  35931. /* If this frame set completes the first transaction in the WAL and
  35932. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  35933. ** journal size limit, if possible.
  35934. */
  35935. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  35936. i64 sz = pWal->mxWalSize;
  35937. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  35938. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  35939. }
  35940. walLimitSize(pWal, sz);
  35941. pWal->truncateOnCommit = 0;
  35942. }
  35943. /* Append data to the wal-index. It is not necessary to lock the
  35944. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  35945. ** guarantees that there are no other writers, and no data that may
  35946. ** be in use by existing readers is being overwritten.
  35947. */
  35948. iFrame = pWal->hdr.mxFrame;
  35949. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  35950. iFrame++;
  35951. rc = walIndexAppend(pWal, iFrame, p->pgno);
  35952. }
  35953. while( rc==SQLITE_OK && nExtra>0 ){
  35954. iFrame++;
  35955. nExtra--;
  35956. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  35957. }
  35958. if( rc==SQLITE_OK ){
  35959. /* Update the private copy of the header. */
  35960. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  35961. testcase( szPage<=32768 );
  35962. testcase( szPage>=65536 );
  35963. pWal->hdr.mxFrame = iFrame;
  35964. if( isCommit ){
  35965. pWal->hdr.iChange++;
  35966. pWal->hdr.nPage = nTruncate;
  35967. }
  35968. /* If this is a commit, update the wal-index header too. */
  35969. if( isCommit ){
  35970. walIndexWriteHdr(pWal);
  35971. pWal->iCallback = iFrame;
  35972. }
  35973. }
  35974. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  35975. return rc;
  35976. }
  35977. /*
  35978. ** This routine is called to implement sqlite3_wal_checkpoint() and
  35979. ** related interfaces.
  35980. **
  35981. ** Obtain a CHECKPOINT lock and then backfill as much information as
  35982. ** we can from WAL into the database.
  35983. **
  35984. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  35985. ** callback. In this case this function runs a blocking checkpoint.
  35986. */
  35987. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  35988. Wal *pWal, /* Wal connection */
  35989. int eMode, /* PASSIVE, FULL or RESTART */
  35990. int (*xBusy)(void*), /* Function to call when busy */
  35991. void *pBusyArg, /* Context argument for xBusyHandler */
  35992. int sync_flags, /* Flags to sync db file with (or 0) */
  35993. int nBuf, /* Size of temporary buffer */
  35994. u8 *zBuf, /* Temporary buffer to use */
  35995. int *pnLog, /* OUT: Number of frames in WAL */
  35996. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  35997. ){
  35998. int rc; /* Return code */
  35999. int isChanged = 0; /* True if a new wal-index header is loaded */
  36000. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  36001. assert( pWal->ckptLock==0 );
  36002. assert( pWal->writeLock==0 );
  36003. if( pWal->readOnly ) return SQLITE_READONLY;
  36004. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  36005. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  36006. if( rc ){
  36007. /* Usually this is SQLITE_BUSY meaning that another thread or process
  36008. ** is already running a checkpoint, or maybe a recovery. But it might
  36009. ** also be SQLITE_IOERR. */
  36010. return rc;
  36011. }
  36012. pWal->ckptLock = 1;
  36013. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  36014. ** to prevent any writers from running while the checkpoint is underway.
  36015. ** This has to be done before the call to walIndexReadHdr() below.
  36016. **
  36017. ** If the writer lock cannot be obtained, then a passive checkpoint is
  36018. ** run instead. Since the checkpointer is not holding the writer lock,
  36019. ** there is no point in blocking waiting for any readers. Assuming no
  36020. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  36021. */
  36022. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  36023. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  36024. if( rc==SQLITE_OK ){
  36025. pWal->writeLock = 1;
  36026. }else if( rc==SQLITE_BUSY ){
  36027. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  36028. rc = SQLITE_OK;
  36029. }
  36030. }
  36031. /* Read the wal-index header. */
  36032. if( rc==SQLITE_OK ){
  36033. rc = walIndexReadHdr(pWal, &isChanged);
  36034. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  36035. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  36036. }
  36037. }
  36038. /* Copy data from the log to the database file. */
  36039. if( rc==SQLITE_OK ){
  36040. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  36041. rc = SQLITE_CORRUPT_BKPT;
  36042. }else{
  36043. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  36044. }
  36045. /* If no error occurred, set the output variables. */
  36046. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  36047. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  36048. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  36049. }
  36050. }
  36051. if( isChanged ){
  36052. /* If a new wal-index header was loaded before the checkpoint was
  36053. ** performed, then the pager-cache associated with pWal is now
  36054. ** out of date. So zero the cached wal-index header to ensure that
  36055. ** next time the pager opens a snapshot on this database it knows that
  36056. ** the cache needs to be reset.
  36057. */
  36058. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  36059. }
  36060. /* Release the locks. */
  36061. sqlite3WalEndWriteTransaction(pWal);
  36062. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  36063. pWal->ckptLock = 0;
  36064. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  36065. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  36066. }
  36067. /* Return the value to pass to a sqlite3_wal_hook callback, the
  36068. ** number of frames in the WAL at the point of the last commit since
  36069. ** sqlite3WalCallback() was called. If no commits have occurred since
  36070. ** the last call, then return 0.
  36071. */
  36072. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  36073. u32 ret = 0;
  36074. if( pWal ){
  36075. ret = pWal->iCallback;
  36076. pWal->iCallback = 0;
  36077. }
  36078. return (int)ret;
  36079. }
  36080. /*
  36081. ** This function is called to change the WAL subsystem into or out
  36082. ** of locking_mode=EXCLUSIVE.
  36083. **
  36084. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  36085. ** into locking_mode=NORMAL. This means that we must acquire a lock
  36086. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  36087. ** or if the acquisition of the lock fails, then return 0. If the
  36088. ** transition out of exclusive-mode is successful, return 1. This
  36089. ** operation must occur while the pager is still holding the exclusive
  36090. ** lock on the main database file.
  36091. **
  36092. ** If op is one, then change from locking_mode=NORMAL into
  36093. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  36094. ** be released. Return 1 if the transition is made and 0 if the
  36095. ** WAL is already in exclusive-locking mode - meaning that this
  36096. ** routine is a no-op. The pager must already hold the exclusive lock
  36097. ** on the main database file before invoking this operation.
  36098. **
  36099. ** If op is negative, then do a dry-run of the op==1 case but do
  36100. ** not actually change anything. The pager uses this to see if it
  36101. ** should acquire the database exclusive lock prior to invoking
  36102. ** the op==1 case.
  36103. */
  36104. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  36105. int rc;
  36106. assert( pWal->writeLock==0 );
  36107. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  36108. /* pWal->readLock is usually set, but might be -1 if there was a
  36109. ** prior error while attempting to acquire are read-lock. This cannot
  36110. ** happen if the connection is actually in exclusive mode (as no xShmLock
  36111. ** locks are taken in this case). Nor should the pager attempt to
  36112. ** upgrade to exclusive-mode following such an error.
  36113. */
  36114. assert( pWal->readLock>=0 || pWal->lockError );
  36115. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  36116. if( op==0 ){
  36117. if( pWal->exclusiveMode ){
  36118. pWal->exclusiveMode = 0;
  36119. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  36120. pWal->exclusiveMode = 1;
  36121. }
  36122. rc = pWal->exclusiveMode==0;
  36123. }else{
  36124. /* Already in locking_mode=NORMAL */
  36125. rc = 0;
  36126. }
  36127. }else if( op>0 ){
  36128. assert( pWal->exclusiveMode==0 );
  36129. assert( pWal->readLock>=0 );
  36130. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  36131. pWal->exclusiveMode = 1;
  36132. rc = 1;
  36133. }else{
  36134. rc = pWal->exclusiveMode==0;
  36135. }
  36136. return rc;
  36137. }
  36138. /*
  36139. ** Return true if the argument is non-NULL and the WAL module is using
  36140. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  36141. ** WAL module is using shared-memory, return false.
  36142. */
  36143. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  36144. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  36145. }
  36146. #ifdef SQLITE_ENABLE_ZIPVFS
  36147. /*
  36148. ** If the argument is not NULL, it points to a Wal object that holds a
  36149. ** read-lock. This function returns the database page-size if it is known,
  36150. ** or zero if it is not (or if pWal is NULL).
  36151. */
  36152. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  36153. assert( pWal==0 || pWal->readLock>=0 );
  36154. return (pWal ? pWal->szPage : 0);
  36155. }
  36156. #endif
  36157. #endif /* #ifndef SQLITE_OMIT_WAL */
  36158. /************** End of wal.c *************************************************/
  36159. /************** Begin file btmutex.c *****************************************/
  36160. /*
  36161. ** 2007 August 27
  36162. **
  36163. ** The author disclaims copyright to this source code. In place of
  36164. ** a legal notice, here is a blessing:
  36165. **
  36166. ** May you do good and not evil.
  36167. ** May you find forgiveness for yourself and forgive others.
  36168. ** May you share freely, never taking more than you give.
  36169. **
  36170. *************************************************************************
  36171. **
  36172. ** This file contains code used to implement mutexes on Btree objects.
  36173. ** This code really belongs in btree.c. But btree.c is getting too
  36174. ** big and we want to break it down some. This packaged seemed like
  36175. ** a good breakout.
  36176. */
  36177. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  36178. /************** Begin file btreeInt.h ****************************************/
  36179. /*
  36180. ** 2004 April 6
  36181. **
  36182. ** The author disclaims copyright to this source code. In place of
  36183. ** a legal notice, here is a blessing:
  36184. **
  36185. ** May you do good and not evil.
  36186. ** May you find forgiveness for yourself and forgive others.
  36187. ** May you share freely, never taking more than you give.
  36188. **
  36189. *************************************************************************
  36190. ** This file implements a external (disk-based) database using BTrees.
  36191. ** For a detailed discussion of BTrees, refer to
  36192. **
  36193. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  36194. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  36195. ** Publishing Company, Reading, Massachusetts.
  36196. **
  36197. ** The basic idea is that each page of the file contains N database
  36198. ** entries and N+1 pointers to subpages.
  36199. **
  36200. ** ----------------------------------------------------------------
  36201. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  36202. ** ----------------------------------------------------------------
  36203. **
  36204. ** All of the keys on the page that Ptr(0) points to have values less
  36205. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  36206. ** values greater than Key(0) and less than Key(1). All of the keys
  36207. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  36208. ** so forth.
  36209. **
  36210. ** Finding a particular key requires reading O(log(M)) pages from the
  36211. ** disk where M is the number of entries in the tree.
  36212. **
  36213. ** In this implementation, a single file can hold one or more separate
  36214. ** BTrees. Each BTree is identified by the index of its root page. The
  36215. ** key and data for any entry are combined to form the "payload". A
  36216. ** fixed amount of payload can be carried directly on the database
  36217. ** page. If the payload is larger than the preset amount then surplus
  36218. ** bytes are stored on overflow pages. The payload for an entry
  36219. ** and the preceding pointer are combined to form a "Cell". Each
  36220. ** page has a small header which contains the Ptr(N) pointer and other
  36221. ** information such as the size of key and data.
  36222. **
  36223. ** FORMAT DETAILS
  36224. **
  36225. ** The file is divided into pages. The first page is called page 1,
  36226. ** the second is page 2, and so forth. A page number of zero indicates
  36227. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  36228. ** Each page can be either a btree page, a freelist page, an overflow
  36229. ** page, or a pointer-map page.
  36230. **
  36231. ** The first page is always a btree page. The first 100 bytes of the first
  36232. ** page contain a special header (the "file header") that describes the file.
  36233. ** The format of the file header is as follows:
  36234. **
  36235. ** OFFSET SIZE DESCRIPTION
  36236. ** 0 16 Header string: "SQLite format 3\000"
  36237. ** 16 2 Page size in bytes. (1 means 65536)
  36238. ** 18 1 File format write version
  36239. ** 19 1 File format read version
  36240. ** 20 1 Bytes of unused space at the end of each page
  36241. ** 21 1 Max embedded payload fraction (must be 64)
  36242. ** 22 1 Min embedded payload fraction (must be 32)
  36243. ** 23 1 Min leaf payload fraction (must be 32)
  36244. ** 24 4 File change counter
  36245. ** 28 4 Reserved for future use
  36246. ** 32 4 First freelist page
  36247. ** 36 4 Number of freelist pages in the file
  36248. ** 40 60 15 4-byte meta values passed to higher layers
  36249. **
  36250. ** 40 4 Schema cookie
  36251. ** 44 4 File format of schema layer
  36252. ** 48 4 Size of page cache
  36253. ** 52 4 Largest root-page (auto/incr_vacuum)
  36254. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  36255. ** 60 4 User version
  36256. ** 64 4 Incremental vacuum mode
  36257. ** 68 4 Application-ID
  36258. ** 72 20 unused
  36259. ** 92 4 The version-valid-for number
  36260. ** 96 4 SQLITE_VERSION_NUMBER
  36261. **
  36262. ** All of the integer values are big-endian (most significant byte first).
  36263. **
  36264. ** The file change counter is incremented when the database is changed
  36265. ** This counter allows other processes to know when the file has changed
  36266. ** and thus when they need to flush their cache.
  36267. **
  36268. ** The max embedded payload fraction is the amount of the total usable
  36269. ** space in a page that can be consumed by a single cell for standard
  36270. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  36271. ** is to limit the maximum cell size so that at least 4 cells will fit
  36272. ** on one page. Thus the default max embedded payload fraction is 64.
  36273. **
  36274. ** If the payload for a cell is larger than the max payload, then extra
  36275. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  36276. ** as many bytes as possible are moved into the overflow pages without letting
  36277. ** the cell size drop below the min embedded payload fraction.
  36278. **
  36279. ** The min leaf payload fraction is like the min embedded payload fraction
  36280. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  36281. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  36282. ** not specified in the header.
  36283. **
  36284. ** Each btree pages is divided into three sections: The header, the
  36285. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  36286. ** file header that occurs before the page header.
  36287. **
  36288. ** |----------------|
  36289. ** | file header | 100 bytes. Page 1 only.
  36290. ** |----------------|
  36291. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  36292. ** |----------------|
  36293. ** | cell pointer | | 2 bytes per cell. Sorted order.
  36294. ** | array | | Grows downward
  36295. ** | | v
  36296. ** |----------------|
  36297. ** | unallocated |
  36298. ** | space |
  36299. ** |----------------| ^ Grows upwards
  36300. ** | cell content | | Arbitrary order interspersed with freeblocks.
  36301. ** | area | | and free space fragments.
  36302. ** |----------------|
  36303. **
  36304. ** The page headers looks like this:
  36305. **
  36306. ** OFFSET SIZE DESCRIPTION
  36307. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  36308. ** 1 2 byte offset to the first freeblock
  36309. ** 3 2 number of cells on this page
  36310. ** 5 2 first byte of the cell content area
  36311. ** 7 1 number of fragmented free bytes
  36312. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  36313. **
  36314. ** The flags define the format of this btree page. The leaf flag means that
  36315. ** this page has no children. The zerodata flag means that this page carries
  36316. ** only keys and no data. The intkey flag means that the key is a integer
  36317. ** which is stored in the key size entry of the cell header rather than in
  36318. ** the payload area.
  36319. **
  36320. ** The cell pointer array begins on the first byte after the page header.
  36321. ** The cell pointer array contains zero or more 2-byte numbers which are
  36322. ** offsets from the beginning of the page to the cell content in the cell
  36323. ** content area. The cell pointers occur in sorted order. The system strives
  36324. ** to keep free space after the last cell pointer so that new cells can
  36325. ** be easily added without having to defragment the page.
  36326. **
  36327. ** Cell content is stored at the very end of the page and grows toward the
  36328. ** beginning of the page.
  36329. **
  36330. ** Unused space within the cell content area is collected into a linked list of
  36331. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  36332. ** to the first freeblock is given in the header. Freeblocks occur in
  36333. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  36334. ** any group of 3 or fewer unused bytes in the cell content area cannot
  36335. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  36336. ** a fragment. The total number of bytes in all fragments is recorded.
  36337. ** in the page header at offset 7.
  36338. **
  36339. ** SIZE DESCRIPTION
  36340. ** 2 Byte offset of the next freeblock
  36341. ** 2 Bytes in this freeblock
  36342. **
  36343. ** Cells are of variable length. Cells are stored in the cell content area at
  36344. ** the end of the page. Pointers to the cells are in the cell pointer array
  36345. ** that immediately follows the page header. Cells is not necessarily
  36346. ** contiguous or in order, but cell pointers are contiguous and in order.
  36347. **
  36348. ** Cell content makes use of variable length integers. A variable
  36349. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  36350. ** byte are used. The integer consists of all bytes that have bit 8 set and
  36351. ** the first byte with bit 8 clear. The most significant byte of the integer
  36352. ** appears first. A variable-length integer may not be more than 9 bytes long.
  36353. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  36354. ** allows a 64-bit integer to be encoded in 9 bytes.
  36355. **
  36356. ** 0x00 becomes 0x00000000
  36357. ** 0x7f becomes 0x0000007f
  36358. ** 0x81 0x00 becomes 0x00000080
  36359. ** 0x82 0x00 becomes 0x00000100
  36360. ** 0x80 0x7f becomes 0x0000007f
  36361. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  36362. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  36363. **
  36364. ** Variable length integers are used for rowids and to hold the number of
  36365. ** bytes of key and data in a btree cell.
  36366. **
  36367. ** The content of a cell looks like this:
  36368. **
  36369. ** SIZE DESCRIPTION
  36370. ** 4 Page number of the left child. Omitted if leaf flag is set.
  36371. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  36372. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  36373. ** * Payload
  36374. ** 4 First page of the overflow chain. Omitted if no overflow
  36375. **
  36376. ** Overflow pages form a linked list. Each page except the last is completely
  36377. ** filled with data (pagesize - 4 bytes). The last page can have as little
  36378. ** as 1 byte of data.
  36379. **
  36380. ** SIZE DESCRIPTION
  36381. ** 4 Page number of next overflow page
  36382. ** * Data
  36383. **
  36384. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  36385. ** file header points to the first in a linked list of trunk page. Each trunk
  36386. ** page points to multiple leaf pages. The content of a leaf page is
  36387. ** unspecified. A trunk page looks like this:
  36388. **
  36389. ** SIZE DESCRIPTION
  36390. ** 4 Page number of next trunk page
  36391. ** 4 Number of leaf pointers on this page
  36392. ** * zero or more pages numbers of leaves
  36393. */
  36394. /* The following value is the maximum cell size assuming a maximum page
  36395. ** size give above.
  36396. */
  36397. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  36398. /* The maximum number of cells on a single page of the database. This
  36399. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  36400. ** plus 2 bytes for the index to the cell in the page header). Such
  36401. ** small cells will be rare, but they are possible.
  36402. */
  36403. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  36404. /* Forward declarations */
  36405. typedef struct MemPage MemPage;
  36406. typedef struct BtLock BtLock;
  36407. /*
  36408. ** This is a magic string that appears at the beginning of every
  36409. ** SQLite database in order to identify the file as a real database.
  36410. **
  36411. ** You can change this value at compile-time by specifying a
  36412. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  36413. ** header must be exactly 16 bytes including the zero-terminator so
  36414. ** the string itself should be 15 characters long. If you change
  36415. ** the header, then your custom library will not be able to read
  36416. ** databases generated by the standard tools and the standard tools
  36417. ** will not be able to read databases created by your custom library.
  36418. */
  36419. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  36420. # define SQLITE_FILE_HEADER "SQLite format 3"
  36421. #endif
  36422. /*
  36423. ** Page type flags. An ORed combination of these flags appear as the
  36424. ** first byte of on-disk image of every BTree page.
  36425. */
  36426. #define PTF_INTKEY 0x01
  36427. #define PTF_ZERODATA 0x02
  36428. #define PTF_LEAFDATA 0x04
  36429. #define PTF_LEAF 0x08
  36430. /*
  36431. ** As each page of the file is loaded into memory, an instance of the following
  36432. ** structure is appended and initialized to zero. This structure stores
  36433. ** information about the page that is decoded from the raw file page.
  36434. **
  36435. ** The pParent field points back to the parent page. This allows us to
  36436. ** walk up the BTree from any leaf to the root. Care must be taken to
  36437. ** unref() the parent page pointer when this page is no longer referenced.
  36438. ** The pageDestructor() routine handles that chore.
  36439. **
  36440. ** Access to all fields of this structure is controlled by the mutex
  36441. ** stored in MemPage.pBt->mutex.
  36442. */
  36443. struct MemPage {
  36444. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  36445. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  36446. u8 intKey; /* True if intkey flag is set */
  36447. u8 leaf; /* True if leaf flag is set */
  36448. u8 hasData; /* True if this page stores data */
  36449. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  36450. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  36451. u8 max1bytePayload; /* min(maxLocal,127) */
  36452. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  36453. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  36454. u16 cellOffset; /* Index in aData of first cell pointer */
  36455. u16 nFree; /* Number of free bytes on the page */
  36456. u16 nCell; /* Number of cells on this page, local and ovfl */
  36457. u16 maskPage; /* Mask for page offset */
  36458. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  36459. ** non-overflow cell */
  36460. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  36461. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  36462. u8 *aData; /* Pointer to disk image of the page data */
  36463. u8 *aDataEnd; /* One byte past the end of usable data */
  36464. u8 *aCellIdx; /* The cell index area */
  36465. DbPage *pDbPage; /* Pager page handle */
  36466. Pgno pgno; /* Page number for this page */
  36467. };
  36468. /*
  36469. ** The in-memory image of a disk page has the auxiliary information appended
  36470. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  36471. ** that extra information.
  36472. */
  36473. #define EXTRA_SIZE sizeof(MemPage)
  36474. /*
  36475. ** A linked list of the following structures is stored at BtShared.pLock.
  36476. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  36477. ** is opened on the table with root page BtShared.iTable. Locks are removed
  36478. ** from this list when a transaction is committed or rolled back, or when
  36479. ** a btree handle is closed.
  36480. */
  36481. struct BtLock {
  36482. Btree *pBtree; /* Btree handle holding this lock */
  36483. Pgno iTable; /* Root page of table */
  36484. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  36485. BtLock *pNext; /* Next in BtShared.pLock list */
  36486. };
  36487. /* Candidate values for BtLock.eLock */
  36488. #define READ_LOCK 1
  36489. #define WRITE_LOCK 2
  36490. /* A Btree handle
  36491. **
  36492. ** A database connection contains a pointer to an instance of
  36493. ** this object for every database file that it has open. This structure
  36494. ** is opaque to the database connection. The database connection cannot
  36495. ** see the internals of this structure and only deals with pointers to
  36496. ** this structure.
  36497. **
  36498. ** For some database files, the same underlying database cache might be
  36499. ** shared between multiple connections. In that case, each connection
  36500. ** has it own instance of this object. But each instance of this object
  36501. ** points to the same BtShared object. The database cache and the
  36502. ** schema associated with the database file are all contained within
  36503. ** the BtShared object.
  36504. **
  36505. ** All fields in this structure are accessed under sqlite3.mutex.
  36506. ** The pBt pointer itself may not be changed while there exists cursors
  36507. ** in the referenced BtShared that point back to this Btree since those
  36508. ** cursors have to go through this Btree to find their BtShared and
  36509. ** they often do so without holding sqlite3.mutex.
  36510. */
  36511. struct Btree {
  36512. sqlite3 *db; /* The database connection holding this btree */
  36513. BtShared *pBt; /* Sharable content of this btree */
  36514. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  36515. u8 sharable; /* True if we can share pBt with another db */
  36516. u8 locked; /* True if db currently has pBt locked */
  36517. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  36518. int nBackup; /* Number of backup operations reading this btree */
  36519. Btree *pNext; /* List of other sharable Btrees from the same db */
  36520. Btree *pPrev; /* Back pointer of the same list */
  36521. #ifndef SQLITE_OMIT_SHARED_CACHE
  36522. BtLock lock; /* Object used to lock page 1 */
  36523. #endif
  36524. };
  36525. /*
  36526. ** Btree.inTrans may take one of the following values.
  36527. **
  36528. ** If the shared-data extension is enabled, there may be multiple users
  36529. ** of the Btree structure. At most one of these may open a write transaction,
  36530. ** but any number may have active read transactions.
  36531. */
  36532. #define TRANS_NONE 0
  36533. #define TRANS_READ 1
  36534. #define TRANS_WRITE 2
  36535. /*
  36536. ** An instance of this object represents a single database file.
  36537. **
  36538. ** A single database file can be in use at the same time by two
  36539. ** or more database connections. When two or more connections are
  36540. ** sharing the same database file, each connection has it own
  36541. ** private Btree object for the file and each of those Btrees points
  36542. ** to this one BtShared object. BtShared.nRef is the number of
  36543. ** connections currently sharing this database file.
  36544. **
  36545. ** Fields in this structure are accessed under the BtShared.mutex
  36546. ** mutex, except for nRef and pNext which are accessed under the
  36547. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  36548. ** may not be modified once it is initially set as long as nRef>0.
  36549. ** The pSchema field may be set once under BtShared.mutex and
  36550. ** thereafter is unchanged as long as nRef>0.
  36551. **
  36552. ** isPending:
  36553. **
  36554. ** If a BtShared client fails to obtain a write-lock on a database
  36555. ** table (because there exists one or more read-locks on the table),
  36556. ** the shared-cache enters 'pending-lock' state and isPending is
  36557. ** set to true.
  36558. **
  36559. ** The shared-cache leaves the 'pending lock' state when either of
  36560. ** the following occur:
  36561. **
  36562. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  36563. ** 2) The number of locks held by other connections drops to zero.
  36564. **
  36565. ** while in the 'pending-lock' state, no connection may start a new
  36566. ** transaction.
  36567. **
  36568. ** This feature is included to help prevent writer-starvation.
  36569. */
  36570. struct BtShared {
  36571. Pager *pPager; /* The page cache */
  36572. sqlite3 *db; /* Database connection currently using this Btree */
  36573. BtCursor *pCursor; /* A list of all open cursors */
  36574. MemPage *pPage1; /* First page of the database */
  36575. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  36576. #ifndef SQLITE_OMIT_AUTOVACUUM
  36577. u8 autoVacuum; /* True if auto-vacuum is enabled */
  36578. u8 incrVacuum; /* True if incr-vacuum is enabled */
  36579. u8 bDoTruncate; /* True to truncate db on commit */
  36580. #endif
  36581. u8 inTransaction; /* Transaction state */
  36582. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  36583. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  36584. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  36585. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  36586. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  36587. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  36588. u32 pageSize; /* Total number of bytes on a page */
  36589. u32 usableSize; /* Number of usable bytes on each page */
  36590. int nTransaction; /* Number of open transactions (read + write) */
  36591. u32 nPage; /* Number of pages in the database */
  36592. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  36593. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  36594. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  36595. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  36596. #ifndef SQLITE_OMIT_SHARED_CACHE
  36597. int nRef; /* Number of references to this structure */
  36598. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  36599. BtLock *pLock; /* List of locks held on this shared-btree struct */
  36600. Btree *pWriter; /* Btree with currently open write transaction */
  36601. #endif
  36602. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  36603. };
  36604. /*
  36605. ** Allowed values for BtShared.btsFlags
  36606. */
  36607. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  36608. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  36609. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  36610. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  36611. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  36612. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  36613. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  36614. /*
  36615. ** An instance of the following structure is used to hold information
  36616. ** about a cell. The parseCellPtr() function fills in this structure
  36617. ** based on information extract from the raw disk page.
  36618. */
  36619. typedef struct CellInfo CellInfo;
  36620. struct CellInfo {
  36621. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  36622. u8 *pCell; /* Pointer to the start of cell content */
  36623. u32 nData; /* Number of bytes of data */
  36624. u32 nPayload; /* Total amount of payload */
  36625. u16 nHeader; /* Size of the cell content header in bytes */
  36626. u16 nLocal; /* Amount of payload held locally */
  36627. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  36628. u16 nSize; /* Size of the cell content on the main b-tree page */
  36629. };
  36630. /*
  36631. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  36632. ** this will be declared corrupt. This value is calculated based on a
  36633. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  36634. ** root-node and 3 for all other internal nodes.
  36635. **
  36636. ** If a tree that appears to be taller than this is encountered, it is
  36637. ** assumed that the database is corrupt.
  36638. */
  36639. #define BTCURSOR_MAX_DEPTH 20
  36640. /*
  36641. ** A cursor is a pointer to a particular entry within a particular
  36642. ** b-tree within a database file.
  36643. **
  36644. ** The entry is identified by its MemPage and the index in
  36645. ** MemPage.aCell[] of the entry.
  36646. **
  36647. ** A single database file can be shared by two more database connections,
  36648. ** but cursors cannot be shared. Each cursor is associated with a
  36649. ** particular database connection identified BtCursor.pBtree.db.
  36650. **
  36651. ** Fields in this structure are accessed under the BtShared.mutex
  36652. ** found at self->pBt->mutex.
  36653. */
  36654. struct BtCursor {
  36655. Btree *pBtree; /* The Btree to which this cursor belongs */
  36656. BtShared *pBt; /* The BtShared this cursor points to */
  36657. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  36658. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  36659. #ifndef SQLITE_OMIT_INCRBLOB
  36660. Pgno *aOverflow; /* Cache of overflow page locations */
  36661. #endif
  36662. Pgno pgnoRoot; /* The root page of this tree */
  36663. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  36664. CellInfo info; /* A parse of the cell we are pointing at */
  36665. i64 nKey; /* Size of pKey, or last integer key */
  36666. void *pKey; /* Saved key that was cursor's last known position */
  36667. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  36668. u8 wrFlag; /* True if writable */
  36669. u8 atLast; /* Cursor pointing to the last entry */
  36670. u8 validNKey; /* True if info.nKey is valid */
  36671. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  36672. #ifndef SQLITE_OMIT_INCRBLOB
  36673. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  36674. #endif
  36675. u8 hints; /* As configured by CursorSetHints() */
  36676. i16 iPage; /* Index of current page in apPage */
  36677. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  36678. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  36679. };
  36680. /*
  36681. ** Potential values for BtCursor.eState.
  36682. **
  36683. ** CURSOR_INVALID:
  36684. ** Cursor does not point to a valid entry. This can happen (for example)
  36685. ** because the table is empty or because BtreeCursorFirst() has not been
  36686. ** called.
  36687. **
  36688. ** CURSOR_VALID:
  36689. ** Cursor points to a valid entry. getPayload() etc. may be called.
  36690. **
  36691. ** CURSOR_SKIPNEXT:
  36692. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  36693. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  36694. ** operation should be a no-op.
  36695. **
  36696. ** CURSOR_REQUIRESEEK:
  36697. ** The table that this cursor was opened on still exists, but has been
  36698. ** modified since the cursor was last used. The cursor position is saved
  36699. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  36700. ** this state, restoreCursorPosition() can be called to attempt to
  36701. ** seek the cursor to the saved position.
  36702. **
  36703. ** CURSOR_FAULT:
  36704. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  36705. ** on a different connection that shares the BtShared cache with this
  36706. ** cursor. The error has left the cache in an inconsistent state.
  36707. ** Do nothing else with this cursor. Any attempt to use the cursor
  36708. ** should return the error code stored in BtCursor.skip
  36709. */
  36710. #define CURSOR_INVALID 0
  36711. #define CURSOR_VALID 1
  36712. #define CURSOR_SKIPNEXT 2
  36713. #define CURSOR_REQUIRESEEK 3
  36714. #define CURSOR_FAULT 4
  36715. /*
  36716. ** The database page the PENDING_BYTE occupies. This page is never used.
  36717. */
  36718. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  36719. /*
  36720. ** These macros define the location of the pointer-map entry for a
  36721. ** database page. The first argument to each is the number of usable
  36722. ** bytes on each page of the database (often 1024). The second is the
  36723. ** page number to look up in the pointer map.
  36724. **
  36725. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  36726. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  36727. ** the offset of the requested map entry.
  36728. **
  36729. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  36730. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  36731. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  36732. ** this test.
  36733. */
  36734. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  36735. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  36736. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  36737. /*
  36738. ** The pointer map is a lookup table that identifies the parent page for
  36739. ** each child page in the database file. The parent page is the page that
  36740. ** contains a pointer to the child. Every page in the database contains
  36741. ** 0 or 1 parent pages. (In this context 'database page' refers
  36742. ** to any page that is not part of the pointer map itself.) Each pointer map
  36743. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  36744. ** The PTRMAP_XXX identifiers below are the valid types.
  36745. **
  36746. ** The purpose of the pointer map is to facility moving pages from one
  36747. ** position in the file to another as part of autovacuum. When a page
  36748. ** is moved, the pointer in its parent must be updated to point to the
  36749. ** new location. The pointer map is used to locate the parent page quickly.
  36750. **
  36751. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  36752. ** used in this case.
  36753. **
  36754. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  36755. ** is not used in this case.
  36756. **
  36757. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  36758. ** overflow pages. The page number identifies the page that
  36759. ** contains the cell with a pointer to this overflow page.
  36760. **
  36761. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  36762. ** overflow pages. The page-number identifies the previous
  36763. ** page in the overflow page list.
  36764. **
  36765. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  36766. ** identifies the parent page in the btree.
  36767. */
  36768. #define PTRMAP_ROOTPAGE 1
  36769. #define PTRMAP_FREEPAGE 2
  36770. #define PTRMAP_OVERFLOW1 3
  36771. #define PTRMAP_OVERFLOW2 4
  36772. #define PTRMAP_BTREE 5
  36773. /* A bunch of assert() statements to check the transaction state variables
  36774. ** of handle p (type Btree*) are internally consistent.
  36775. */
  36776. #define btreeIntegrity(p) \
  36777. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  36778. assert( p->pBt->inTransaction>=p->inTrans );
  36779. /*
  36780. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  36781. ** if the database supports auto-vacuum or not. Because it is used
  36782. ** within an expression that is an argument to another macro
  36783. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  36784. ** So, this macro is defined instead.
  36785. */
  36786. #ifndef SQLITE_OMIT_AUTOVACUUM
  36787. #define ISAUTOVACUUM (pBt->autoVacuum)
  36788. #else
  36789. #define ISAUTOVACUUM 0
  36790. #endif
  36791. /*
  36792. ** This structure is passed around through all the sanity checking routines
  36793. ** in order to keep track of some global state information.
  36794. **
  36795. ** The aRef[] array is allocated so that there is 1 bit for each page in
  36796. ** the database. As the integrity-check proceeds, for each page used in
  36797. ** the database the corresponding bit is set. This allows integrity-check to
  36798. ** detect pages that are used twice and orphaned pages (both of which
  36799. ** indicate corruption).
  36800. */
  36801. typedef struct IntegrityCk IntegrityCk;
  36802. struct IntegrityCk {
  36803. BtShared *pBt; /* The tree being checked out */
  36804. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  36805. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  36806. Pgno nPage; /* Number of pages in the database */
  36807. int mxErr; /* Stop accumulating errors when this reaches zero */
  36808. int nErr; /* Number of messages written to zErrMsg so far */
  36809. int mallocFailed; /* A memory allocation error has occurred */
  36810. StrAccum errMsg; /* Accumulate the error message text here */
  36811. };
  36812. /*
  36813. ** Routines to read or write a two- and four-byte big-endian integer values.
  36814. */
  36815. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  36816. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  36817. #define get4byte sqlite3Get4byte
  36818. #define put4byte sqlite3Put4byte
  36819. /************** End of btreeInt.h ********************************************/
  36820. /************** Continuing where we left off in btmutex.c ********************/
  36821. #ifndef SQLITE_OMIT_SHARED_CACHE
  36822. #if SQLITE_THREADSAFE
  36823. /*
  36824. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  36825. ** set BtShared.db to the database handle associated with p and the
  36826. ** p->locked boolean to true.
  36827. */
  36828. static void lockBtreeMutex(Btree *p){
  36829. assert( p->locked==0 );
  36830. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  36831. assert( sqlite3_mutex_held(p->db->mutex) );
  36832. sqlite3_mutex_enter(p->pBt->mutex);
  36833. p->pBt->db = p->db;
  36834. p->locked = 1;
  36835. }
  36836. /*
  36837. ** Release the BtShared mutex associated with B-Tree handle p and
  36838. ** clear the p->locked boolean.
  36839. */
  36840. static void unlockBtreeMutex(Btree *p){
  36841. BtShared *pBt = p->pBt;
  36842. assert( p->locked==1 );
  36843. assert( sqlite3_mutex_held(pBt->mutex) );
  36844. assert( sqlite3_mutex_held(p->db->mutex) );
  36845. assert( p->db==pBt->db );
  36846. sqlite3_mutex_leave(pBt->mutex);
  36847. p->locked = 0;
  36848. }
  36849. /*
  36850. ** Enter a mutex on the given BTree object.
  36851. **
  36852. ** If the object is not sharable, then no mutex is ever required
  36853. ** and this routine is a no-op. The underlying mutex is non-recursive.
  36854. ** But we keep a reference count in Btree.wantToLock so the behavior
  36855. ** of this interface is recursive.
  36856. **
  36857. ** To avoid deadlocks, multiple Btrees are locked in the same order
  36858. ** by all database connections. The p->pNext is a list of other
  36859. ** Btrees belonging to the same database connection as the p Btree
  36860. ** which need to be locked after p. If we cannot get a lock on
  36861. ** p, then first unlock all of the others on p->pNext, then wait
  36862. ** for the lock to become available on p, then relock all of the
  36863. ** subsequent Btrees that desire a lock.
  36864. */
  36865. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  36866. Btree *pLater;
  36867. /* Some basic sanity checking on the Btree. The list of Btrees
  36868. ** connected by pNext and pPrev should be in sorted order by
  36869. ** Btree.pBt value. All elements of the list should belong to
  36870. ** the same connection. Only shared Btrees are on the list. */
  36871. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  36872. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  36873. assert( p->pNext==0 || p->pNext->db==p->db );
  36874. assert( p->pPrev==0 || p->pPrev->db==p->db );
  36875. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  36876. /* Check for locking consistency */
  36877. assert( !p->locked || p->wantToLock>0 );
  36878. assert( p->sharable || p->wantToLock==0 );
  36879. /* We should already hold a lock on the database connection */
  36880. assert( sqlite3_mutex_held(p->db->mutex) );
  36881. /* Unless the database is sharable and unlocked, then BtShared.db
  36882. ** should already be set correctly. */
  36883. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  36884. if( !p->sharable ) return;
  36885. p->wantToLock++;
  36886. if( p->locked ) return;
  36887. /* In most cases, we should be able to acquire the lock we
  36888. ** want without having to go throught the ascending lock
  36889. ** procedure that follows. Just be sure not to block.
  36890. */
  36891. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  36892. p->pBt->db = p->db;
  36893. p->locked = 1;
  36894. return;
  36895. }
  36896. /* To avoid deadlock, first release all locks with a larger
  36897. ** BtShared address. Then acquire our lock. Then reacquire
  36898. ** the other BtShared locks that we used to hold in ascending
  36899. ** order.
  36900. */
  36901. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  36902. assert( pLater->sharable );
  36903. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  36904. assert( !pLater->locked || pLater->wantToLock>0 );
  36905. if( pLater->locked ){
  36906. unlockBtreeMutex(pLater);
  36907. }
  36908. }
  36909. lockBtreeMutex(p);
  36910. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  36911. if( pLater->wantToLock ){
  36912. lockBtreeMutex(pLater);
  36913. }
  36914. }
  36915. }
  36916. /*
  36917. ** Exit the recursive mutex on a Btree.
  36918. */
  36919. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  36920. if( p->sharable ){
  36921. assert( p->wantToLock>0 );
  36922. p->wantToLock--;
  36923. if( p->wantToLock==0 ){
  36924. unlockBtreeMutex(p);
  36925. }
  36926. }
  36927. }
  36928. #ifndef NDEBUG
  36929. /*
  36930. ** Return true if the BtShared mutex is held on the btree, or if the
  36931. ** B-Tree is not marked as sharable.
  36932. **
  36933. ** This routine is used only from within assert() statements.
  36934. */
  36935. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  36936. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  36937. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  36938. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  36939. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  36940. return (p->sharable==0 || p->locked);
  36941. }
  36942. #endif
  36943. #ifndef SQLITE_OMIT_INCRBLOB
  36944. /*
  36945. ** Enter and leave a mutex on a Btree given a cursor owned by that
  36946. ** Btree. These entry points are used by incremental I/O and can be
  36947. ** omitted if that module is not used.
  36948. */
  36949. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  36950. sqlite3BtreeEnter(pCur->pBtree);
  36951. }
  36952. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  36953. sqlite3BtreeLeave(pCur->pBtree);
  36954. }
  36955. #endif /* SQLITE_OMIT_INCRBLOB */
  36956. /*
  36957. ** Enter the mutex on every Btree associated with a database
  36958. ** connection. This is needed (for example) prior to parsing
  36959. ** a statement since we will be comparing table and column names
  36960. ** against all schemas and we do not want those schemas being
  36961. ** reset out from under us.
  36962. **
  36963. ** There is a corresponding leave-all procedures.
  36964. **
  36965. ** Enter the mutexes in accending order by BtShared pointer address
  36966. ** to avoid the possibility of deadlock when two threads with
  36967. ** two or more btrees in common both try to lock all their btrees
  36968. ** at the same instant.
  36969. */
  36970. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  36971. int i;
  36972. Btree *p;
  36973. assert( sqlite3_mutex_held(db->mutex) );
  36974. for(i=0; i<db->nDb; i++){
  36975. p = db->aDb[i].pBt;
  36976. if( p ) sqlite3BtreeEnter(p);
  36977. }
  36978. }
  36979. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  36980. int i;
  36981. Btree *p;
  36982. assert( sqlite3_mutex_held(db->mutex) );
  36983. for(i=0; i<db->nDb; i++){
  36984. p = db->aDb[i].pBt;
  36985. if( p ) sqlite3BtreeLeave(p);
  36986. }
  36987. }
  36988. /*
  36989. ** Return true if a particular Btree requires a lock. Return FALSE if
  36990. ** no lock is ever required since it is not sharable.
  36991. */
  36992. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  36993. return p->sharable;
  36994. }
  36995. #ifndef NDEBUG
  36996. /*
  36997. ** Return true if the current thread holds the database connection
  36998. ** mutex and all required BtShared mutexes.
  36999. **
  37000. ** This routine is used inside assert() statements only.
  37001. */
  37002. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  37003. int i;
  37004. if( !sqlite3_mutex_held(db->mutex) ){
  37005. return 0;
  37006. }
  37007. for(i=0; i<db->nDb; i++){
  37008. Btree *p;
  37009. p = db->aDb[i].pBt;
  37010. if( p && p->sharable &&
  37011. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  37012. return 0;
  37013. }
  37014. }
  37015. return 1;
  37016. }
  37017. #endif /* NDEBUG */
  37018. #ifndef NDEBUG
  37019. /*
  37020. ** Return true if the correct mutexes are held for accessing the
  37021. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  37022. ** access are:
  37023. **
  37024. ** (1) The mutex on db
  37025. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  37026. **
  37027. ** If pSchema is not NULL, then iDb is computed from pSchema and
  37028. ** db using sqlite3SchemaToIndex().
  37029. */
  37030. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  37031. Btree *p;
  37032. assert( db!=0 );
  37033. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  37034. assert( iDb>=0 && iDb<db->nDb );
  37035. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  37036. if( iDb==1 ) return 1;
  37037. p = db->aDb[iDb].pBt;
  37038. assert( p!=0 );
  37039. return p->sharable==0 || p->locked==1;
  37040. }
  37041. #endif /* NDEBUG */
  37042. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  37043. /*
  37044. ** The following are special cases for mutex enter routines for use
  37045. ** in single threaded applications that use shared cache. Except for
  37046. ** these two routines, all mutex operations are no-ops in that case and
  37047. ** are null #defines in btree.h.
  37048. **
  37049. ** If shared cache is disabled, then all btree mutex routines, including
  37050. ** the ones below, are no-ops and are null #defines in btree.h.
  37051. */
  37052. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  37053. p->pBt->db = p->db;
  37054. }
  37055. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  37056. int i;
  37057. for(i=0; i<db->nDb; i++){
  37058. Btree *p = db->aDb[i].pBt;
  37059. if( p ){
  37060. p->pBt->db = p->db;
  37061. }
  37062. }
  37063. }
  37064. #endif /* if SQLITE_THREADSAFE */
  37065. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  37066. /************** End of btmutex.c *********************************************/
  37067. /************** Begin file btree.c *******************************************/
  37068. /*
  37069. ** 2004 April 6
  37070. **
  37071. ** The author disclaims copyright to this source code. In place of
  37072. ** a legal notice, here is a blessing:
  37073. **
  37074. ** May you do good and not evil.
  37075. ** May you find forgiveness for yourself and forgive others.
  37076. ** May you share freely, never taking more than you give.
  37077. **
  37078. *************************************************************************
  37079. ** This file implements a external (disk-based) database using BTrees.
  37080. ** See the header comment on "btreeInt.h" for additional information.
  37081. ** Including a description of file format and an overview of operation.
  37082. */
  37083. /*
  37084. ** The header string that appears at the beginning of every
  37085. ** SQLite database.
  37086. */
  37087. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  37088. /*
  37089. ** Set this global variable to 1 to enable tracing using the TRACE
  37090. ** macro.
  37091. */
  37092. #if 0
  37093. int sqlite3BtreeTrace=1; /* True to enable tracing */
  37094. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  37095. #else
  37096. # define TRACE(X)
  37097. #endif
  37098. /*
  37099. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  37100. ** But if the value is zero, make it 65536.
  37101. **
  37102. ** This routine is used to extract the "offset to cell content area" value
  37103. ** from the header of a btree page. If the page size is 65536 and the page
  37104. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  37105. ** This routine makes the necessary adjustment to 65536.
  37106. */
  37107. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  37108. /*
  37109. ** Values passed as the 5th argument to allocateBtreePage()
  37110. */
  37111. #define BTALLOC_ANY 0 /* Allocate any page */
  37112. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  37113. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  37114. /*
  37115. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  37116. ** defined, or 0 if it is. For example:
  37117. **
  37118. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  37119. */
  37120. #ifndef SQLITE_OMIT_AUTOVACUUM
  37121. #define IfNotOmitAV(expr) (expr)
  37122. #else
  37123. #define IfNotOmitAV(expr) 0
  37124. #endif
  37125. #ifndef SQLITE_OMIT_SHARED_CACHE
  37126. /*
  37127. ** A list of BtShared objects that are eligible for participation
  37128. ** in shared cache. This variable has file scope during normal builds,
  37129. ** but the test harness needs to access it so we make it global for
  37130. ** test builds.
  37131. **
  37132. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  37133. */
  37134. #ifdef SQLITE_TEST
  37135. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  37136. #else
  37137. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  37138. #endif
  37139. #endif /* SQLITE_OMIT_SHARED_CACHE */
  37140. #ifndef SQLITE_OMIT_SHARED_CACHE
  37141. /*
  37142. ** Enable or disable the shared pager and schema features.
  37143. **
  37144. ** This routine has no effect on existing database connections.
  37145. ** The shared cache setting effects only future calls to
  37146. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  37147. */
  37148. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  37149. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  37150. return SQLITE_OK;
  37151. }
  37152. #endif
  37153. #ifdef SQLITE_OMIT_SHARED_CACHE
  37154. /*
  37155. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  37156. ** and clearAllSharedCacheTableLocks()
  37157. ** manipulate entries in the BtShared.pLock linked list used to store
  37158. ** shared-cache table level locks. If the library is compiled with the
  37159. ** shared-cache feature disabled, then there is only ever one user
  37160. ** of each BtShared structure and so this locking is not necessary.
  37161. ** So define the lock related functions as no-ops.
  37162. */
  37163. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  37164. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  37165. #define clearAllSharedCacheTableLocks(a)
  37166. #define downgradeAllSharedCacheTableLocks(a)
  37167. #define hasSharedCacheTableLock(a,b,c,d) 1
  37168. #define hasReadConflicts(a, b) 0
  37169. #endif
  37170. #ifndef SQLITE_OMIT_SHARED_CACHE
  37171. #ifdef SQLITE_DEBUG
  37172. /*
  37173. **** This function is only used as part of an assert() statement. ***
  37174. **
  37175. ** Check to see if pBtree holds the required locks to read or write to the
  37176. ** table with root page iRoot. Return 1 if it does and 0 if not.
  37177. **
  37178. ** For example, when writing to a table with root-page iRoot via
  37179. ** Btree connection pBtree:
  37180. **
  37181. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  37182. **
  37183. ** When writing to an index that resides in a sharable database, the
  37184. ** caller should have first obtained a lock specifying the root page of
  37185. ** the corresponding table. This makes things a bit more complicated,
  37186. ** as this module treats each table as a separate structure. To determine
  37187. ** the table corresponding to the index being written, this
  37188. ** function has to search through the database schema.
  37189. **
  37190. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  37191. ** hold a write-lock on the schema table (root page 1). This is also
  37192. ** acceptable.
  37193. */
  37194. static int hasSharedCacheTableLock(
  37195. Btree *pBtree, /* Handle that must hold lock */
  37196. Pgno iRoot, /* Root page of b-tree */
  37197. int isIndex, /* True if iRoot is the root of an index b-tree */
  37198. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  37199. ){
  37200. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  37201. Pgno iTab = 0;
  37202. BtLock *pLock;
  37203. /* If this database is not shareable, or if the client is reading
  37204. ** and has the read-uncommitted flag set, then no lock is required.
  37205. ** Return true immediately.
  37206. */
  37207. if( (pBtree->sharable==0)
  37208. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  37209. ){
  37210. return 1;
  37211. }
  37212. /* If the client is reading or writing an index and the schema is
  37213. ** not loaded, then it is too difficult to actually check to see if
  37214. ** the correct locks are held. So do not bother - just return true.
  37215. ** This case does not come up very often anyhow.
  37216. */
  37217. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  37218. return 1;
  37219. }
  37220. /* Figure out the root-page that the lock should be held on. For table
  37221. ** b-trees, this is just the root page of the b-tree being read or
  37222. ** written. For index b-trees, it is the root page of the associated
  37223. ** table. */
  37224. if( isIndex ){
  37225. HashElem *p;
  37226. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  37227. Index *pIdx = (Index *)sqliteHashData(p);
  37228. if( pIdx->tnum==(int)iRoot ){
  37229. iTab = pIdx->pTable->tnum;
  37230. }
  37231. }
  37232. }else{
  37233. iTab = iRoot;
  37234. }
  37235. /* Search for the required lock. Either a write-lock on root-page iTab, a
  37236. ** write-lock on the schema table, or (if the client is reading) a
  37237. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  37238. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  37239. if( pLock->pBtree==pBtree
  37240. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  37241. && pLock->eLock>=eLockType
  37242. ){
  37243. return 1;
  37244. }
  37245. }
  37246. /* Failed to find the required lock. */
  37247. return 0;
  37248. }
  37249. #endif /* SQLITE_DEBUG */
  37250. #ifdef SQLITE_DEBUG
  37251. /*
  37252. **** This function may be used as part of assert() statements only. ****
  37253. **
  37254. ** Return true if it would be illegal for pBtree to write into the
  37255. ** table or index rooted at iRoot because other shared connections are
  37256. ** simultaneously reading that same table or index.
  37257. **
  37258. ** It is illegal for pBtree to write if some other Btree object that
  37259. ** shares the same BtShared object is currently reading or writing
  37260. ** the iRoot table. Except, if the other Btree object has the
  37261. ** read-uncommitted flag set, then it is OK for the other object to
  37262. ** have a read cursor.
  37263. **
  37264. ** For example, before writing to any part of the table or index
  37265. ** rooted at page iRoot, one should call:
  37266. **
  37267. ** assert( !hasReadConflicts(pBtree, iRoot) );
  37268. */
  37269. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  37270. BtCursor *p;
  37271. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  37272. if( p->pgnoRoot==iRoot
  37273. && p->pBtree!=pBtree
  37274. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  37275. ){
  37276. return 1;
  37277. }
  37278. }
  37279. return 0;
  37280. }
  37281. #endif /* #ifdef SQLITE_DEBUG */
  37282. /*
  37283. ** Query to see if Btree handle p may obtain a lock of type eLock
  37284. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  37285. ** SQLITE_OK if the lock may be obtained (by calling
  37286. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  37287. */
  37288. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  37289. BtShared *pBt = p->pBt;
  37290. BtLock *pIter;
  37291. assert( sqlite3BtreeHoldsMutex(p) );
  37292. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  37293. assert( p->db!=0 );
  37294. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  37295. /* If requesting a write-lock, then the Btree must have an open write
  37296. ** transaction on this file. And, obviously, for this to be so there
  37297. ** must be an open write transaction on the file itself.
  37298. */
  37299. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  37300. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  37301. /* This routine is a no-op if the shared-cache is not enabled */
  37302. if( !p->sharable ){
  37303. return SQLITE_OK;
  37304. }
  37305. /* If some other connection is holding an exclusive lock, the
  37306. ** requested lock may not be obtained.
  37307. */
  37308. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  37309. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  37310. return SQLITE_LOCKED_SHAREDCACHE;
  37311. }
  37312. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  37313. /* The condition (pIter->eLock!=eLock) in the following if(...)
  37314. ** statement is a simplification of:
  37315. **
  37316. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  37317. **
  37318. ** since we know that if eLock==WRITE_LOCK, then no other connection
  37319. ** may hold a WRITE_LOCK on any table in this file (since there can
  37320. ** only be a single writer).
  37321. */
  37322. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  37323. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  37324. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  37325. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  37326. if( eLock==WRITE_LOCK ){
  37327. assert( p==pBt->pWriter );
  37328. pBt->btsFlags |= BTS_PENDING;
  37329. }
  37330. return SQLITE_LOCKED_SHAREDCACHE;
  37331. }
  37332. }
  37333. return SQLITE_OK;
  37334. }
  37335. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  37336. #ifndef SQLITE_OMIT_SHARED_CACHE
  37337. /*
  37338. ** Add a lock on the table with root-page iTable to the shared-btree used
  37339. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  37340. ** WRITE_LOCK.
  37341. **
  37342. ** This function assumes the following:
  37343. **
  37344. ** (a) The specified Btree object p is connected to a sharable
  37345. ** database (one with the BtShared.sharable flag set), and
  37346. **
  37347. ** (b) No other Btree objects hold a lock that conflicts
  37348. ** with the requested lock (i.e. querySharedCacheTableLock() has
  37349. ** already been called and returned SQLITE_OK).
  37350. **
  37351. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  37352. ** is returned if a malloc attempt fails.
  37353. */
  37354. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  37355. BtShared *pBt = p->pBt;
  37356. BtLock *pLock = 0;
  37357. BtLock *pIter;
  37358. assert( sqlite3BtreeHoldsMutex(p) );
  37359. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  37360. assert( p->db!=0 );
  37361. /* A connection with the read-uncommitted flag set will never try to
  37362. ** obtain a read-lock using this function. The only read-lock obtained
  37363. ** by a connection in read-uncommitted mode is on the sqlite_master
  37364. ** table, and that lock is obtained in BtreeBeginTrans(). */
  37365. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  37366. /* This function should only be called on a sharable b-tree after it
  37367. ** has been determined that no other b-tree holds a conflicting lock. */
  37368. assert( p->sharable );
  37369. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  37370. /* First search the list for an existing lock on this table. */
  37371. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  37372. if( pIter->iTable==iTable && pIter->pBtree==p ){
  37373. pLock = pIter;
  37374. break;
  37375. }
  37376. }
  37377. /* If the above search did not find a BtLock struct associating Btree p
  37378. ** with table iTable, allocate one and link it into the list.
  37379. */
  37380. if( !pLock ){
  37381. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  37382. if( !pLock ){
  37383. return SQLITE_NOMEM;
  37384. }
  37385. pLock->iTable = iTable;
  37386. pLock->pBtree = p;
  37387. pLock->pNext = pBt->pLock;
  37388. pBt->pLock = pLock;
  37389. }
  37390. /* Set the BtLock.eLock variable to the maximum of the current lock
  37391. ** and the requested lock. This means if a write-lock was already held
  37392. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  37393. */
  37394. assert( WRITE_LOCK>READ_LOCK );
  37395. if( eLock>pLock->eLock ){
  37396. pLock->eLock = eLock;
  37397. }
  37398. return SQLITE_OK;
  37399. }
  37400. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  37401. #ifndef SQLITE_OMIT_SHARED_CACHE
  37402. /*
  37403. ** Release all the table locks (locks obtained via calls to
  37404. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  37405. **
  37406. ** This function assumes that Btree p has an open read or write
  37407. ** transaction. If it does not, then the BTS_PENDING flag
  37408. ** may be incorrectly cleared.
  37409. */
  37410. static void clearAllSharedCacheTableLocks(Btree *p){
  37411. BtShared *pBt = p->pBt;
  37412. BtLock **ppIter = &pBt->pLock;
  37413. assert( sqlite3BtreeHoldsMutex(p) );
  37414. assert( p->sharable || 0==*ppIter );
  37415. assert( p->inTrans>0 );
  37416. while( *ppIter ){
  37417. BtLock *pLock = *ppIter;
  37418. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  37419. assert( pLock->pBtree->inTrans>=pLock->eLock );
  37420. if( pLock->pBtree==p ){
  37421. *ppIter = pLock->pNext;
  37422. assert( pLock->iTable!=1 || pLock==&p->lock );
  37423. if( pLock->iTable!=1 ){
  37424. sqlite3_free(pLock);
  37425. }
  37426. }else{
  37427. ppIter = &pLock->pNext;
  37428. }
  37429. }
  37430. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  37431. if( pBt->pWriter==p ){
  37432. pBt->pWriter = 0;
  37433. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  37434. }else if( pBt->nTransaction==2 ){
  37435. /* This function is called when Btree p is concluding its
  37436. ** transaction. If there currently exists a writer, and p is not
  37437. ** that writer, then the number of locks held by connections other
  37438. ** than the writer must be about to drop to zero. In this case
  37439. ** set the BTS_PENDING flag to 0.
  37440. **
  37441. ** If there is not currently a writer, then BTS_PENDING must
  37442. ** be zero already. So this next line is harmless in that case.
  37443. */
  37444. pBt->btsFlags &= ~BTS_PENDING;
  37445. }
  37446. }
  37447. /*
  37448. ** This function changes all write-locks held by Btree p into read-locks.
  37449. */
  37450. static void downgradeAllSharedCacheTableLocks(Btree *p){
  37451. BtShared *pBt = p->pBt;
  37452. if( pBt->pWriter==p ){
  37453. BtLock *pLock;
  37454. pBt->pWriter = 0;
  37455. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  37456. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  37457. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  37458. pLock->eLock = READ_LOCK;
  37459. }
  37460. }
  37461. }
  37462. #endif /* SQLITE_OMIT_SHARED_CACHE */
  37463. static void releasePage(MemPage *pPage); /* Forward reference */
  37464. /*
  37465. ***** This routine is used inside of assert() only ****
  37466. **
  37467. ** Verify that the cursor holds the mutex on its BtShared
  37468. */
  37469. #ifdef SQLITE_DEBUG
  37470. static int cursorHoldsMutex(BtCursor *p){
  37471. return sqlite3_mutex_held(p->pBt->mutex);
  37472. }
  37473. #endif
  37474. #ifndef SQLITE_OMIT_INCRBLOB
  37475. /*
  37476. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  37477. */
  37478. static void invalidateOverflowCache(BtCursor *pCur){
  37479. assert( cursorHoldsMutex(pCur) );
  37480. sqlite3_free(pCur->aOverflow);
  37481. pCur->aOverflow = 0;
  37482. }
  37483. /*
  37484. ** Invalidate the overflow page-list cache for all cursors opened
  37485. ** on the shared btree structure pBt.
  37486. */
  37487. static void invalidateAllOverflowCache(BtShared *pBt){
  37488. BtCursor *p;
  37489. assert( sqlite3_mutex_held(pBt->mutex) );
  37490. for(p=pBt->pCursor; p; p=p->pNext){
  37491. invalidateOverflowCache(p);
  37492. }
  37493. }
  37494. /*
  37495. ** This function is called before modifying the contents of a table
  37496. ** to invalidate any incrblob cursors that are open on the
  37497. ** row or one of the rows being modified.
  37498. **
  37499. ** If argument isClearTable is true, then the entire contents of the
  37500. ** table is about to be deleted. In this case invalidate all incrblob
  37501. ** cursors open on any row within the table with root-page pgnoRoot.
  37502. **
  37503. ** Otherwise, if argument isClearTable is false, then the row with
  37504. ** rowid iRow is being replaced or deleted. In this case invalidate
  37505. ** only those incrblob cursors open on that specific row.
  37506. */
  37507. static void invalidateIncrblobCursors(
  37508. Btree *pBtree, /* The database file to check */
  37509. i64 iRow, /* The rowid that might be changing */
  37510. int isClearTable /* True if all rows are being deleted */
  37511. ){
  37512. BtCursor *p;
  37513. BtShared *pBt = pBtree->pBt;
  37514. assert( sqlite3BtreeHoldsMutex(pBtree) );
  37515. for(p=pBt->pCursor; p; p=p->pNext){
  37516. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  37517. p->eState = CURSOR_INVALID;
  37518. }
  37519. }
  37520. }
  37521. #else
  37522. /* Stub functions when INCRBLOB is omitted */
  37523. #define invalidateOverflowCache(x)
  37524. #define invalidateAllOverflowCache(x)
  37525. #define invalidateIncrblobCursors(x,y,z)
  37526. #endif /* SQLITE_OMIT_INCRBLOB */
  37527. /*
  37528. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  37529. ** when a page that previously contained data becomes a free-list leaf
  37530. ** page.
  37531. **
  37532. ** The BtShared.pHasContent bitvec exists to work around an obscure
  37533. ** bug caused by the interaction of two useful IO optimizations surrounding
  37534. ** free-list leaf pages:
  37535. **
  37536. ** 1) When all data is deleted from a page and the page becomes
  37537. ** a free-list leaf page, the page is not written to the database
  37538. ** (as free-list leaf pages contain no meaningful data). Sometimes
  37539. ** such a page is not even journalled (as it will not be modified,
  37540. ** why bother journalling it?).
  37541. **
  37542. ** 2) When a free-list leaf page is reused, its content is not read
  37543. ** from the database or written to the journal file (why should it
  37544. ** be, if it is not at all meaningful?).
  37545. **
  37546. ** By themselves, these optimizations work fine and provide a handy
  37547. ** performance boost to bulk delete or insert operations. However, if
  37548. ** a page is moved to the free-list and then reused within the same
  37549. ** transaction, a problem comes up. If the page is not journalled when
  37550. ** it is moved to the free-list and it is also not journalled when it
  37551. ** is extracted from the free-list and reused, then the original data
  37552. ** may be lost. In the event of a rollback, it may not be possible
  37553. ** to restore the database to its original configuration.
  37554. **
  37555. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  37556. ** moved to become a free-list leaf page, the corresponding bit is
  37557. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  37558. ** optimization 2 above is omitted if the corresponding bit is already
  37559. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  37560. ** at the end of every transaction.
  37561. */
  37562. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  37563. int rc = SQLITE_OK;
  37564. if( !pBt->pHasContent ){
  37565. assert( pgno<=pBt->nPage );
  37566. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  37567. if( !pBt->pHasContent ){
  37568. rc = SQLITE_NOMEM;
  37569. }
  37570. }
  37571. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  37572. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  37573. }
  37574. return rc;
  37575. }
  37576. /*
  37577. ** Query the BtShared.pHasContent vector.
  37578. **
  37579. ** This function is called when a free-list leaf page is removed from the
  37580. ** free-list for reuse. It returns false if it is safe to retrieve the
  37581. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  37582. */
  37583. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  37584. Bitvec *p = pBt->pHasContent;
  37585. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  37586. }
  37587. /*
  37588. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  37589. ** invoked at the conclusion of each write-transaction.
  37590. */
  37591. static void btreeClearHasContent(BtShared *pBt){
  37592. sqlite3BitvecDestroy(pBt->pHasContent);
  37593. pBt->pHasContent = 0;
  37594. }
  37595. /*
  37596. ** Release all of the apPage[] pages for a cursor.
  37597. */
  37598. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  37599. int i;
  37600. for(i=0; i<=pCur->iPage; i++){
  37601. releasePage(pCur->apPage[i]);
  37602. pCur->apPage[i] = 0;
  37603. }
  37604. pCur->iPage = -1;
  37605. }
  37606. /*
  37607. ** Save the current cursor position in the variables BtCursor.nKey
  37608. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  37609. **
  37610. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  37611. ** prior to calling this routine.
  37612. */
  37613. static int saveCursorPosition(BtCursor *pCur){
  37614. int rc;
  37615. assert( CURSOR_VALID==pCur->eState );
  37616. assert( 0==pCur->pKey );
  37617. assert( cursorHoldsMutex(pCur) );
  37618. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  37619. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  37620. /* If this is an intKey table, then the above call to BtreeKeySize()
  37621. ** stores the integer key in pCur->nKey. In this case this value is
  37622. ** all that is required. Otherwise, if pCur is not open on an intKey
  37623. ** table, then malloc space for and store the pCur->nKey bytes of key
  37624. ** data.
  37625. */
  37626. if( 0==pCur->apPage[0]->intKey ){
  37627. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  37628. if( pKey ){
  37629. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  37630. if( rc==SQLITE_OK ){
  37631. pCur->pKey = pKey;
  37632. }else{
  37633. sqlite3_free(pKey);
  37634. }
  37635. }else{
  37636. rc = SQLITE_NOMEM;
  37637. }
  37638. }
  37639. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  37640. if( rc==SQLITE_OK ){
  37641. btreeReleaseAllCursorPages(pCur);
  37642. pCur->eState = CURSOR_REQUIRESEEK;
  37643. }
  37644. invalidateOverflowCache(pCur);
  37645. return rc;
  37646. }
  37647. /*
  37648. ** Save the positions of all cursors (except pExcept) that are open on
  37649. ** the table with root-page iRoot. Usually, this is called just before cursor
  37650. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  37651. */
  37652. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  37653. BtCursor *p;
  37654. assert( sqlite3_mutex_held(pBt->mutex) );
  37655. assert( pExcept==0 || pExcept->pBt==pBt );
  37656. for(p=pBt->pCursor; p; p=p->pNext){
  37657. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  37658. if( p->eState==CURSOR_VALID ){
  37659. int rc = saveCursorPosition(p);
  37660. if( SQLITE_OK!=rc ){
  37661. return rc;
  37662. }
  37663. }else{
  37664. testcase( p->iPage>0 );
  37665. btreeReleaseAllCursorPages(p);
  37666. }
  37667. }
  37668. }
  37669. return SQLITE_OK;
  37670. }
  37671. /*
  37672. ** Clear the current cursor position.
  37673. */
  37674. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  37675. assert( cursorHoldsMutex(pCur) );
  37676. sqlite3_free(pCur->pKey);
  37677. pCur->pKey = 0;
  37678. pCur->eState = CURSOR_INVALID;
  37679. }
  37680. /*
  37681. ** In this version of BtreeMoveto, pKey is a packed index record
  37682. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  37683. ** record and then call BtreeMovetoUnpacked() to do the work.
  37684. */
  37685. static int btreeMoveto(
  37686. BtCursor *pCur, /* Cursor open on the btree to be searched */
  37687. const void *pKey, /* Packed key if the btree is an index */
  37688. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  37689. int bias, /* Bias search to the high end */
  37690. int *pRes /* Write search results here */
  37691. ){
  37692. int rc; /* Status code */
  37693. UnpackedRecord *pIdxKey; /* Unpacked index key */
  37694. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  37695. char *pFree = 0;
  37696. if( pKey ){
  37697. assert( nKey==(i64)(int)nKey );
  37698. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  37699. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  37700. );
  37701. if( pIdxKey==0 ) return SQLITE_NOMEM;
  37702. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  37703. }else{
  37704. pIdxKey = 0;
  37705. }
  37706. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  37707. if( pFree ){
  37708. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  37709. }
  37710. return rc;
  37711. }
  37712. /*
  37713. ** Restore the cursor to the position it was in (or as close to as possible)
  37714. ** when saveCursorPosition() was called. Note that this call deletes the
  37715. ** saved position info stored by saveCursorPosition(), so there can be
  37716. ** at most one effective restoreCursorPosition() call after each
  37717. ** saveCursorPosition().
  37718. */
  37719. static int btreeRestoreCursorPosition(BtCursor *pCur){
  37720. int rc;
  37721. assert( cursorHoldsMutex(pCur) );
  37722. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  37723. if( pCur->eState==CURSOR_FAULT ){
  37724. return pCur->skipNext;
  37725. }
  37726. pCur->eState = CURSOR_INVALID;
  37727. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  37728. if( rc==SQLITE_OK ){
  37729. sqlite3_free(pCur->pKey);
  37730. pCur->pKey = 0;
  37731. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  37732. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  37733. pCur->eState = CURSOR_SKIPNEXT;
  37734. }
  37735. }
  37736. return rc;
  37737. }
  37738. #define restoreCursorPosition(p) \
  37739. (p->eState>=CURSOR_REQUIRESEEK ? \
  37740. btreeRestoreCursorPosition(p) : \
  37741. SQLITE_OK)
  37742. /*
  37743. ** Determine whether or not a cursor has moved from the position it
  37744. ** was last placed at. Cursors can move when the row they are pointing
  37745. ** at is deleted out from under them.
  37746. **
  37747. ** This routine returns an error code if something goes wrong. The
  37748. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  37749. */
  37750. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  37751. int rc;
  37752. rc = restoreCursorPosition(pCur);
  37753. if( rc ){
  37754. *pHasMoved = 1;
  37755. return rc;
  37756. }
  37757. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  37758. *pHasMoved = 1;
  37759. }else{
  37760. *pHasMoved = 0;
  37761. }
  37762. return SQLITE_OK;
  37763. }
  37764. #ifndef SQLITE_OMIT_AUTOVACUUM
  37765. /*
  37766. ** Given a page number of a regular database page, return the page
  37767. ** number for the pointer-map page that contains the entry for the
  37768. ** input page number.
  37769. **
  37770. ** Return 0 (not a valid page) for pgno==1 since there is
  37771. ** no pointer map associated with page 1. The integrity_check logic
  37772. ** requires that ptrmapPageno(*,1)!=1.
  37773. */
  37774. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  37775. int nPagesPerMapPage;
  37776. Pgno iPtrMap, ret;
  37777. assert( sqlite3_mutex_held(pBt->mutex) );
  37778. if( pgno<2 ) return 0;
  37779. nPagesPerMapPage = (pBt->usableSize/5)+1;
  37780. iPtrMap = (pgno-2)/nPagesPerMapPage;
  37781. ret = (iPtrMap*nPagesPerMapPage) + 2;
  37782. if( ret==PENDING_BYTE_PAGE(pBt) ){
  37783. ret++;
  37784. }
  37785. return ret;
  37786. }
  37787. /*
  37788. ** Write an entry into the pointer map.
  37789. **
  37790. ** This routine updates the pointer map entry for page number 'key'
  37791. ** so that it maps to type 'eType' and parent page number 'pgno'.
  37792. **
  37793. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  37794. ** a no-op. If an error occurs, the appropriate error code is written
  37795. ** into *pRC.
  37796. */
  37797. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  37798. DbPage *pDbPage; /* The pointer map page */
  37799. u8 *pPtrmap; /* The pointer map data */
  37800. Pgno iPtrmap; /* The pointer map page number */
  37801. int offset; /* Offset in pointer map page */
  37802. int rc; /* Return code from subfunctions */
  37803. if( *pRC ) return;
  37804. assert( sqlite3_mutex_held(pBt->mutex) );
  37805. /* The master-journal page number must never be used as a pointer map page */
  37806. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  37807. assert( pBt->autoVacuum );
  37808. if( key==0 ){
  37809. *pRC = SQLITE_CORRUPT_BKPT;
  37810. return;
  37811. }
  37812. iPtrmap = PTRMAP_PAGENO(pBt, key);
  37813. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  37814. if( rc!=SQLITE_OK ){
  37815. *pRC = rc;
  37816. return;
  37817. }
  37818. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  37819. if( offset<0 ){
  37820. *pRC = SQLITE_CORRUPT_BKPT;
  37821. goto ptrmap_exit;
  37822. }
  37823. assert( offset <= (int)pBt->usableSize-5 );
  37824. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  37825. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  37826. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  37827. *pRC= rc = sqlite3PagerWrite(pDbPage);
  37828. if( rc==SQLITE_OK ){
  37829. pPtrmap[offset] = eType;
  37830. put4byte(&pPtrmap[offset+1], parent);
  37831. }
  37832. }
  37833. ptrmap_exit:
  37834. sqlite3PagerUnref(pDbPage);
  37835. }
  37836. /*
  37837. ** Read an entry from the pointer map.
  37838. **
  37839. ** This routine retrieves the pointer map entry for page 'key', writing
  37840. ** the type and parent page number to *pEType and *pPgno respectively.
  37841. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  37842. */
  37843. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  37844. DbPage *pDbPage; /* The pointer map page */
  37845. int iPtrmap; /* Pointer map page index */
  37846. u8 *pPtrmap; /* Pointer map page data */
  37847. int offset; /* Offset of entry in pointer map */
  37848. int rc;
  37849. assert( sqlite3_mutex_held(pBt->mutex) );
  37850. iPtrmap = PTRMAP_PAGENO(pBt, key);
  37851. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  37852. if( rc!=0 ){
  37853. return rc;
  37854. }
  37855. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  37856. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  37857. if( offset<0 ){
  37858. sqlite3PagerUnref(pDbPage);
  37859. return SQLITE_CORRUPT_BKPT;
  37860. }
  37861. assert( offset <= (int)pBt->usableSize-5 );
  37862. assert( pEType!=0 );
  37863. *pEType = pPtrmap[offset];
  37864. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  37865. sqlite3PagerUnref(pDbPage);
  37866. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  37867. return SQLITE_OK;
  37868. }
  37869. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  37870. #define ptrmapPut(w,x,y,z,rc)
  37871. #define ptrmapGet(w,x,y,z) SQLITE_OK
  37872. #define ptrmapPutOvflPtr(x, y, rc)
  37873. #endif
  37874. /*
  37875. ** Given a btree page and a cell index (0 means the first cell on
  37876. ** the page, 1 means the second cell, and so forth) return a pointer
  37877. ** to the cell content.
  37878. **
  37879. ** This routine works only for pages that do not contain overflow cells.
  37880. */
  37881. #define findCell(P,I) \
  37882. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  37883. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  37884. /*
  37885. ** This a more complex version of findCell() that works for
  37886. ** pages that do contain overflow cells.
  37887. */
  37888. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  37889. int i;
  37890. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  37891. for(i=pPage->nOverflow-1; i>=0; i--){
  37892. int k;
  37893. k = pPage->aiOvfl[i];
  37894. if( k<=iCell ){
  37895. if( k==iCell ){
  37896. return pPage->apOvfl[i];
  37897. }
  37898. iCell--;
  37899. }
  37900. }
  37901. return findCell(pPage, iCell);
  37902. }
  37903. /*
  37904. ** Parse a cell content block and fill in the CellInfo structure. There
  37905. ** are two versions of this function. btreeParseCell() takes a
  37906. ** cell index as the second argument and btreeParseCellPtr()
  37907. ** takes a pointer to the body of the cell as its second argument.
  37908. **
  37909. ** Within this file, the parseCell() macro can be called instead of
  37910. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  37911. */
  37912. static void btreeParseCellPtr(
  37913. MemPage *pPage, /* Page containing the cell */
  37914. u8 *pCell, /* Pointer to the cell text. */
  37915. CellInfo *pInfo /* Fill in this structure */
  37916. ){
  37917. u16 n; /* Number bytes in cell content header */
  37918. u32 nPayload; /* Number of bytes of cell payload */
  37919. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  37920. pInfo->pCell = pCell;
  37921. assert( pPage->leaf==0 || pPage->leaf==1 );
  37922. n = pPage->childPtrSize;
  37923. assert( n==4-4*pPage->leaf );
  37924. if( pPage->intKey ){
  37925. if( pPage->hasData ){
  37926. assert( n==0 );
  37927. n = getVarint32(pCell, nPayload);
  37928. }else{
  37929. nPayload = 0;
  37930. }
  37931. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  37932. pInfo->nData = nPayload;
  37933. }else{
  37934. pInfo->nData = 0;
  37935. n += getVarint32(&pCell[n], nPayload);
  37936. pInfo->nKey = nPayload;
  37937. }
  37938. pInfo->nPayload = nPayload;
  37939. pInfo->nHeader = n;
  37940. testcase( nPayload==pPage->maxLocal );
  37941. testcase( nPayload==pPage->maxLocal+1 );
  37942. if( likely(nPayload<=pPage->maxLocal) ){
  37943. /* This is the (easy) common case where the entire payload fits
  37944. ** on the local page. No overflow is required.
  37945. */
  37946. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  37947. pInfo->nLocal = (u16)nPayload;
  37948. pInfo->iOverflow = 0;
  37949. }else{
  37950. /* If the payload will not fit completely on the local page, we have
  37951. ** to decide how much to store locally and how much to spill onto
  37952. ** overflow pages. The strategy is to minimize the amount of unused
  37953. ** space on overflow pages while keeping the amount of local storage
  37954. ** in between minLocal and maxLocal.
  37955. **
  37956. ** Warning: changing the way overflow payload is distributed in any
  37957. ** way will result in an incompatible file format.
  37958. */
  37959. int minLocal; /* Minimum amount of payload held locally */
  37960. int maxLocal; /* Maximum amount of payload held locally */
  37961. int surplus; /* Overflow payload available for local storage */
  37962. minLocal = pPage->minLocal;
  37963. maxLocal = pPage->maxLocal;
  37964. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  37965. testcase( surplus==maxLocal );
  37966. testcase( surplus==maxLocal+1 );
  37967. if( surplus <= maxLocal ){
  37968. pInfo->nLocal = (u16)surplus;
  37969. }else{
  37970. pInfo->nLocal = (u16)minLocal;
  37971. }
  37972. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  37973. pInfo->nSize = pInfo->iOverflow + 4;
  37974. }
  37975. }
  37976. #define parseCell(pPage, iCell, pInfo) \
  37977. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  37978. static void btreeParseCell(
  37979. MemPage *pPage, /* Page containing the cell */
  37980. int iCell, /* The cell index. First cell is 0 */
  37981. CellInfo *pInfo /* Fill in this structure */
  37982. ){
  37983. parseCell(pPage, iCell, pInfo);
  37984. }
  37985. /*
  37986. ** Compute the total number of bytes that a Cell needs in the cell
  37987. ** data area of the btree-page. The return number includes the cell
  37988. ** data header and the local payload, but not any overflow page or
  37989. ** the space used by the cell pointer.
  37990. */
  37991. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  37992. u8 *pIter = &pCell[pPage->childPtrSize];
  37993. u32 nSize;
  37994. #ifdef SQLITE_DEBUG
  37995. /* The value returned by this function should always be the same as
  37996. ** the (CellInfo.nSize) value found by doing a full parse of the
  37997. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  37998. ** this function verifies that this invariant is not violated. */
  37999. CellInfo debuginfo;
  38000. btreeParseCellPtr(pPage, pCell, &debuginfo);
  38001. #endif
  38002. if( pPage->intKey ){
  38003. u8 *pEnd;
  38004. if( pPage->hasData ){
  38005. pIter += getVarint32(pIter, nSize);
  38006. }else{
  38007. nSize = 0;
  38008. }
  38009. /* pIter now points at the 64-bit integer key value, a variable length
  38010. ** integer. The following block moves pIter to point at the first byte
  38011. ** past the end of the key value. */
  38012. pEnd = &pIter[9];
  38013. while( (*pIter++)&0x80 && pIter<pEnd );
  38014. }else{
  38015. pIter += getVarint32(pIter, nSize);
  38016. }
  38017. testcase( nSize==pPage->maxLocal );
  38018. testcase( nSize==pPage->maxLocal+1 );
  38019. if( nSize>pPage->maxLocal ){
  38020. int minLocal = pPage->minLocal;
  38021. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  38022. testcase( nSize==pPage->maxLocal );
  38023. testcase( nSize==pPage->maxLocal+1 );
  38024. if( nSize>pPage->maxLocal ){
  38025. nSize = minLocal;
  38026. }
  38027. nSize += 4;
  38028. }
  38029. nSize += (u32)(pIter - pCell);
  38030. /* The minimum size of any cell is 4 bytes. */
  38031. if( nSize<4 ){
  38032. nSize = 4;
  38033. }
  38034. assert( nSize==debuginfo.nSize );
  38035. return (u16)nSize;
  38036. }
  38037. #ifdef SQLITE_DEBUG
  38038. /* This variation on cellSizePtr() is used inside of assert() statements
  38039. ** only. */
  38040. static u16 cellSize(MemPage *pPage, int iCell){
  38041. return cellSizePtr(pPage, findCell(pPage, iCell));
  38042. }
  38043. #endif
  38044. #ifndef SQLITE_OMIT_AUTOVACUUM
  38045. /*
  38046. ** If the cell pCell, part of page pPage contains a pointer
  38047. ** to an overflow page, insert an entry into the pointer-map
  38048. ** for the overflow page.
  38049. */
  38050. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  38051. CellInfo info;
  38052. if( *pRC ) return;
  38053. assert( pCell!=0 );
  38054. btreeParseCellPtr(pPage, pCell, &info);
  38055. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  38056. if( info.iOverflow ){
  38057. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  38058. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  38059. }
  38060. }
  38061. #endif
  38062. /*
  38063. ** Defragment the page given. All Cells are moved to the
  38064. ** end of the page and all free space is collected into one
  38065. ** big FreeBlk that occurs in between the header and cell
  38066. ** pointer array and the cell content area.
  38067. */
  38068. static int defragmentPage(MemPage *pPage){
  38069. int i; /* Loop counter */
  38070. int pc; /* Address of a i-th cell */
  38071. int hdr; /* Offset to the page header */
  38072. int size; /* Size of a cell */
  38073. int usableSize; /* Number of usable bytes on a page */
  38074. int cellOffset; /* Offset to the cell pointer array */
  38075. int cbrk; /* Offset to the cell content area */
  38076. int nCell; /* Number of cells on the page */
  38077. unsigned char *data; /* The page data */
  38078. unsigned char *temp; /* Temp area for cell content */
  38079. int iCellFirst; /* First allowable cell index */
  38080. int iCellLast; /* Last possible cell index */
  38081. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38082. assert( pPage->pBt!=0 );
  38083. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  38084. assert( pPage->nOverflow==0 );
  38085. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38086. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  38087. data = pPage->aData;
  38088. hdr = pPage->hdrOffset;
  38089. cellOffset = pPage->cellOffset;
  38090. nCell = pPage->nCell;
  38091. assert( nCell==get2byte(&data[hdr+3]) );
  38092. usableSize = pPage->pBt->usableSize;
  38093. cbrk = get2byte(&data[hdr+5]);
  38094. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  38095. cbrk = usableSize;
  38096. iCellFirst = cellOffset + 2*nCell;
  38097. iCellLast = usableSize - 4;
  38098. for(i=0; i<nCell; i++){
  38099. u8 *pAddr; /* The i-th cell pointer */
  38100. pAddr = &data[cellOffset + i*2];
  38101. pc = get2byte(pAddr);
  38102. testcase( pc==iCellFirst );
  38103. testcase( pc==iCellLast );
  38104. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38105. /* These conditions have already been verified in btreeInitPage()
  38106. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  38107. */
  38108. if( pc<iCellFirst || pc>iCellLast ){
  38109. return SQLITE_CORRUPT_BKPT;
  38110. }
  38111. #endif
  38112. assert( pc>=iCellFirst && pc<=iCellLast );
  38113. size = cellSizePtr(pPage, &temp[pc]);
  38114. cbrk -= size;
  38115. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38116. if( cbrk<iCellFirst ){
  38117. return SQLITE_CORRUPT_BKPT;
  38118. }
  38119. #else
  38120. if( cbrk<iCellFirst || pc+size>usableSize ){
  38121. return SQLITE_CORRUPT_BKPT;
  38122. }
  38123. #endif
  38124. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  38125. testcase( cbrk+size==usableSize );
  38126. testcase( pc+size==usableSize );
  38127. memcpy(&data[cbrk], &temp[pc], size);
  38128. put2byte(pAddr, cbrk);
  38129. }
  38130. assert( cbrk>=iCellFirst );
  38131. put2byte(&data[hdr+5], cbrk);
  38132. data[hdr+1] = 0;
  38133. data[hdr+2] = 0;
  38134. data[hdr+7] = 0;
  38135. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  38136. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38137. if( cbrk-iCellFirst!=pPage->nFree ){
  38138. return SQLITE_CORRUPT_BKPT;
  38139. }
  38140. return SQLITE_OK;
  38141. }
  38142. /*
  38143. ** Allocate nByte bytes of space from within the B-Tree page passed
  38144. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  38145. ** of the first byte of allocated space. Return either SQLITE_OK or
  38146. ** an error code (usually SQLITE_CORRUPT).
  38147. **
  38148. ** The caller guarantees that there is sufficient space to make the
  38149. ** allocation. This routine might need to defragment in order to bring
  38150. ** all the space together, however. This routine will avoid using
  38151. ** the first two bytes past the cell pointer area since presumably this
  38152. ** allocation is being made in order to insert a new cell, so we will
  38153. ** also end up needing a new cell pointer.
  38154. */
  38155. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  38156. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  38157. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  38158. int nFrag; /* Number of fragmented bytes on pPage */
  38159. int top; /* First byte of cell content area */
  38160. int gap; /* First byte of gap between cell pointers and cell content */
  38161. int rc; /* Integer return code */
  38162. int usableSize; /* Usable size of the page */
  38163. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38164. assert( pPage->pBt );
  38165. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38166. assert( nByte>=0 ); /* Minimum cell size is 4 */
  38167. assert( pPage->nFree>=nByte );
  38168. assert( pPage->nOverflow==0 );
  38169. usableSize = pPage->pBt->usableSize;
  38170. assert( nByte < usableSize-8 );
  38171. nFrag = data[hdr+7];
  38172. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  38173. gap = pPage->cellOffset + 2*pPage->nCell;
  38174. top = get2byteNotZero(&data[hdr+5]);
  38175. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  38176. testcase( gap+2==top );
  38177. testcase( gap+1==top );
  38178. testcase( gap==top );
  38179. if( nFrag>=60 ){
  38180. /* Always defragment highly fragmented pages */
  38181. rc = defragmentPage(pPage);
  38182. if( rc ) return rc;
  38183. top = get2byteNotZero(&data[hdr+5]);
  38184. }else if( gap+2<=top ){
  38185. /* Search the freelist looking for a free slot big enough to satisfy
  38186. ** the request. The allocation is made from the first free slot in
  38187. ** the list that is large enough to accommodate it.
  38188. */
  38189. int pc, addr;
  38190. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  38191. int size; /* Size of the free slot */
  38192. if( pc>usableSize-4 || pc<addr+4 ){
  38193. return SQLITE_CORRUPT_BKPT;
  38194. }
  38195. size = get2byte(&data[pc+2]);
  38196. if( size>=nByte ){
  38197. int x = size - nByte;
  38198. testcase( x==4 );
  38199. testcase( x==3 );
  38200. if( x<4 ){
  38201. /* Remove the slot from the free-list. Update the number of
  38202. ** fragmented bytes within the page. */
  38203. memcpy(&data[addr], &data[pc], 2);
  38204. data[hdr+7] = (u8)(nFrag + x);
  38205. }else if( size+pc > usableSize ){
  38206. return SQLITE_CORRUPT_BKPT;
  38207. }else{
  38208. /* The slot remains on the free-list. Reduce its size to account
  38209. ** for the portion used by the new allocation. */
  38210. put2byte(&data[pc+2], x);
  38211. }
  38212. *pIdx = pc + x;
  38213. return SQLITE_OK;
  38214. }
  38215. }
  38216. }
  38217. /* Check to make sure there is enough space in the gap to satisfy
  38218. ** the allocation. If not, defragment.
  38219. */
  38220. testcase( gap+2+nByte==top );
  38221. if( gap+2+nByte>top ){
  38222. rc = defragmentPage(pPage);
  38223. if( rc ) return rc;
  38224. top = get2byteNotZero(&data[hdr+5]);
  38225. assert( gap+nByte<=top );
  38226. }
  38227. /* Allocate memory from the gap in between the cell pointer array
  38228. ** and the cell content area. The btreeInitPage() call has already
  38229. ** validated the freelist. Given that the freelist is valid, there
  38230. ** is no way that the allocation can extend off the end of the page.
  38231. ** The assert() below verifies the previous sentence.
  38232. */
  38233. top -= nByte;
  38234. put2byte(&data[hdr+5], top);
  38235. assert( top+nByte <= (int)pPage->pBt->usableSize );
  38236. *pIdx = top;
  38237. return SQLITE_OK;
  38238. }
  38239. /*
  38240. ** Return a section of the pPage->aData to the freelist.
  38241. ** The first byte of the new free block is pPage->aDisk[start]
  38242. ** and the size of the block is "size" bytes.
  38243. **
  38244. ** Most of the effort here is involved in coalesing adjacent
  38245. ** free blocks into a single big free block.
  38246. */
  38247. static int freeSpace(MemPage *pPage, int start, int size){
  38248. int addr, pbegin, hdr;
  38249. int iLast; /* Largest possible freeblock offset */
  38250. unsigned char *data = pPage->aData;
  38251. assert( pPage->pBt!=0 );
  38252. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38253. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  38254. assert( (start + size) <= (int)pPage->pBt->usableSize );
  38255. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38256. assert( size>=0 ); /* Minimum cell size is 4 */
  38257. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  38258. /* Overwrite deleted information with zeros when the secure_delete
  38259. ** option is enabled */
  38260. memset(&data[start], 0, size);
  38261. }
  38262. /* Add the space back into the linked list of freeblocks. Note that
  38263. ** even though the freeblock list was checked by btreeInitPage(),
  38264. ** btreeInitPage() did not detect overlapping cells or
  38265. ** freeblocks that overlapped cells. Nor does it detect when the
  38266. ** cell content area exceeds the value in the page header. If these
  38267. ** situations arise, then subsequent insert operations might corrupt
  38268. ** the freelist. So we do need to check for corruption while scanning
  38269. ** the freelist.
  38270. */
  38271. hdr = pPage->hdrOffset;
  38272. addr = hdr + 1;
  38273. iLast = pPage->pBt->usableSize - 4;
  38274. assert( start<=iLast );
  38275. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  38276. if( pbegin<addr+4 ){
  38277. return SQLITE_CORRUPT_BKPT;
  38278. }
  38279. addr = pbegin;
  38280. }
  38281. if( pbegin>iLast ){
  38282. return SQLITE_CORRUPT_BKPT;
  38283. }
  38284. assert( pbegin>addr || pbegin==0 );
  38285. put2byte(&data[addr], start);
  38286. put2byte(&data[start], pbegin);
  38287. put2byte(&data[start+2], size);
  38288. pPage->nFree = pPage->nFree + (u16)size;
  38289. /* Coalesce adjacent free blocks */
  38290. addr = hdr + 1;
  38291. while( (pbegin = get2byte(&data[addr]))>0 ){
  38292. int pnext, psize, x;
  38293. assert( pbegin>addr );
  38294. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  38295. pnext = get2byte(&data[pbegin]);
  38296. psize = get2byte(&data[pbegin+2]);
  38297. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  38298. int frag = pnext - (pbegin+psize);
  38299. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  38300. return SQLITE_CORRUPT_BKPT;
  38301. }
  38302. data[hdr+7] -= (u8)frag;
  38303. x = get2byte(&data[pnext]);
  38304. put2byte(&data[pbegin], x);
  38305. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  38306. put2byte(&data[pbegin+2], x);
  38307. }else{
  38308. addr = pbegin;
  38309. }
  38310. }
  38311. /* If the cell content area begins with a freeblock, remove it. */
  38312. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  38313. int top;
  38314. pbegin = get2byte(&data[hdr+1]);
  38315. memcpy(&data[hdr+1], &data[pbegin], 2);
  38316. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  38317. put2byte(&data[hdr+5], top);
  38318. }
  38319. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38320. return SQLITE_OK;
  38321. }
  38322. /*
  38323. ** Decode the flags byte (the first byte of the header) for a page
  38324. ** and initialize fields of the MemPage structure accordingly.
  38325. **
  38326. ** Only the following combinations are supported. Anything different
  38327. ** indicates a corrupt database files:
  38328. **
  38329. ** PTF_ZERODATA
  38330. ** PTF_ZERODATA | PTF_LEAF
  38331. ** PTF_LEAFDATA | PTF_INTKEY
  38332. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  38333. */
  38334. static int decodeFlags(MemPage *pPage, int flagByte){
  38335. BtShared *pBt; /* A copy of pPage->pBt */
  38336. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  38337. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38338. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  38339. flagByte &= ~PTF_LEAF;
  38340. pPage->childPtrSize = 4-4*pPage->leaf;
  38341. pBt = pPage->pBt;
  38342. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  38343. pPage->intKey = 1;
  38344. pPage->hasData = pPage->leaf;
  38345. pPage->maxLocal = pBt->maxLeaf;
  38346. pPage->minLocal = pBt->minLeaf;
  38347. }else if( flagByte==PTF_ZERODATA ){
  38348. pPage->intKey = 0;
  38349. pPage->hasData = 0;
  38350. pPage->maxLocal = pBt->maxLocal;
  38351. pPage->minLocal = pBt->minLocal;
  38352. }else{
  38353. return SQLITE_CORRUPT_BKPT;
  38354. }
  38355. pPage->max1bytePayload = pBt->max1bytePayload;
  38356. return SQLITE_OK;
  38357. }
  38358. /*
  38359. ** Initialize the auxiliary information for a disk block.
  38360. **
  38361. ** Return SQLITE_OK on success. If we see that the page does
  38362. ** not contain a well-formed database page, then return
  38363. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  38364. ** guarantee that the page is well-formed. It only shows that
  38365. ** we failed to detect any corruption.
  38366. */
  38367. static int btreeInitPage(MemPage *pPage){
  38368. assert( pPage->pBt!=0 );
  38369. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38370. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  38371. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  38372. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  38373. if( !pPage->isInit ){
  38374. u16 pc; /* Address of a freeblock within pPage->aData[] */
  38375. u8 hdr; /* Offset to beginning of page header */
  38376. u8 *data; /* Equal to pPage->aData */
  38377. BtShared *pBt; /* The main btree structure */
  38378. int usableSize; /* Amount of usable space on each page */
  38379. u16 cellOffset; /* Offset from start of page to first cell pointer */
  38380. int nFree; /* Number of unused bytes on the page */
  38381. int top; /* First byte of the cell content area */
  38382. int iCellFirst; /* First allowable cell or freeblock offset */
  38383. int iCellLast; /* Last possible cell or freeblock offset */
  38384. pBt = pPage->pBt;
  38385. hdr = pPage->hdrOffset;
  38386. data = pPage->aData;
  38387. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  38388. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  38389. pPage->maskPage = (u16)(pBt->pageSize - 1);
  38390. pPage->nOverflow = 0;
  38391. usableSize = pBt->usableSize;
  38392. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  38393. pPage->aDataEnd = &data[usableSize];
  38394. pPage->aCellIdx = &data[cellOffset];
  38395. top = get2byteNotZero(&data[hdr+5]);
  38396. pPage->nCell = get2byte(&data[hdr+3]);
  38397. if( pPage->nCell>MX_CELL(pBt) ){
  38398. /* To many cells for a single page. The page must be corrupt */
  38399. return SQLITE_CORRUPT_BKPT;
  38400. }
  38401. testcase( pPage->nCell==MX_CELL(pBt) );
  38402. /* A malformed database page might cause us to read past the end
  38403. ** of page when parsing a cell.
  38404. **
  38405. ** The following block of code checks early to see if a cell extends
  38406. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  38407. ** returned if it does.
  38408. */
  38409. iCellFirst = cellOffset + 2*pPage->nCell;
  38410. iCellLast = usableSize - 4;
  38411. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  38412. {
  38413. int i; /* Index into the cell pointer array */
  38414. int sz; /* Size of a cell */
  38415. if( !pPage->leaf ) iCellLast--;
  38416. for(i=0; i<pPage->nCell; i++){
  38417. pc = get2byte(&data[cellOffset+i*2]);
  38418. testcase( pc==iCellFirst );
  38419. testcase( pc==iCellLast );
  38420. if( pc<iCellFirst || pc>iCellLast ){
  38421. return SQLITE_CORRUPT_BKPT;
  38422. }
  38423. sz = cellSizePtr(pPage, &data[pc]);
  38424. testcase( pc+sz==usableSize );
  38425. if( pc+sz>usableSize ){
  38426. return SQLITE_CORRUPT_BKPT;
  38427. }
  38428. }
  38429. if( !pPage->leaf ) iCellLast++;
  38430. }
  38431. #endif
  38432. /* Compute the total free space on the page */
  38433. pc = get2byte(&data[hdr+1]);
  38434. nFree = data[hdr+7] + top;
  38435. while( pc>0 ){
  38436. u16 next, size;
  38437. if( pc<iCellFirst || pc>iCellLast ){
  38438. /* Start of free block is off the page */
  38439. return SQLITE_CORRUPT_BKPT;
  38440. }
  38441. next = get2byte(&data[pc]);
  38442. size = get2byte(&data[pc+2]);
  38443. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  38444. /* Free blocks must be in ascending order. And the last byte of
  38445. ** the free-block must lie on the database page. */
  38446. return SQLITE_CORRUPT_BKPT;
  38447. }
  38448. nFree = nFree + size;
  38449. pc = next;
  38450. }
  38451. /* At this point, nFree contains the sum of the offset to the start
  38452. ** of the cell-content area plus the number of free bytes within
  38453. ** the cell-content area. If this is greater than the usable-size
  38454. ** of the page, then the page must be corrupted. This check also
  38455. ** serves to verify that the offset to the start of the cell-content
  38456. ** area, according to the page header, lies within the page.
  38457. */
  38458. if( nFree>usableSize ){
  38459. return SQLITE_CORRUPT_BKPT;
  38460. }
  38461. pPage->nFree = (u16)(nFree - iCellFirst);
  38462. pPage->isInit = 1;
  38463. }
  38464. return SQLITE_OK;
  38465. }
  38466. /*
  38467. ** Set up a raw page so that it looks like a database page holding
  38468. ** no entries.
  38469. */
  38470. static void zeroPage(MemPage *pPage, int flags){
  38471. unsigned char *data = pPage->aData;
  38472. BtShared *pBt = pPage->pBt;
  38473. u8 hdr = pPage->hdrOffset;
  38474. u16 first;
  38475. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  38476. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  38477. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  38478. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  38479. assert( sqlite3_mutex_held(pBt->mutex) );
  38480. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  38481. memset(&data[hdr], 0, pBt->usableSize - hdr);
  38482. }
  38483. data[hdr] = (char)flags;
  38484. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  38485. memset(&data[hdr+1], 0, 4);
  38486. data[hdr+7] = 0;
  38487. put2byte(&data[hdr+5], pBt->usableSize);
  38488. pPage->nFree = (u16)(pBt->usableSize - first);
  38489. decodeFlags(pPage, flags);
  38490. pPage->hdrOffset = hdr;
  38491. pPage->cellOffset = first;
  38492. pPage->aDataEnd = &data[pBt->usableSize];
  38493. pPage->aCellIdx = &data[first];
  38494. pPage->nOverflow = 0;
  38495. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  38496. pPage->maskPage = (u16)(pBt->pageSize - 1);
  38497. pPage->nCell = 0;
  38498. pPage->isInit = 1;
  38499. }
  38500. /*
  38501. ** Convert a DbPage obtained from the pager into a MemPage used by
  38502. ** the btree layer.
  38503. */
  38504. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  38505. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  38506. pPage->aData = sqlite3PagerGetData(pDbPage);
  38507. pPage->pDbPage = pDbPage;
  38508. pPage->pBt = pBt;
  38509. pPage->pgno = pgno;
  38510. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  38511. return pPage;
  38512. }
  38513. /*
  38514. ** Get a page from the pager. Initialize the MemPage.pBt and
  38515. ** MemPage.aData elements if needed.
  38516. **
  38517. ** If the noContent flag is set, it means that we do not care about
  38518. ** the content of the page at this time. So do not go to the disk
  38519. ** to fetch the content. Just fill in the content with zeros for now.
  38520. ** If in the future we call sqlite3PagerWrite() on this page, that
  38521. ** means we have started to be concerned about content and the disk
  38522. ** read should occur at that point.
  38523. */
  38524. static int btreeGetPage(
  38525. BtShared *pBt, /* The btree */
  38526. Pgno pgno, /* Number of the page to fetch */
  38527. MemPage **ppPage, /* Return the page in this parameter */
  38528. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  38529. ){
  38530. int rc;
  38531. DbPage *pDbPage;
  38532. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  38533. assert( sqlite3_mutex_held(pBt->mutex) );
  38534. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  38535. if( rc ) return rc;
  38536. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  38537. return SQLITE_OK;
  38538. }
  38539. /*
  38540. ** Retrieve a page from the pager cache. If the requested page is not
  38541. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  38542. ** MemPage.aData elements if needed.
  38543. */
  38544. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  38545. DbPage *pDbPage;
  38546. assert( sqlite3_mutex_held(pBt->mutex) );
  38547. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  38548. if( pDbPage ){
  38549. return btreePageFromDbPage(pDbPage, pgno, pBt);
  38550. }
  38551. return 0;
  38552. }
  38553. /*
  38554. ** Return the size of the database file in pages. If there is any kind of
  38555. ** error, return ((unsigned int)-1).
  38556. */
  38557. static Pgno btreePagecount(BtShared *pBt){
  38558. return pBt->nPage;
  38559. }
  38560. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  38561. assert( sqlite3BtreeHoldsMutex(p) );
  38562. assert( ((p->pBt->nPage)&0x8000000)==0 );
  38563. return (int)btreePagecount(p->pBt);
  38564. }
  38565. /*
  38566. ** Get a page from the pager and initialize it. This routine is just a
  38567. ** convenience wrapper around separate calls to btreeGetPage() and
  38568. ** btreeInitPage().
  38569. **
  38570. ** If an error occurs, then the value *ppPage is set to is undefined. It
  38571. ** may remain unchanged, or it may be set to an invalid value.
  38572. */
  38573. static int getAndInitPage(
  38574. BtShared *pBt, /* The database file */
  38575. Pgno pgno, /* Number of the page to get */
  38576. MemPage **ppPage, /* Write the page pointer here */
  38577. int bReadonly /* PAGER_GET_READONLY or 0 */
  38578. ){
  38579. int rc;
  38580. assert( sqlite3_mutex_held(pBt->mutex) );
  38581. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  38582. if( pgno>btreePagecount(pBt) ){
  38583. rc = SQLITE_CORRUPT_BKPT;
  38584. }else{
  38585. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  38586. if( rc==SQLITE_OK ){
  38587. rc = btreeInitPage(*ppPage);
  38588. if( rc!=SQLITE_OK ){
  38589. releasePage(*ppPage);
  38590. }
  38591. }
  38592. }
  38593. testcase( pgno==0 );
  38594. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  38595. return rc;
  38596. }
  38597. /*
  38598. ** Release a MemPage. This should be called once for each prior
  38599. ** call to btreeGetPage.
  38600. */
  38601. static void releasePage(MemPage *pPage){
  38602. if( pPage ){
  38603. assert( pPage->aData );
  38604. assert( pPage->pBt );
  38605. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  38606. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  38607. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38608. sqlite3PagerUnref(pPage->pDbPage);
  38609. }
  38610. }
  38611. /*
  38612. ** During a rollback, when the pager reloads information into the cache
  38613. ** so that the cache is restored to its original state at the start of
  38614. ** the transaction, for each page restored this routine is called.
  38615. **
  38616. ** This routine needs to reset the extra data section at the end of the
  38617. ** page to agree with the restored data.
  38618. */
  38619. static void pageReinit(DbPage *pData){
  38620. MemPage *pPage;
  38621. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  38622. assert( sqlite3PagerPageRefcount(pData)>0 );
  38623. if( pPage->isInit ){
  38624. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  38625. pPage->isInit = 0;
  38626. if( sqlite3PagerPageRefcount(pData)>1 ){
  38627. /* pPage might not be a btree page; it might be an overflow page
  38628. ** or ptrmap page or a free page. In those cases, the following
  38629. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  38630. ** But no harm is done by this. And it is very important that
  38631. ** btreeInitPage() be called on every btree page so we make
  38632. ** the call for every page that comes in for re-initing. */
  38633. btreeInitPage(pPage);
  38634. }
  38635. }
  38636. }
  38637. /*
  38638. ** Invoke the busy handler for a btree.
  38639. */
  38640. static int btreeInvokeBusyHandler(void *pArg){
  38641. BtShared *pBt = (BtShared*)pArg;
  38642. assert( pBt->db );
  38643. assert( sqlite3_mutex_held(pBt->db->mutex) );
  38644. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  38645. }
  38646. /*
  38647. ** Open a database file.
  38648. **
  38649. ** zFilename is the name of the database file. If zFilename is NULL
  38650. ** then an ephemeral database is created. The ephemeral database might
  38651. ** be exclusively in memory, or it might use a disk-based memory cache.
  38652. ** Either way, the ephemeral database will be automatically deleted
  38653. ** when sqlite3BtreeClose() is called.
  38654. **
  38655. ** If zFilename is ":memory:" then an in-memory database is created
  38656. ** that is automatically destroyed when it is closed.
  38657. **
  38658. ** The "flags" parameter is a bitmask that might contain bits like
  38659. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  38660. **
  38661. ** If the database is already opened in the same database connection
  38662. ** and we are in shared cache mode, then the open will fail with an
  38663. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  38664. ** objects in the same database connection since doing so will lead
  38665. ** to problems with locking.
  38666. */
  38667. SQLITE_PRIVATE int sqlite3BtreeOpen(
  38668. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  38669. const char *zFilename, /* Name of the file containing the BTree database */
  38670. sqlite3 *db, /* Associated database handle */
  38671. Btree **ppBtree, /* Pointer to new Btree object written here */
  38672. int flags, /* Options */
  38673. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  38674. ){
  38675. BtShared *pBt = 0; /* Shared part of btree structure */
  38676. Btree *p; /* Handle to return */
  38677. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  38678. int rc = SQLITE_OK; /* Result code from this function */
  38679. u8 nReserve; /* Byte of unused space on each page */
  38680. unsigned char zDbHeader[100]; /* Database header content */
  38681. /* True if opening an ephemeral, temporary database */
  38682. const int isTempDb = zFilename==0 || zFilename[0]==0;
  38683. /* Set the variable isMemdb to true for an in-memory database, or
  38684. ** false for a file-based database.
  38685. */
  38686. #ifdef SQLITE_OMIT_MEMORYDB
  38687. const int isMemdb = 0;
  38688. #else
  38689. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  38690. || (isTempDb && sqlite3TempInMemory(db))
  38691. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  38692. #endif
  38693. assert( db!=0 );
  38694. assert( pVfs!=0 );
  38695. assert( sqlite3_mutex_held(db->mutex) );
  38696. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  38697. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  38698. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  38699. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  38700. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  38701. if( isMemdb ){
  38702. flags |= BTREE_MEMORY;
  38703. }
  38704. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  38705. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  38706. }
  38707. p = sqlite3MallocZero(sizeof(Btree));
  38708. if( !p ){
  38709. return SQLITE_NOMEM;
  38710. }
  38711. p->inTrans = TRANS_NONE;
  38712. p->db = db;
  38713. #ifndef SQLITE_OMIT_SHARED_CACHE
  38714. p->lock.pBtree = p;
  38715. p->lock.iTable = 1;
  38716. #endif
  38717. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38718. /*
  38719. ** If this Btree is a candidate for shared cache, try to find an
  38720. ** existing BtShared object that we can share with
  38721. */
  38722. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  38723. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  38724. int nFullPathname = pVfs->mxPathname+1;
  38725. char *zFullPathname = sqlite3Malloc(nFullPathname);
  38726. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  38727. p->sharable = 1;
  38728. if( !zFullPathname ){
  38729. sqlite3_free(p);
  38730. return SQLITE_NOMEM;
  38731. }
  38732. if( isMemdb ){
  38733. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  38734. }else{
  38735. rc = sqlite3OsFullPathname(pVfs, zFilename,
  38736. nFullPathname, zFullPathname);
  38737. if( rc ){
  38738. sqlite3_free(zFullPathname);
  38739. sqlite3_free(p);
  38740. return rc;
  38741. }
  38742. }
  38743. #if SQLITE_THREADSAFE
  38744. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  38745. sqlite3_mutex_enter(mutexOpen);
  38746. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  38747. sqlite3_mutex_enter(mutexShared);
  38748. #endif
  38749. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  38750. assert( pBt->nRef>0 );
  38751. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  38752. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  38753. int iDb;
  38754. for(iDb=db->nDb-1; iDb>=0; iDb--){
  38755. Btree *pExisting = db->aDb[iDb].pBt;
  38756. if( pExisting && pExisting->pBt==pBt ){
  38757. sqlite3_mutex_leave(mutexShared);
  38758. sqlite3_mutex_leave(mutexOpen);
  38759. sqlite3_free(zFullPathname);
  38760. sqlite3_free(p);
  38761. return SQLITE_CONSTRAINT;
  38762. }
  38763. }
  38764. p->pBt = pBt;
  38765. pBt->nRef++;
  38766. break;
  38767. }
  38768. }
  38769. sqlite3_mutex_leave(mutexShared);
  38770. sqlite3_free(zFullPathname);
  38771. }
  38772. #ifdef SQLITE_DEBUG
  38773. else{
  38774. /* In debug mode, we mark all persistent databases as sharable
  38775. ** even when they are not. This exercises the locking code and
  38776. ** gives more opportunity for asserts(sqlite3_mutex_held())
  38777. ** statements to find locking problems.
  38778. */
  38779. p->sharable = 1;
  38780. }
  38781. #endif
  38782. }
  38783. #endif
  38784. if( pBt==0 ){
  38785. /*
  38786. ** The following asserts make sure that structures used by the btree are
  38787. ** the right size. This is to guard against size changes that result
  38788. ** when compiling on a different architecture.
  38789. */
  38790. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  38791. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  38792. assert( sizeof(u32)==4 );
  38793. assert( sizeof(u16)==2 );
  38794. assert( sizeof(Pgno)==4 );
  38795. pBt = sqlite3MallocZero( sizeof(*pBt) );
  38796. if( pBt==0 ){
  38797. rc = SQLITE_NOMEM;
  38798. goto btree_open_out;
  38799. }
  38800. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  38801. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  38802. if( rc==SQLITE_OK ){
  38803. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  38804. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  38805. }
  38806. if( rc!=SQLITE_OK ){
  38807. goto btree_open_out;
  38808. }
  38809. pBt->openFlags = (u8)flags;
  38810. pBt->db = db;
  38811. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  38812. p->pBt = pBt;
  38813. pBt->pCursor = 0;
  38814. pBt->pPage1 = 0;
  38815. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  38816. #ifdef SQLITE_SECURE_DELETE
  38817. pBt->btsFlags |= BTS_SECURE_DELETE;
  38818. #endif
  38819. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  38820. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  38821. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  38822. pBt->pageSize = 0;
  38823. #ifndef SQLITE_OMIT_AUTOVACUUM
  38824. /* If the magic name ":memory:" will create an in-memory database, then
  38825. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  38826. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  38827. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  38828. ** regular file-name. In this case the auto-vacuum applies as per normal.
  38829. */
  38830. if( zFilename && !isMemdb ){
  38831. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  38832. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  38833. }
  38834. #endif
  38835. nReserve = 0;
  38836. }else{
  38837. nReserve = zDbHeader[20];
  38838. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  38839. #ifndef SQLITE_OMIT_AUTOVACUUM
  38840. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  38841. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  38842. #endif
  38843. }
  38844. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  38845. if( rc ) goto btree_open_out;
  38846. pBt->usableSize = pBt->pageSize - nReserve;
  38847. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  38848. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38849. /* Add the new BtShared object to the linked list sharable BtShareds.
  38850. */
  38851. if( p->sharable ){
  38852. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  38853. pBt->nRef = 1;
  38854. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  38855. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  38856. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  38857. if( pBt->mutex==0 ){
  38858. rc = SQLITE_NOMEM;
  38859. db->mallocFailed = 0;
  38860. goto btree_open_out;
  38861. }
  38862. }
  38863. sqlite3_mutex_enter(mutexShared);
  38864. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  38865. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  38866. sqlite3_mutex_leave(mutexShared);
  38867. }
  38868. #endif
  38869. }
  38870. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  38871. /* If the new Btree uses a sharable pBtShared, then link the new
  38872. ** Btree into the list of all sharable Btrees for the same connection.
  38873. ** The list is kept in ascending order by pBt address.
  38874. */
  38875. if( p->sharable ){
  38876. int i;
  38877. Btree *pSib;
  38878. for(i=0; i<db->nDb; i++){
  38879. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  38880. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  38881. if( p->pBt<pSib->pBt ){
  38882. p->pNext = pSib;
  38883. p->pPrev = 0;
  38884. pSib->pPrev = p;
  38885. }else{
  38886. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  38887. pSib = pSib->pNext;
  38888. }
  38889. p->pNext = pSib->pNext;
  38890. p->pPrev = pSib;
  38891. if( p->pNext ){
  38892. p->pNext->pPrev = p;
  38893. }
  38894. pSib->pNext = p;
  38895. }
  38896. break;
  38897. }
  38898. }
  38899. }
  38900. #endif
  38901. *ppBtree = p;
  38902. btree_open_out:
  38903. if( rc!=SQLITE_OK ){
  38904. if( pBt && pBt->pPager ){
  38905. sqlite3PagerClose(pBt->pPager);
  38906. }
  38907. sqlite3_free(pBt);
  38908. sqlite3_free(p);
  38909. *ppBtree = 0;
  38910. }else{
  38911. /* If the B-Tree was successfully opened, set the pager-cache size to the
  38912. ** default value. Except, when opening on an existing shared pager-cache,
  38913. ** do not change the pager-cache size.
  38914. */
  38915. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  38916. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  38917. }
  38918. }
  38919. if( mutexOpen ){
  38920. assert( sqlite3_mutex_held(mutexOpen) );
  38921. sqlite3_mutex_leave(mutexOpen);
  38922. }
  38923. return rc;
  38924. }
  38925. /*
  38926. ** Decrement the BtShared.nRef counter. When it reaches zero,
  38927. ** remove the BtShared structure from the sharing list. Return
  38928. ** true if the BtShared.nRef counter reaches zero and return
  38929. ** false if it is still positive.
  38930. */
  38931. static int removeFromSharingList(BtShared *pBt){
  38932. #ifndef SQLITE_OMIT_SHARED_CACHE
  38933. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  38934. BtShared *pList;
  38935. int removed = 0;
  38936. assert( sqlite3_mutex_notheld(pBt->mutex) );
  38937. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  38938. sqlite3_mutex_enter(pMaster);
  38939. pBt->nRef--;
  38940. if( pBt->nRef<=0 ){
  38941. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  38942. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  38943. }else{
  38944. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  38945. while( ALWAYS(pList) && pList->pNext!=pBt ){
  38946. pList=pList->pNext;
  38947. }
  38948. if( ALWAYS(pList) ){
  38949. pList->pNext = pBt->pNext;
  38950. }
  38951. }
  38952. if( SQLITE_THREADSAFE ){
  38953. sqlite3_mutex_free(pBt->mutex);
  38954. }
  38955. removed = 1;
  38956. }
  38957. sqlite3_mutex_leave(pMaster);
  38958. return removed;
  38959. #else
  38960. return 1;
  38961. #endif
  38962. }
  38963. /*
  38964. ** Make sure pBt->pTmpSpace points to an allocation of
  38965. ** MX_CELL_SIZE(pBt) bytes.
  38966. */
  38967. static void allocateTempSpace(BtShared *pBt){
  38968. if( !pBt->pTmpSpace ){
  38969. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  38970. /* One of the uses of pBt->pTmpSpace is to format cells before
  38971. ** inserting them into a leaf page (function fillInCell()). If
  38972. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  38973. ** by the various routines that manipulate binary cells. Which
  38974. ** can mean that fillInCell() only initializes the first 2 or 3
  38975. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  38976. ** it into a database page. This is not actually a problem, but it
  38977. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  38978. ** data is passed to system call write(). So to avoid this error,
  38979. ** zero the first 4 bytes of temp space here. */
  38980. if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
  38981. }
  38982. }
  38983. /*
  38984. ** Free the pBt->pTmpSpace allocation
  38985. */
  38986. static void freeTempSpace(BtShared *pBt){
  38987. sqlite3PageFree( pBt->pTmpSpace);
  38988. pBt->pTmpSpace = 0;
  38989. }
  38990. /*
  38991. ** Close an open database and invalidate all cursors.
  38992. */
  38993. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  38994. BtShared *pBt = p->pBt;
  38995. BtCursor *pCur;
  38996. /* Close all cursors opened via this handle. */
  38997. assert( sqlite3_mutex_held(p->db->mutex) );
  38998. sqlite3BtreeEnter(p);
  38999. pCur = pBt->pCursor;
  39000. while( pCur ){
  39001. BtCursor *pTmp = pCur;
  39002. pCur = pCur->pNext;
  39003. if( pTmp->pBtree==p ){
  39004. sqlite3BtreeCloseCursor(pTmp);
  39005. }
  39006. }
  39007. /* Rollback any active transaction and free the handle structure.
  39008. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  39009. ** this handle.
  39010. */
  39011. sqlite3BtreeRollback(p, SQLITE_OK);
  39012. sqlite3BtreeLeave(p);
  39013. /* If there are still other outstanding references to the shared-btree
  39014. ** structure, return now. The remainder of this procedure cleans
  39015. ** up the shared-btree.
  39016. */
  39017. assert( p->wantToLock==0 && p->locked==0 );
  39018. if( !p->sharable || removeFromSharingList(pBt) ){
  39019. /* The pBt is no longer on the sharing list, so we can access
  39020. ** it without having to hold the mutex.
  39021. **
  39022. ** Clean out and delete the BtShared object.
  39023. */
  39024. assert( !pBt->pCursor );
  39025. sqlite3PagerClose(pBt->pPager);
  39026. if( pBt->xFreeSchema && pBt->pSchema ){
  39027. pBt->xFreeSchema(pBt->pSchema);
  39028. }
  39029. sqlite3DbFree(0, pBt->pSchema);
  39030. freeTempSpace(pBt);
  39031. sqlite3_free(pBt);
  39032. }
  39033. #ifndef SQLITE_OMIT_SHARED_CACHE
  39034. assert( p->wantToLock==0 );
  39035. assert( p->locked==0 );
  39036. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  39037. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  39038. #endif
  39039. sqlite3_free(p);
  39040. return SQLITE_OK;
  39041. }
  39042. /*
  39043. ** Change the limit on the number of pages allowed in the cache.
  39044. **
  39045. ** The maximum number of cache pages is set to the absolute
  39046. ** value of mxPage. If mxPage is negative, the pager will
  39047. ** operate asynchronously - it will not stop to do fsync()s
  39048. ** to insure data is written to the disk surface before
  39049. ** continuing. Transactions still work if synchronous is off,
  39050. ** and the database cannot be corrupted if this program
  39051. ** crashes. But if the operating system crashes or there is
  39052. ** an abrupt power failure when synchronous is off, the database
  39053. ** could be left in an inconsistent and unrecoverable state.
  39054. ** Synchronous is on by default so database corruption is not
  39055. ** normally a worry.
  39056. */
  39057. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  39058. BtShared *pBt = p->pBt;
  39059. assert( sqlite3_mutex_held(p->db->mutex) );
  39060. sqlite3BtreeEnter(p);
  39061. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  39062. sqlite3BtreeLeave(p);
  39063. return SQLITE_OK;
  39064. }
  39065. /*
  39066. ** Change the limit on the amount of the database file that may be
  39067. ** memory mapped.
  39068. */
  39069. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  39070. BtShared *pBt = p->pBt;
  39071. assert( sqlite3_mutex_held(p->db->mutex) );
  39072. sqlite3BtreeEnter(p);
  39073. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  39074. sqlite3BtreeLeave(p);
  39075. return SQLITE_OK;
  39076. }
  39077. /*
  39078. ** Change the way data is synced to disk in order to increase or decrease
  39079. ** how well the database resists damage due to OS crashes and power
  39080. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  39081. ** there is a high probability of damage) Level 2 is the default. There
  39082. ** is a very low but non-zero probability of damage. Level 3 reduces the
  39083. ** probability of damage to near zero but with a write performance reduction.
  39084. */
  39085. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  39086. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  39087. Btree *p, /* The btree to set the safety level on */
  39088. unsigned pgFlags /* Various PAGER_* flags */
  39089. ){
  39090. BtShared *pBt = p->pBt;
  39091. assert( sqlite3_mutex_held(p->db->mutex) );
  39092. sqlite3BtreeEnter(p);
  39093. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  39094. sqlite3BtreeLeave(p);
  39095. return SQLITE_OK;
  39096. }
  39097. #endif
  39098. /*
  39099. ** Return TRUE if the given btree is set to safety level 1. In other
  39100. ** words, return TRUE if no sync() occurs on the disk files.
  39101. */
  39102. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  39103. BtShared *pBt = p->pBt;
  39104. int rc;
  39105. assert( sqlite3_mutex_held(p->db->mutex) );
  39106. sqlite3BtreeEnter(p);
  39107. assert( pBt && pBt->pPager );
  39108. rc = sqlite3PagerNosync(pBt->pPager);
  39109. sqlite3BtreeLeave(p);
  39110. return rc;
  39111. }
  39112. /*
  39113. ** Change the default pages size and the number of reserved bytes per page.
  39114. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  39115. ** without changing anything.
  39116. **
  39117. ** The page size must be a power of 2 between 512 and 65536. If the page
  39118. ** size supplied does not meet this constraint then the page size is not
  39119. ** changed.
  39120. **
  39121. ** Page sizes are constrained to be a power of two so that the region
  39122. ** of the database file used for locking (beginning at PENDING_BYTE,
  39123. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  39124. ** at the beginning of a page.
  39125. **
  39126. ** If parameter nReserve is less than zero, then the number of reserved
  39127. ** bytes per page is left unchanged.
  39128. **
  39129. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  39130. ** and autovacuum mode can no longer be changed.
  39131. */
  39132. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  39133. int rc = SQLITE_OK;
  39134. BtShared *pBt = p->pBt;
  39135. assert( nReserve>=-1 && nReserve<=255 );
  39136. sqlite3BtreeEnter(p);
  39137. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  39138. sqlite3BtreeLeave(p);
  39139. return SQLITE_READONLY;
  39140. }
  39141. if( nReserve<0 ){
  39142. nReserve = pBt->pageSize - pBt->usableSize;
  39143. }
  39144. assert( nReserve>=0 && nReserve<=255 );
  39145. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  39146. ((pageSize-1)&pageSize)==0 ){
  39147. assert( (pageSize & 7)==0 );
  39148. assert( !pBt->pPage1 && !pBt->pCursor );
  39149. pBt->pageSize = (u32)pageSize;
  39150. freeTempSpace(pBt);
  39151. }
  39152. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  39153. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  39154. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  39155. sqlite3BtreeLeave(p);
  39156. return rc;
  39157. }
  39158. /*
  39159. ** Return the currently defined page size
  39160. */
  39161. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  39162. return p->pBt->pageSize;
  39163. }
  39164. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  39165. /*
  39166. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  39167. ** may only be called if it is guaranteed that the b-tree mutex is already
  39168. ** held.
  39169. **
  39170. ** This is useful in one special case in the backup API code where it is
  39171. ** known that the shared b-tree mutex is held, but the mutex on the
  39172. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  39173. ** were to be called, it might collide with some other operation on the
  39174. ** database handle that owns *p, causing undefined behavior.
  39175. */
  39176. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  39177. assert( sqlite3_mutex_held(p->pBt->mutex) );
  39178. return p->pBt->pageSize - p->pBt->usableSize;
  39179. }
  39180. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  39181. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  39182. /*
  39183. ** Return the number of bytes of space at the end of every page that
  39184. ** are intentually left unused. This is the "reserved" space that is
  39185. ** sometimes used by extensions.
  39186. */
  39187. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  39188. int n;
  39189. sqlite3BtreeEnter(p);
  39190. n = p->pBt->pageSize - p->pBt->usableSize;
  39191. sqlite3BtreeLeave(p);
  39192. return n;
  39193. }
  39194. /*
  39195. ** Set the maximum page count for a database if mxPage is positive.
  39196. ** No changes are made if mxPage is 0 or negative.
  39197. ** Regardless of the value of mxPage, return the maximum page count.
  39198. */
  39199. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  39200. int n;
  39201. sqlite3BtreeEnter(p);
  39202. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  39203. sqlite3BtreeLeave(p);
  39204. return n;
  39205. }
  39206. /*
  39207. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  39208. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  39209. ** setting after the change.
  39210. */
  39211. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  39212. int b;
  39213. if( p==0 ) return 0;
  39214. sqlite3BtreeEnter(p);
  39215. if( newFlag>=0 ){
  39216. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  39217. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  39218. }
  39219. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  39220. sqlite3BtreeLeave(p);
  39221. return b;
  39222. }
  39223. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  39224. /*
  39225. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  39226. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  39227. ** is disabled. The default value for the auto-vacuum property is
  39228. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  39229. */
  39230. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  39231. #ifdef SQLITE_OMIT_AUTOVACUUM
  39232. return SQLITE_READONLY;
  39233. #else
  39234. BtShared *pBt = p->pBt;
  39235. int rc = SQLITE_OK;
  39236. u8 av = (u8)autoVacuum;
  39237. sqlite3BtreeEnter(p);
  39238. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  39239. rc = SQLITE_READONLY;
  39240. }else{
  39241. pBt->autoVacuum = av ?1:0;
  39242. pBt->incrVacuum = av==2 ?1:0;
  39243. }
  39244. sqlite3BtreeLeave(p);
  39245. return rc;
  39246. #endif
  39247. }
  39248. /*
  39249. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  39250. ** enabled 1 is returned. Otherwise 0.
  39251. */
  39252. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  39253. #ifdef SQLITE_OMIT_AUTOVACUUM
  39254. return BTREE_AUTOVACUUM_NONE;
  39255. #else
  39256. int rc;
  39257. sqlite3BtreeEnter(p);
  39258. rc = (
  39259. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  39260. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  39261. BTREE_AUTOVACUUM_INCR
  39262. );
  39263. sqlite3BtreeLeave(p);
  39264. return rc;
  39265. #endif
  39266. }
  39267. /*
  39268. ** Get a reference to pPage1 of the database file. This will
  39269. ** also acquire a readlock on that file.
  39270. **
  39271. ** SQLITE_OK is returned on success. If the file is not a
  39272. ** well-formed database file, then SQLITE_CORRUPT is returned.
  39273. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  39274. ** is returned if we run out of memory.
  39275. */
  39276. static int lockBtree(BtShared *pBt){
  39277. int rc; /* Result code from subfunctions */
  39278. MemPage *pPage1; /* Page 1 of the database file */
  39279. int nPage; /* Number of pages in the database */
  39280. int nPageFile = 0; /* Number of pages in the database file */
  39281. int nPageHeader; /* Number of pages in the database according to hdr */
  39282. assert( sqlite3_mutex_held(pBt->mutex) );
  39283. assert( pBt->pPage1==0 );
  39284. rc = sqlite3PagerSharedLock(pBt->pPager);
  39285. if( rc!=SQLITE_OK ) return rc;
  39286. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  39287. if( rc!=SQLITE_OK ) return rc;
  39288. /* Do some checking to help insure the file we opened really is
  39289. ** a valid database file.
  39290. */
  39291. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  39292. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  39293. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  39294. nPage = nPageFile;
  39295. }
  39296. if( nPage>0 ){
  39297. u32 pageSize;
  39298. u32 usableSize;
  39299. u8 *page1 = pPage1->aData;
  39300. rc = SQLITE_NOTADB;
  39301. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  39302. goto page1_init_failed;
  39303. }
  39304. #ifdef SQLITE_OMIT_WAL
  39305. if( page1[18]>1 ){
  39306. pBt->btsFlags |= BTS_READ_ONLY;
  39307. }
  39308. if( page1[19]>1 ){
  39309. goto page1_init_failed;
  39310. }
  39311. #else
  39312. if( page1[18]>2 ){
  39313. pBt->btsFlags |= BTS_READ_ONLY;
  39314. }
  39315. if( page1[19]>2 ){
  39316. goto page1_init_failed;
  39317. }
  39318. /* If the write version is set to 2, this database should be accessed
  39319. ** in WAL mode. If the log is not already open, open it now. Then
  39320. ** return SQLITE_OK and return without populating BtShared.pPage1.
  39321. ** The caller detects this and calls this function again. This is
  39322. ** required as the version of page 1 currently in the page1 buffer
  39323. ** may not be the latest version - there may be a newer one in the log
  39324. ** file.
  39325. */
  39326. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  39327. int isOpen = 0;
  39328. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  39329. if( rc!=SQLITE_OK ){
  39330. goto page1_init_failed;
  39331. }else if( isOpen==0 ){
  39332. releasePage(pPage1);
  39333. return SQLITE_OK;
  39334. }
  39335. rc = SQLITE_NOTADB;
  39336. }
  39337. #endif
  39338. /* The maximum embedded fraction must be exactly 25%. And the minimum
  39339. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  39340. ** The original design allowed these amounts to vary, but as of
  39341. ** version 3.6.0, we require them to be fixed.
  39342. */
  39343. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  39344. goto page1_init_failed;
  39345. }
  39346. pageSize = (page1[16]<<8) | (page1[17]<<16);
  39347. if( ((pageSize-1)&pageSize)!=0
  39348. || pageSize>SQLITE_MAX_PAGE_SIZE
  39349. || pageSize<=256
  39350. ){
  39351. goto page1_init_failed;
  39352. }
  39353. assert( (pageSize & 7)==0 );
  39354. usableSize = pageSize - page1[20];
  39355. if( (u32)pageSize!=pBt->pageSize ){
  39356. /* After reading the first page of the database assuming a page size
  39357. ** of BtShared.pageSize, we have discovered that the page-size is
  39358. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  39359. ** zero and return SQLITE_OK. The caller will call this function
  39360. ** again with the correct page-size.
  39361. */
  39362. releasePage(pPage1);
  39363. pBt->usableSize = usableSize;
  39364. pBt->pageSize = pageSize;
  39365. freeTempSpace(pBt);
  39366. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  39367. pageSize-usableSize);
  39368. return rc;
  39369. }
  39370. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  39371. rc = SQLITE_CORRUPT_BKPT;
  39372. goto page1_init_failed;
  39373. }
  39374. if( usableSize<480 ){
  39375. goto page1_init_failed;
  39376. }
  39377. pBt->pageSize = pageSize;
  39378. pBt->usableSize = usableSize;
  39379. #ifndef SQLITE_OMIT_AUTOVACUUM
  39380. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  39381. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  39382. #endif
  39383. }
  39384. /* maxLocal is the maximum amount of payload to store locally for
  39385. ** a cell. Make sure it is small enough so that at least minFanout
  39386. ** cells can will fit on one page. We assume a 10-byte page header.
  39387. ** Besides the payload, the cell must store:
  39388. ** 2-byte pointer to the cell
  39389. ** 4-byte child pointer
  39390. ** 9-byte nKey value
  39391. ** 4-byte nData value
  39392. ** 4-byte overflow page pointer
  39393. ** So a cell consists of a 2-byte pointer, a header which is as much as
  39394. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  39395. ** page pointer.
  39396. */
  39397. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  39398. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  39399. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  39400. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  39401. if( pBt->maxLocal>127 ){
  39402. pBt->max1bytePayload = 127;
  39403. }else{
  39404. pBt->max1bytePayload = (u8)pBt->maxLocal;
  39405. }
  39406. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  39407. pBt->pPage1 = pPage1;
  39408. pBt->nPage = nPage;
  39409. return SQLITE_OK;
  39410. page1_init_failed:
  39411. releasePage(pPage1);
  39412. pBt->pPage1 = 0;
  39413. return rc;
  39414. }
  39415. #ifndef NDEBUG
  39416. /*
  39417. ** Return the number of cursors open on pBt. This is for use
  39418. ** in assert() expressions, so it is only compiled if NDEBUG is not
  39419. ** defined.
  39420. **
  39421. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  39422. ** false then all cursors are counted.
  39423. **
  39424. ** For the purposes of this routine, a cursor is any cursor that
  39425. ** is capable of reading or writing to the databse. Cursors that
  39426. ** have been tripped into the CURSOR_FAULT state are not counted.
  39427. */
  39428. static int countValidCursors(BtShared *pBt, int wrOnly){
  39429. BtCursor *pCur;
  39430. int r = 0;
  39431. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  39432. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  39433. }
  39434. return r;
  39435. }
  39436. #endif
  39437. /*
  39438. ** If there are no outstanding cursors and we are not in the middle
  39439. ** of a transaction but there is a read lock on the database, then
  39440. ** this routine unrefs the first page of the database file which
  39441. ** has the effect of releasing the read lock.
  39442. **
  39443. ** If there is a transaction in progress, this routine is a no-op.
  39444. */
  39445. static void unlockBtreeIfUnused(BtShared *pBt){
  39446. assert( sqlite3_mutex_held(pBt->mutex) );
  39447. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  39448. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  39449. assert( pBt->pPage1->aData );
  39450. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  39451. assert( pBt->pPage1->aData );
  39452. releasePage(pBt->pPage1);
  39453. pBt->pPage1 = 0;
  39454. }
  39455. }
  39456. /*
  39457. ** If pBt points to an empty file then convert that empty file
  39458. ** into a new empty database by initializing the first page of
  39459. ** the database.
  39460. */
  39461. static int newDatabase(BtShared *pBt){
  39462. MemPage *pP1;
  39463. unsigned char *data;
  39464. int rc;
  39465. assert( sqlite3_mutex_held(pBt->mutex) );
  39466. if( pBt->nPage>0 ){
  39467. return SQLITE_OK;
  39468. }
  39469. pP1 = pBt->pPage1;
  39470. assert( pP1!=0 );
  39471. data = pP1->aData;
  39472. rc = sqlite3PagerWrite(pP1->pDbPage);
  39473. if( rc ) return rc;
  39474. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  39475. assert( sizeof(zMagicHeader)==16 );
  39476. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  39477. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  39478. data[18] = 1;
  39479. data[19] = 1;
  39480. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  39481. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  39482. data[21] = 64;
  39483. data[22] = 32;
  39484. data[23] = 32;
  39485. memset(&data[24], 0, 100-24);
  39486. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  39487. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  39488. #ifndef SQLITE_OMIT_AUTOVACUUM
  39489. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  39490. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  39491. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  39492. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  39493. #endif
  39494. pBt->nPage = 1;
  39495. data[31] = 1;
  39496. return SQLITE_OK;
  39497. }
  39498. /*
  39499. ** Initialize the first page of the database file (creating a database
  39500. ** consisting of a single page and no schema objects). Return SQLITE_OK
  39501. ** if successful, or an SQLite error code otherwise.
  39502. */
  39503. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  39504. int rc;
  39505. sqlite3BtreeEnter(p);
  39506. p->pBt->nPage = 0;
  39507. rc = newDatabase(p->pBt);
  39508. sqlite3BtreeLeave(p);
  39509. return rc;
  39510. }
  39511. /*
  39512. ** Attempt to start a new transaction. A write-transaction
  39513. ** is started if the second argument is nonzero, otherwise a read-
  39514. ** transaction. If the second argument is 2 or more and exclusive
  39515. ** transaction is started, meaning that no other process is allowed
  39516. ** to access the database. A preexisting transaction may not be
  39517. ** upgraded to exclusive by calling this routine a second time - the
  39518. ** exclusivity flag only works for a new transaction.
  39519. **
  39520. ** A write-transaction must be started before attempting any
  39521. ** changes to the database. None of the following routines
  39522. ** will work unless a transaction is started first:
  39523. **
  39524. ** sqlite3BtreeCreateTable()
  39525. ** sqlite3BtreeCreateIndex()
  39526. ** sqlite3BtreeClearTable()
  39527. ** sqlite3BtreeDropTable()
  39528. ** sqlite3BtreeInsert()
  39529. ** sqlite3BtreeDelete()
  39530. ** sqlite3BtreeUpdateMeta()
  39531. **
  39532. ** If an initial attempt to acquire the lock fails because of lock contention
  39533. ** and the database was previously unlocked, then invoke the busy handler
  39534. ** if there is one. But if there was previously a read-lock, do not
  39535. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  39536. ** returned when there is already a read-lock in order to avoid a deadlock.
  39537. **
  39538. ** Suppose there are two processes A and B. A has a read lock and B has
  39539. ** a reserved lock. B tries to promote to exclusive but is blocked because
  39540. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  39541. ** One or the other of the two processes must give way or there can be
  39542. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  39543. ** when A already has a read lock, we encourage A to give up and let B
  39544. ** proceed.
  39545. */
  39546. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  39547. sqlite3 *pBlock = 0;
  39548. BtShared *pBt = p->pBt;
  39549. int rc = SQLITE_OK;
  39550. sqlite3BtreeEnter(p);
  39551. btreeIntegrity(p);
  39552. /* If the btree is already in a write-transaction, or it
  39553. ** is already in a read-transaction and a read-transaction
  39554. ** is requested, this is a no-op.
  39555. */
  39556. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  39557. goto trans_begun;
  39558. }
  39559. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  39560. /* Write transactions are not possible on a read-only database */
  39561. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  39562. rc = SQLITE_READONLY;
  39563. goto trans_begun;
  39564. }
  39565. #ifndef SQLITE_OMIT_SHARED_CACHE
  39566. /* If another database handle has already opened a write transaction
  39567. ** on this shared-btree structure and a second write transaction is
  39568. ** requested, return SQLITE_LOCKED.
  39569. */
  39570. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  39571. || (pBt->btsFlags & BTS_PENDING)!=0
  39572. ){
  39573. pBlock = pBt->pWriter->db;
  39574. }else if( wrflag>1 ){
  39575. BtLock *pIter;
  39576. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  39577. if( pIter->pBtree!=p ){
  39578. pBlock = pIter->pBtree->db;
  39579. break;
  39580. }
  39581. }
  39582. }
  39583. if( pBlock ){
  39584. sqlite3ConnectionBlocked(p->db, pBlock);
  39585. rc = SQLITE_LOCKED_SHAREDCACHE;
  39586. goto trans_begun;
  39587. }
  39588. #endif
  39589. /* Any read-only or read-write transaction implies a read-lock on
  39590. ** page 1. So if some other shared-cache client already has a write-lock
  39591. ** on page 1, the transaction cannot be opened. */
  39592. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  39593. if( SQLITE_OK!=rc ) goto trans_begun;
  39594. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  39595. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  39596. do {
  39597. /* Call lockBtree() until either pBt->pPage1 is populated or
  39598. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  39599. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  39600. ** reading page 1 it discovers that the page-size of the database
  39601. ** file is not pBt->pageSize. In this case lockBtree() will update
  39602. ** pBt->pageSize to the page-size of the file on disk.
  39603. */
  39604. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  39605. if( rc==SQLITE_OK && wrflag ){
  39606. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  39607. rc = SQLITE_READONLY;
  39608. }else{
  39609. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  39610. if( rc==SQLITE_OK ){
  39611. rc = newDatabase(pBt);
  39612. }
  39613. }
  39614. }
  39615. if( rc!=SQLITE_OK ){
  39616. unlockBtreeIfUnused(pBt);
  39617. }
  39618. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  39619. btreeInvokeBusyHandler(pBt) );
  39620. if( rc==SQLITE_OK ){
  39621. if( p->inTrans==TRANS_NONE ){
  39622. pBt->nTransaction++;
  39623. #ifndef SQLITE_OMIT_SHARED_CACHE
  39624. if( p->sharable ){
  39625. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  39626. p->lock.eLock = READ_LOCK;
  39627. p->lock.pNext = pBt->pLock;
  39628. pBt->pLock = &p->lock;
  39629. }
  39630. #endif
  39631. }
  39632. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  39633. if( p->inTrans>pBt->inTransaction ){
  39634. pBt->inTransaction = p->inTrans;
  39635. }
  39636. if( wrflag ){
  39637. MemPage *pPage1 = pBt->pPage1;
  39638. #ifndef SQLITE_OMIT_SHARED_CACHE
  39639. assert( !pBt->pWriter );
  39640. pBt->pWriter = p;
  39641. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  39642. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  39643. #endif
  39644. /* If the db-size header field is incorrect (as it may be if an old
  39645. ** client has been writing the database file), update it now. Doing
  39646. ** this sooner rather than later means the database size can safely
  39647. ** re-read the database size from page 1 if a savepoint or transaction
  39648. ** rollback occurs within the transaction.
  39649. */
  39650. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  39651. rc = sqlite3PagerWrite(pPage1->pDbPage);
  39652. if( rc==SQLITE_OK ){
  39653. put4byte(&pPage1->aData[28], pBt->nPage);
  39654. }
  39655. }
  39656. }
  39657. }
  39658. trans_begun:
  39659. if( rc==SQLITE_OK && wrflag ){
  39660. /* This call makes sure that the pager has the correct number of
  39661. ** open savepoints. If the second parameter is greater than 0 and
  39662. ** the sub-journal is not already open, then it will be opened here.
  39663. */
  39664. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  39665. }
  39666. btreeIntegrity(p);
  39667. sqlite3BtreeLeave(p);
  39668. return rc;
  39669. }
  39670. #ifndef SQLITE_OMIT_AUTOVACUUM
  39671. /*
  39672. ** Set the pointer-map entries for all children of page pPage. Also, if
  39673. ** pPage contains cells that point to overflow pages, set the pointer
  39674. ** map entries for the overflow pages as well.
  39675. */
  39676. static int setChildPtrmaps(MemPage *pPage){
  39677. int i; /* Counter variable */
  39678. int nCell; /* Number of cells in page pPage */
  39679. int rc; /* Return code */
  39680. BtShared *pBt = pPage->pBt;
  39681. u8 isInitOrig = pPage->isInit;
  39682. Pgno pgno = pPage->pgno;
  39683. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39684. rc = btreeInitPage(pPage);
  39685. if( rc!=SQLITE_OK ){
  39686. goto set_child_ptrmaps_out;
  39687. }
  39688. nCell = pPage->nCell;
  39689. for(i=0; i<nCell; i++){
  39690. u8 *pCell = findCell(pPage, i);
  39691. ptrmapPutOvflPtr(pPage, pCell, &rc);
  39692. if( !pPage->leaf ){
  39693. Pgno childPgno = get4byte(pCell);
  39694. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  39695. }
  39696. }
  39697. if( !pPage->leaf ){
  39698. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  39699. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  39700. }
  39701. set_child_ptrmaps_out:
  39702. pPage->isInit = isInitOrig;
  39703. return rc;
  39704. }
  39705. /*
  39706. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  39707. ** that it points to iTo. Parameter eType describes the type of pointer to
  39708. ** be modified, as follows:
  39709. **
  39710. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  39711. ** page of pPage.
  39712. **
  39713. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  39714. ** page pointed to by one of the cells on pPage.
  39715. **
  39716. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  39717. ** overflow page in the list.
  39718. */
  39719. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  39720. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  39721. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  39722. if( eType==PTRMAP_OVERFLOW2 ){
  39723. /* The pointer is always the first 4 bytes of the page in this case. */
  39724. if( get4byte(pPage->aData)!=iFrom ){
  39725. return SQLITE_CORRUPT_BKPT;
  39726. }
  39727. put4byte(pPage->aData, iTo);
  39728. }else{
  39729. u8 isInitOrig = pPage->isInit;
  39730. int i;
  39731. int nCell;
  39732. btreeInitPage(pPage);
  39733. nCell = pPage->nCell;
  39734. for(i=0; i<nCell; i++){
  39735. u8 *pCell = findCell(pPage, i);
  39736. if( eType==PTRMAP_OVERFLOW1 ){
  39737. CellInfo info;
  39738. btreeParseCellPtr(pPage, pCell, &info);
  39739. if( info.iOverflow
  39740. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  39741. && iFrom==get4byte(&pCell[info.iOverflow])
  39742. ){
  39743. put4byte(&pCell[info.iOverflow], iTo);
  39744. break;
  39745. }
  39746. }else{
  39747. if( get4byte(pCell)==iFrom ){
  39748. put4byte(pCell, iTo);
  39749. break;
  39750. }
  39751. }
  39752. }
  39753. if( i==nCell ){
  39754. if( eType!=PTRMAP_BTREE ||
  39755. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  39756. return SQLITE_CORRUPT_BKPT;
  39757. }
  39758. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  39759. }
  39760. pPage->isInit = isInitOrig;
  39761. }
  39762. return SQLITE_OK;
  39763. }
  39764. /*
  39765. ** Move the open database page pDbPage to location iFreePage in the
  39766. ** database. The pDbPage reference remains valid.
  39767. **
  39768. ** The isCommit flag indicates that there is no need to remember that
  39769. ** the journal needs to be sync()ed before database page pDbPage->pgno
  39770. ** can be written to. The caller has already promised not to write to that
  39771. ** page.
  39772. */
  39773. static int relocatePage(
  39774. BtShared *pBt, /* Btree */
  39775. MemPage *pDbPage, /* Open page to move */
  39776. u8 eType, /* Pointer map 'type' entry for pDbPage */
  39777. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  39778. Pgno iFreePage, /* The location to move pDbPage to */
  39779. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  39780. ){
  39781. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  39782. Pgno iDbPage = pDbPage->pgno;
  39783. Pager *pPager = pBt->pPager;
  39784. int rc;
  39785. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  39786. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  39787. assert( sqlite3_mutex_held(pBt->mutex) );
  39788. assert( pDbPage->pBt==pBt );
  39789. /* Move page iDbPage from its current location to page number iFreePage */
  39790. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  39791. iDbPage, iFreePage, iPtrPage, eType));
  39792. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  39793. if( rc!=SQLITE_OK ){
  39794. return rc;
  39795. }
  39796. pDbPage->pgno = iFreePage;
  39797. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  39798. ** that point to overflow pages. The pointer map entries for all these
  39799. ** pages need to be changed.
  39800. **
  39801. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  39802. ** pointer to a subsequent overflow page. If this is the case, then
  39803. ** the pointer map needs to be updated for the subsequent overflow page.
  39804. */
  39805. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  39806. rc = setChildPtrmaps(pDbPage);
  39807. if( rc!=SQLITE_OK ){
  39808. return rc;
  39809. }
  39810. }else{
  39811. Pgno nextOvfl = get4byte(pDbPage->aData);
  39812. if( nextOvfl!=0 ){
  39813. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  39814. if( rc!=SQLITE_OK ){
  39815. return rc;
  39816. }
  39817. }
  39818. }
  39819. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  39820. ** that it points at iFreePage. Also fix the pointer map entry for
  39821. ** iPtrPage.
  39822. */
  39823. if( eType!=PTRMAP_ROOTPAGE ){
  39824. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  39825. if( rc!=SQLITE_OK ){
  39826. return rc;
  39827. }
  39828. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  39829. if( rc!=SQLITE_OK ){
  39830. releasePage(pPtrPage);
  39831. return rc;
  39832. }
  39833. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  39834. releasePage(pPtrPage);
  39835. if( rc==SQLITE_OK ){
  39836. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  39837. }
  39838. }
  39839. return rc;
  39840. }
  39841. /* Forward declaration required by incrVacuumStep(). */
  39842. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  39843. /*
  39844. ** Perform a single step of an incremental-vacuum. If successful, return
  39845. ** SQLITE_OK. If there is no work to do (and therefore no point in
  39846. ** calling this function again), return SQLITE_DONE. Or, if an error
  39847. ** occurs, return some other error code.
  39848. **
  39849. ** More specificly, this function attempts to re-organize the database so
  39850. ** that the last page of the file currently in use is no longer in use.
  39851. **
  39852. ** Parameter nFin is the number of pages that this database would contain
  39853. ** were this function called until it returns SQLITE_DONE.
  39854. **
  39855. ** If the bCommit parameter is non-zero, this function assumes that the
  39856. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  39857. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  39858. ** operation, or false for an incremental vacuum.
  39859. */
  39860. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  39861. Pgno nFreeList; /* Number of pages still on the free-list */
  39862. int rc;
  39863. assert( sqlite3_mutex_held(pBt->mutex) );
  39864. assert( iLastPg>nFin );
  39865. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  39866. u8 eType;
  39867. Pgno iPtrPage;
  39868. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  39869. if( nFreeList==0 ){
  39870. return SQLITE_DONE;
  39871. }
  39872. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  39873. if( rc!=SQLITE_OK ){
  39874. return rc;
  39875. }
  39876. if( eType==PTRMAP_ROOTPAGE ){
  39877. return SQLITE_CORRUPT_BKPT;
  39878. }
  39879. if( eType==PTRMAP_FREEPAGE ){
  39880. if( bCommit==0 ){
  39881. /* Remove the page from the files free-list. This is not required
  39882. ** if bCommit is non-zero. In that case, the free-list will be
  39883. ** truncated to zero after this function returns, so it doesn't
  39884. ** matter if it still contains some garbage entries.
  39885. */
  39886. Pgno iFreePg;
  39887. MemPage *pFreePg;
  39888. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  39889. if( rc!=SQLITE_OK ){
  39890. return rc;
  39891. }
  39892. assert( iFreePg==iLastPg );
  39893. releasePage(pFreePg);
  39894. }
  39895. } else {
  39896. Pgno iFreePg; /* Index of free page to move pLastPg to */
  39897. MemPage *pLastPg;
  39898. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  39899. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  39900. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  39901. if( rc!=SQLITE_OK ){
  39902. return rc;
  39903. }
  39904. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  39905. ** is swapped with the first free page pulled off the free list.
  39906. **
  39907. ** On the other hand, if bCommit is greater than zero, then keep
  39908. ** looping until a free-page located within the first nFin pages
  39909. ** of the file is found.
  39910. */
  39911. if( bCommit==0 ){
  39912. eMode = BTALLOC_LE;
  39913. iNear = nFin;
  39914. }
  39915. do {
  39916. MemPage *pFreePg;
  39917. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  39918. if( rc!=SQLITE_OK ){
  39919. releasePage(pLastPg);
  39920. return rc;
  39921. }
  39922. releasePage(pFreePg);
  39923. }while( bCommit && iFreePg>nFin );
  39924. assert( iFreePg<iLastPg );
  39925. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  39926. releasePage(pLastPg);
  39927. if( rc!=SQLITE_OK ){
  39928. return rc;
  39929. }
  39930. }
  39931. }
  39932. if( bCommit==0 ){
  39933. do {
  39934. iLastPg--;
  39935. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  39936. pBt->bDoTruncate = 1;
  39937. pBt->nPage = iLastPg;
  39938. }
  39939. return SQLITE_OK;
  39940. }
  39941. /*
  39942. ** The database opened by the first argument is an auto-vacuum database
  39943. ** nOrig pages in size containing nFree free pages. Return the expected
  39944. ** size of the database in pages following an auto-vacuum operation.
  39945. */
  39946. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  39947. int nEntry; /* Number of entries on one ptrmap page */
  39948. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  39949. Pgno nFin; /* Return value */
  39950. nEntry = pBt->usableSize/5;
  39951. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  39952. nFin = nOrig - nFree - nPtrmap;
  39953. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  39954. nFin--;
  39955. }
  39956. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  39957. nFin--;
  39958. }
  39959. return nFin;
  39960. }
  39961. /*
  39962. ** A write-transaction must be opened before calling this function.
  39963. ** It performs a single unit of work towards an incremental vacuum.
  39964. **
  39965. ** If the incremental vacuum is finished after this function has run,
  39966. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  39967. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  39968. */
  39969. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  39970. int rc;
  39971. BtShared *pBt = p->pBt;
  39972. sqlite3BtreeEnter(p);
  39973. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  39974. if( !pBt->autoVacuum ){
  39975. rc = SQLITE_DONE;
  39976. }else{
  39977. Pgno nOrig = btreePagecount(pBt);
  39978. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  39979. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  39980. if( nOrig<nFin ){
  39981. rc = SQLITE_CORRUPT_BKPT;
  39982. }else if( nFree>0 ){
  39983. rc = saveAllCursors(pBt, 0, 0);
  39984. if( rc==SQLITE_OK ){
  39985. invalidateAllOverflowCache(pBt);
  39986. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  39987. }
  39988. if( rc==SQLITE_OK ){
  39989. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  39990. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  39991. }
  39992. }else{
  39993. rc = SQLITE_DONE;
  39994. }
  39995. }
  39996. sqlite3BtreeLeave(p);
  39997. return rc;
  39998. }
  39999. /*
  40000. ** This routine is called prior to sqlite3PagerCommit when a transaction
  40001. ** is committed for an auto-vacuum database.
  40002. **
  40003. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  40004. ** the database file should be truncated to during the commit process.
  40005. ** i.e. the database has been reorganized so that only the first *pnTrunc
  40006. ** pages are in use.
  40007. */
  40008. static int autoVacuumCommit(BtShared *pBt){
  40009. int rc = SQLITE_OK;
  40010. Pager *pPager = pBt->pPager;
  40011. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  40012. assert( sqlite3_mutex_held(pBt->mutex) );
  40013. invalidateAllOverflowCache(pBt);
  40014. assert(pBt->autoVacuum);
  40015. if( !pBt->incrVacuum ){
  40016. Pgno nFin; /* Number of pages in database after autovacuuming */
  40017. Pgno nFree; /* Number of pages on the freelist initially */
  40018. Pgno iFree; /* The next page to be freed */
  40019. Pgno nOrig; /* Database size before freeing */
  40020. nOrig = btreePagecount(pBt);
  40021. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  40022. /* It is not possible to create a database for which the final page
  40023. ** is either a pointer-map page or the pending-byte page. If one
  40024. ** is encountered, this indicates corruption.
  40025. */
  40026. return SQLITE_CORRUPT_BKPT;
  40027. }
  40028. nFree = get4byte(&pBt->pPage1->aData[36]);
  40029. nFin = finalDbSize(pBt, nOrig, nFree);
  40030. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  40031. if( nFin<nOrig ){
  40032. rc = saveAllCursors(pBt, 0, 0);
  40033. }
  40034. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  40035. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  40036. }
  40037. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  40038. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  40039. put4byte(&pBt->pPage1->aData[32], 0);
  40040. put4byte(&pBt->pPage1->aData[36], 0);
  40041. put4byte(&pBt->pPage1->aData[28], nFin);
  40042. pBt->bDoTruncate = 1;
  40043. pBt->nPage = nFin;
  40044. }
  40045. if( rc!=SQLITE_OK ){
  40046. sqlite3PagerRollback(pPager);
  40047. }
  40048. }
  40049. assert( nRef>=sqlite3PagerRefcount(pPager) );
  40050. return rc;
  40051. }
  40052. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  40053. # define setChildPtrmaps(x) SQLITE_OK
  40054. #endif
  40055. /*
  40056. ** This routine does the first phase of a two-phase commit. This routine
  40057. ** causes a rollback journal to be created (if it does not already exist)
  40058. ** and populated with enough information so that if a power loss occurs
  40059. ** the database can be restored to its original state by playing back
  40060. ** the journal. Then the contents of the journal are flushed out to
  40061. ** the disk. After the journal is safely on oxide, the changes to the
  40062. ** database are written into the database file and flushed to oxide.
  40063. ** At the end of this call, the rollback journal still exists on the
  40064. ** disk and we are still holding all locks, so the transaction has not
  40065. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  40066. ** commit process.
  40067. **
  40068. ** This call is a no-op if no write-transaction is currently active on pBt.
  40069. **
  40070. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  40071. ** the name of a master journal file that should be written into the
  40072. ** individual journal file, or is NULL, indicating no master journal file
  40073. ** (single database transaction).
  40074. **
  40075. ** When this is called, the master journal should already have been
  40076. ** created, populated with this journal pointer and synced to disk.
  40077. **
  40078. ** Once this is routine has returned, the only thing required to commit
  40079. ** the write-transaction for this database file is to delete the journal.
  40080. */
  40081. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  40082. int rc = SQLITE_OK;
  40083. if( p->inTrans==TRANS_WRITE ){
  40084. BtShared *pBt = p->pBt;
  40085. sqlite3BtreeEnter(p);
  40086. #ifndef SQLITE_OMIT_AUTOVACUUM
  40087. if( pBt->autoVacuum ){
  40088. rc = autoVacuumCommit(pBt);
  40089. if( rc!=SQLITE_OK ){
  40090. sqlite3BtreeLeave(p);
  40091. return rc;
  40092. }
  40093. }
  40094. if( pBt->bDoTruncate ){
  40095. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  40096. }
  40097. #endif
  40098. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  40099. sqlite3BtreeLeave(p);
  40100. }
  40101. return rc;
  40102. }
  40103. /*
  40104. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  40105. ** at the conclusion of a transaction.
  40106. */
  40107. static void btreeEndTransaction(Btree *p){
  40108. BtShared *pBt = p->pBt;
  40109. sqlite3 *db = p->db;
  40110. assert( sqlite3BtreeHoldsMutex(p) );
  40111. #ifndef SQLITE_OMIT_AUTOVACUUM
  40112. pBt->bDoTruncate = 0;
  40113. #endif
  40114. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  40115. /* If there are other active statements that belong to this database
  40116. ** handle, downgrade to a read-only transaction. The other statements
  40117. ** may still be reading from the database. */
  40118. downgradeAllSharedCacheTableLocks(p);
  40119. p->inTrans = TRANS_READ;
  40120. }else{
  40121. /* If the handle had any kind of transaction open, decrement the
  40122. ** transaction count of the shared btree. If the transaction count
  40123. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  40124. ** call below will unlock the pager. */
  40125. if( p->inTrans!=TRANS_NONE ){
  40126. clearAllSharedCacheTableLocks(p);
  40127. pBt->nTransaction--;
  40128. if( 0==pBt->nTransaction ){
  40129. pBt->inTransaction = TRANS_NONE;
  40130. }
  40131. }
  40132. /* Set the current transaction state to TRANS_NONE and unlock the
  40133. ** pager if this call closed the only read or write transaction. */
  40134. p->inTrans = TRANS_NONE;
  40135. unlockBtreeIfUnused(pBt);
  40136. }
  40137. btreeIntegrity(p);
  40138. }
  40139. /*
  40140. ** Commit the transaction currently in progress.
  40141. **
  40142. ** This routine implements the second phase of a 2-phase commit. The
  40143. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  40144. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  40145. ** routine did all the work of writing information out to disk and flushing the
  40146. ** contents so that they are written onto the disk platter. All this
  40147. ** routine has to do is delete or truncate or zero the header in the
  40148. ** the rollback journal (which causes the transaction to commit) and
  40149. ** drop locks.
  40150. **
  40151. ** Normally, if an error occurs while the pager layer is attempting to
  40152. ** finalize the underlying journal file, this function returns an error and
  40153. ** the upper layer will attempt a rollback. However, if the second argument
  40154. ** is non-zero then this b-tree transaction is part of a multi-file
  40155. ** transaction. In this case, the transaction has already been committed
  40156. ** (by deleting a master journal file) and the caller will ignore this
  40157. ** functions return code. So, even if an error occurs in the pager layer,
  40158. ** reset the b-tree objects internal state to indicate that the write
  40159. ** transaction has been closed. This is quite safe, as the pager will have
  40160. ** transitioned to the error state.
  40161. **
  40162. ** This will release the write lock on the database file. If there
  40163. ** are no active cursors, it also releases the read lock.
  40164. */
  40165. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  40166. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  40167. sqlite3BtreeEnter(p);
  40168. btreeIntegrity(p);
  40169. /* If the handle has a write-transaction open, commit the shared-btrees
  40170. ** transaction and set the shared state to TRANS_READ.
  40171. */
  40172. if( p->inTrans==TRANS_WRITE ){
  40173. int rc;
  40174. BtShared *pBt = p->pBt;
  40175. assert( pBt->inTransaction==TRANS_WRITE );
  40176. assert( pBt->nTransaction>0 );
  40177. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  40178. if( rc!=SQLITE_OK && bCleanup==0 ){
  40179. sqlite3BtreeLeave(p);
  40180. return rc;
  40181. }
  40182. pBt->inTransaction = TRANS_READ;
  40183. btreeClearHasContent(pBt);
  40184. }
  40185. btreeEndTransaction(p);
  40186. sqlite3BtreeLeave(p);
  40187. return SQLITE_OK;
  40188. }
  40189. /*
  40190. ** Do both phases of a commit.
  40191. */
  40192. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  40193. int rc;
  40194. sqlite3BtreeEnter(p);
  40195. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  40196. if( rc==SQLITE_OK ){
  40197. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  40198. }
  40199. sqlite3BtreeLeave(p);
  40200. return rc;
  40201. }
  40202. /*
  40203. ** This routine sets the state to CURSOR_FAULT and the error
  40204. ** code to errCode for every cursor on BtShared that pBtree
  40205. ** references.
  40206. **
  40207. ** Every cursor is tripped, including cursors that belong
  40208. ** to other database connections that happen to be sharing
  40209. ** the cache with pBtree.
  40210. **
  40211. ** This routine gets called when a rollback occurs.
  40212. ** All cursors using the same cache must be tripped
  40213. ** to prevent them from trying to use the btree after
  40214. ** the rollback. The rollback may have deleted tables
  40215. ** or moved root pages, so it is not sufficient to
  40216. ** save the state of the cursor. The cursor must be
  40217. ** invalidated.
  40218. */
  40219. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  40220. BtCursor *p;
  40221. if( pBtree==0 ) return;
  40222. sqlite3BtreeEnter(pBtree);
  40223. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  40224. int i;
  40225. sqlite3BtreeClearCursor(p);
  40226. p->eState = CURSOR_FAULT;
  40227. p->skipNext = errCode;
  40228. for(i=0; i<=p->iPage; i++){
  40229. releasePage(p->apPage[i]);
  40230. p->apPage[i] = 0;
  40231. }
  40232. }
  40233. sqlite3BtreeLeave(pBtree);
  40234. }
  40235. /*
  40236. ** Rollback the transaction in progress. All cursors will be
  40237. ** invalided by this operation. Any attempt to use a cursor
  40238. ** that was open at the beginning of this operation will result
  40239. ** in an error.
  40240. **
  40241. ** This will release the write lock on the database file. If there
  40242. ** are no active cursors, it also releases the read lock.
  40243. */
  40244. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  40245. int rc;
  40246. BtShared *pBt = p->pBt;
  40247. MemPage *pPage1;
  40248. sqlite3BtreeEnter(p);
  40249. if( tripCode==SQLITE_OK ){
  40250. rc = tripCode = saveAllCursors(pBt, 0, 0);
  40251. }else{
  40252. rc = SQLITE_OK;
  40253. }
  40254. if( tripCode ){
  40255. sqlite3BtreeTripAllCursors(p, tripCode);
  40256. }
  40257. btreeIntegrity(p);
  40258. if( p->inTrans==TRANS_WRITE ){
  40259. int rc2;
  40260. assert( TRANS_WRITE==pBt->inTransaction );
  40261. rc2 = sqlite3PagerRollback(pBt->pPager);
  40262. if( rc2!=SQLITE_OK ){
  40263. rc = rc2;
  40264. }
  40265. /* The rollback may have destroyed the pPage1->aData value. So
  40266. ** call btreeGetPage() on page 1 again to make
  40267. ** sure pPage1->aData is set correctly. */
  40268. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  40269. int nPage = get4byte(28+(u8*)pPage1->aData);
  40270. testcase( nPage==0 );
  40271. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  40272. testcase( pBt->nPage!=nPage );
  40273. pBt->nPage = nPage;
  40274. releasePage(pPage1);
  40275. }
  40276. assert( countValidCursors(pBt, 1)==0 );
  40277. pBt->inTransaction = TRANS_READ;
  40278. btreeClearHasContent(pBt);
  40279. }
  40280. btreeEndTransaction(p);
  40281. sqlite3BtreeLeave(p);
  40282. return rc;
  40283. }
  40284. /*
  40285. ** Start a statement subtransaction. The subtransaction can can be rolled
  40286. ** back independently of the main transaction. You must start a transaction
  40287. ** before starting a subtransaction. The subtransaction is ended automatically
  40288. ** if the main transaction commits or rolls back.
  40289. **
  40290. ** Statement subtransactions are used around individual SQL statements
  40291. ** that are contained within a BEGIN...COMMIT block. If a constraint
  40292. ** error occurs within the statement, the effect of that one statement
  40293. ** can be rolled back without having to rollback the entire transaction.
  40294. **
  40295. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  40296. ** value passed as the second parameter is the total number of savepoints,
  40297. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  40298. ** are no active savepoints and no other statement-transactions open,
  40299. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  40300. ** using the sqlite3BtreeSavepoint() function.
  40301. */
  40302. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  40303. int rc;
  40304. BtShared *pBt = p->pBt;
  40305. sqlite3BtreeEnter(p);
  40306. assert( p->inTrans==TRANS_WRITE );
  40307. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  40308. assert( iStatement>0 );
  40309. assert( iStatement>p->db->nSavepoint );
  40310. assert( pBt->inTransaction==TRANS_WRITE );
  40311. /* At the pager level, a statement transaction is a savepoint with
  40312. ** an index greater than all savepoints created explicitly using
  40313. ** SQL statements. It is illegal to open, release or rollback any
  40314. ** such savepoints while the statement transaction savepoint is active.
  40315. */
  40316. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  40317. sqlite3BtreeLeave(p);
  40318. return rc;
  40319. }
  40320. /*
  40321. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  40322. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  40323. ** savepoint identified by parameter iSavepoint, depending on the value
  40324. ** of op.
  40325. **
  40326. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  40327. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  40328. ** contents of the entire transaction are rolled back. This is different
  40329. ** from a normal transaction rollback, as no locks are released and the
  40330. ** transaction remains open.
  40331. */
  40332. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  40333. int rc = SQLITE_OK;
  40334. if( p && p->inTrans==TRANS_WRITE ){
  40335. BtShared *pBt = p->pBt;
  40336. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  40337. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  40338. sqlite3BtreeEnter(p);
  40339. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  40340. if( rc==SQLITE_OK ){
  40341. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  40342. pBt->nPage = 0;
  40343. }
  40344. rc = newDatabase(pBt);
  40345. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  40346. /* The database size was written into the offset 28 of the header
  40347. ** when the transaction started, so we know that the value at offset
  40348. ** 28 is nonzero. */
  40349. assert( pBt->nPage>0 );
  40350. }
  40351. sqlite3BtreeLeave(p);
  40352. }
  40353. return rc;
  40354. }
  40355. /*
  40356. ** Create a new cursor for the BTree whose root is on the page
  40357. ** iTable. If a read-only cursor is requested, it is assumed that
  40358. ** the caller already has at least a read-only transaction open
  40359. ** on the database already. If a write-cursor is requested, then
  40360. ** the caller is assumed to have an open write transaction.
  40361. **
  40362. ** If wrFlag==0, then the cursor can only be used for reading.
  40363. ** If wrFlag==1, then the cursor can be used for reading or for
  40364. ** writing if other conditions for writing are also met. These
  40365. ** are the conditions that must be met in order for writing to
  40366. ** be allowed:
  40367. **
  40368. ** 1: The cursor must have been opened with wrFlag==1
  40369. **
  40370. ** 2: Other database connections that share the same pager cache
  40371. ** but which are not in the READ_UNCOMMITTED state may not have
  40372. ** cursors open with wrFlag==0 on the same table. Otherwise
  40373. ** the changes made by this write cursor would be visible to
  40374. ** the read cursors in the other database connection.
  40375. **
  40376. ** 3: The database must be writable (not on read-only media)
  40377. **
  40378. ** 4: There must be an active transaction.
  40379. **
  40380. ** No checking is done to make sure that page iTable really is the
  40381. ** root page of a b-tree. If it is not, then the cursor acquired
  40382. ** will not work correctly.
  40383. **
  40384. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  40385. ** on pCur to initialize the memory space prior to invoking this routine.
  40386. */
  40387. static int btreeCursor(
  40388. Btree *p, /* The btree */
  40389. int iTable, /* Root page of table to open */
  40390. int wrFlag, /* 1 to write. 0 read-only */
  40391. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  40392. BtCursor *pCur /* Space for new cursor */
  40393. ){
  40394. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  40395. assert( sqlite3BtreeHoldsMutex(p) );
  40396. assert( wrFlag==0 || wrFlag==1 );
  40397. /* The following assert statements verify that if this is a sharable
  40398. ** b-tree database, the connection is holding the required table locks,
  40399. ** and that no other connection has any open cursor that conflicts with
  40400. ** this lock. */
  40401. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  40402. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  40403. /* Assert that the caller has opened the required transaction. */
  40404. assert( p->inTrans>TRANS_NONE );
  40405. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  40406. assert( pBt->pPage1 && pBt->pPage1->aData );
  40407. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  40408. return SQLITE_READONLY;
  40409. }
  40410. if( iTable==1 && btreePagecount(pBt)==0 ){
  40411. assert( wrFlag==0 );
  40412. iTable = 0;
  40413. }
  40414. /* Now that no other errors can occur, finish filling in the BtCursor
  40415. ** variables and link the cursor into the BtShared list. */
  40416. pCur->pgnoRoot = (Pgno)iTable;
  40417. pCur->iPage = -1;
  40418. pCur->pKeyInfo = pKeyInfo;
  40419. pCur->pBtree = p;
  40420. pCur->pBt = pBt;
  40421. pCur->wrFlag = (u8)wrFlag;
  40422. pCur->pNext = pBt->pCursor;
  40423. if( pCur->pNext ){
  40424. pCur->pNext->pPrev = pCur;
  40425. }
  40426. pBt->pCursor = pCur;
  40427. pCur->eState = CURSOR_INVALID;
  40428. pCur->cachedRowid = 0;
  40429. return SQLITE_OK;
  40430. }
  40431. SQLITE_PRIVATE int sqlite3BtreeCursor(
  40432. Btree *p, /* The btree */
  40433. int iTable, /* Root page of table to open */
  40434. int wrFlag, /* 1 to write. 0 read-only */
  40435. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  40436. BtCursor *pCur /* Write new cursor here */
  40437. ){
  40438. int rc;
  40439. sqlite3BtreeEnter(p);
  40440. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  40441. sqlite3BtreeLeave(p);
  40442. return rc;
  40443. }
  40444. /*
  40445. ** Return the size of a BtCursor object in bytes.
  40446. **
  40447. ** This interfaces is needed so that users of cursors can preallocate
  40448. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  40449. ** to users so they cannot do the sizeof() themselves - they must call
  40450. ** this routine.
  40451. */
  40452. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  40453. return ROUND8(sizeof(BtCursor));
  40454. }
  40455. /*
  40456. ** Initialize memory that will be converted into a BtCursor object.
  40457. **
  40458. ** The simple approach here would be to memset() the entire object
  40459. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  40460. ** do not need to be zeroed and they are large, so we can save a lot
  40461. ** of run-time by skipping the initialization of those elements.
  40462. */
  40463. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  40464. memset(p, 0, offsetof(BtCursor, iPage));
  40465. }
  40466. /*
  40467. ** Set the cached rowid value of every cursor in the same database file
  40468. ** as pCur and having the same root page number as pCur. The value is
  40469. ** set to iRowid.
  40470. **
  40471. ** Only positive rowid values are considered valid for this cache.
  40472. ** The cache is initialized to zero, indicating an invalid cache.
  40473. ** A btree will work fine with zero or negative rowids. We just cannot
  40474. ** cache zero or negative rowids, which means tables that use zero or
  40475. ** negative rowids might run a little slower. But in practice, zero
  40476. ** or negative rowids are very uncommon so this should not be a problem.
  40477. */
  40478. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  40479. BtCursor *p;
  40480. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  40481. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  40482. }
  40483. assert( pCur->cachedRowid==iRowid );
  40484. }
  40485. /*
  40486. ** Return the cached rowid for the given cursor. A negative or zero
  40487. ** return value indicates that the rowid cache is invalid and should be
  40488. ** ignored. If the rowid cache has never before been set, then a
  40489. ** zero is returned.
  40490. */
  40491. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  40492. return pCur->cachedRowid;
  40493. }
  40494. /*
  40495. ** Close a cursor. The read lock on the database file is released
  40496. ** when the last cursor is closed.
  40497. */
  40498. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  40499. Btree *pBtree = pCur->pBtree;
  40500. if( pBtree ){
  40501. int i;
  40502. BtShared *pBt = pCur->pBt;
  40503. sqlite3BtreeEnter(pBtree);
  40504. sqlite3BtreeClearCursor(pCur);
  40505. if( pCur->pPrev ){
  40506. pCur->pPrev->pNext = pCur->pNext;
  40507. }else{
  40508. pBt->pCursor = pCur->pNext;
  40509. }
  40510. if( pCur->pNext ){
  40511. pCur->pNext->pPrev = pCur->pPrev;
  40512. }
  40513. for(i=0; i<=pCur->iPage; i++){
  40514. releasePage(pCur->apPage[i]);
  40515. }
  40516. unlockBtreeIfUnused(pBt);
  40517. invalidateOverflowCache(pCur);
  40518. /* sqlite3_free(pCur); */
  40519. sqlite3BtreeLeave(pBtree);
  40520. }
  40521. return SQLITE_OK;
  40522. }
  40523. /*
  40524. ** Make sure the BtCursor* given in the argument has a valid
  40525. ** BtCursor.info structure. If it is not already valid, call
  40526. ** btreeParseCell() to fill it in.
  40527. **
  40528. ** BtCursor.info is a cache of the information in the current cell.
  40529. ** Using this cache reduces the number of calls to btreeParseCell().
  40530. **
  40531. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  40532. ** compiler to crash when getCellInfo() is implemented as a macro.
  40533. ** But there is a measureable speed advantage to using the macro on gcc
  40534. ** (when less compiler optimizations like -Os or -O0 are used and the
  40535. ** compiler is not doing agressive inlining.) So we use a real function
  40536. ** for MSVC and a macro for everything else. Ticket #2457.
  40537. */
  40538. #ifndef NDEBUG
  40539. static void assertCellInfo(BtCursor *pCur){
  40540. CellInfo info;
  40541. int iPage = pCur->iPage;
  40542. memset(&info, 0, sizeof(info));
  40543. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  40544. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  40545. }
  40546. #else
  40547. #define assertCellInfo(x)
  40548. #endif
  40549. #ifdef _MSC_VER
  40550. /* Use a real function in MSVC to work around bugs in that compiler. */
  40551. static void getCellInfo(BtCursor *pCur){
  40552. if( pCur->info.nSize==0 ){
  40553. int iPage = pCur->iPage;
  40554. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  40555. pCur->validNKey = 1;
  40556. }else{
  40557. assertCellInfo(pCur);
  40558. }
  40559. }
  40560. #else /* if not _MSC_VER */
  40561. /* Use a macro in all other compilers so that the function is inlined */
  40562. #define getCellInfo(pCur) \
  40563. if( pCur->info.nSize==0 ){ \
  40564. int iPage = pCur->iPage; \
  40565. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  40566. pCur->validNKey = 1; \
  40567. }else{ \
  40568. assertCellInfo(pCur); \
  40569. }
  40570. #endif /* _MSC_VER */
  40571. #ifndef NDEBUG /* The next routine used only within assert() statements */
  40572. /*
  40573. ** Return true if the given BtCursor is valid. A valid cursor is one
  40574. ** that is currently pointing to a row in a (non-empty) table.
  40575. ** This is a verification routine is used only within assert() statements.
  40576. */
  40577. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  40578. return pCur && pCur->eState==CURSOR_VALID;
  40579. }
  40580. #endif /* NDEBUG */
  40581. /*
  40582. ** Set *pSize to the size of the buffer needed to hold the value of
  40583. ** the key for the current entry. If the cursor is not pointing
  40584. ** to a valid entry, *pSize is set to 0.
  40585. **
  40586. ** For a table with the INTKEY flag set, this routine returns the key
  40587. ** itself, not the number of bytes in the key.
  40588. **
  40589. ** The caller must position the cursor prior to invoking this routine.
  40590. **
  40591. ** This routine cannot fail. It always returns SQLITE_OK.
  40592. */
  40593. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  40594. assert( cursorHoldsMutex(pCur) );
  40595. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  40596. if( pCur->eState!=CURSOR_VALID ){
  40597. *pSize = 0;
  40598. }else{
  40599. getCellInfo(pCur);
  40600. *pSize = pCur->info.nKey;
  40601. }
  40602. return SQLITE_OK;
  40603. }
  40604. /*
  40605. ** Set *pSize to the number of bytes of data in the entry the
  40606. ** cursor currently points to.
  40607. **
  40608. ** The caller must guarantee that the cursor is pointing to a non-NULL
  40609. ** valid entry. In other words, the calling procedure must guarantee
  40610. ** that the cursor has Cursor.eState==CURSOR_VALID.
  40611. **
  40612. ** Failure is not possible. This function always returns SQLITE_OK.
  40613. ** It might just as well be a procedure (returning void) but we continue
  40614. ** to return an integer result code for historical reasons.
  40615. */
  40616. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  40617. assert( cursorHoldsMutex(pCur) );
  40618. assert( pCur->eState==CURSOR_VALID );
  40619. getCellInfo(pCur);
  40620. *pSize = pCur->info.nData;
  40621. return SQLITE_OK;
  40622. }
  40623. /*
  40624. ** Given the page number of an overflow page in the database (parameter
  40625. ** ovfl), this function finds the page number of the next page in the
  40626. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  40627. ** pointer-map data instead of reading the content of page ovfl to do so.
  40628. **
  40629. ** If an error occurs an SQLite error code is returned. Otherwise:
  40630. **
  40631. ** The page number of the next overflow page in the linked list is
  40632. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  40633. ** list, *pPgnoNext is set to zero.
  40634. **
  40635. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  40636. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  40637. ** reference. It is the responsibility of the caller to call releasePage()
  40638. ** on *ppPage to free the reference. In no reference was obtained (because
  40639. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  40640. ** *ppPage is set to zero.
  40641. */
  40642. static int getOverflowPage(
  40643. BtShared *pBt, /* The database file */
  40644. Pgno ovfl, /* Current overflow page number */
  40645. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  40646. Pgno *pPgnoNext /* OUT: Next overflow page number */
  40647. ){
  40648. Pgno next = 0;
  40649. MemPage *pPage = 0;
  40650. int rc = SQLITE_OK;
  40651. assert( sqlite3_mutex_held(pBt->mutex) );
  40652. assert(pPgnoNext);
  40653. #ifndef SQLITE_OMIT_AUTOVACUUM
  40654. /* Try to find the next page in the overflow list using the
  40655. ** autovacuum pointer-map pages. Guess that the next page in
  40656. ** the overflow list is page number (ovfl+1). If that guess turns
  40657. ** out to be wrong, fall back to loading the data of page
  40658. ** number ovfl to determine the next page number.
  40659. */
  40660. if( pBt->autoVacuum ){
  40661. Pgno pgno;
  40662. Pgno iGuess = ovfl+1;
  40663. u8 eType;
  40664. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  40665. iGuess++;
  40666. }
  40667. if( iGuess<=btreePagecount(pBt) ){
  40668. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  40669. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  40670. next = iGuess;
  40671. rc = SQLITE_DONE;
  40672. }
  40673. }
  40674. }
  40675. #endif
  40676. assert( next==0 || rc==SQLITE_DONE );
  40677. if( rc==SQLITE_OK ){
  40678. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  40679. assert( rc==SQLITE_OK || pPage==0 );
  40680. if( rc==SQLITE_OK ){
  40681. next = get4byte(pPage->aData);
  40682. }
  40683. }
  40684. *pPgnoNext = next;
  40685. if( ppPage ){
  40686. *ppPage = pPage;
  40687. }else{
  40688. releasePage(pPage);
  40689. }
  40690. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  40691. }
  40692. /*
  40693. ** Copy data from a buffer to a page, or from a page to a buffer.
  40694. **
  40695. ** pPayload is a pointer to data stored on database page pDbPage.
  40696. ** If argument eOp is false, then nByte bytes of data are copied
  40697. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  40698. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  40699. ** of data are copied from the buffer pBuf to pPayload.
  40700. **
  40701. ** SQLITE_OK is returned on success, otherwise an error code.
  40702. */
  40703. static int copyPayload(
  40704. void *pPayload, /* Pointer to page data */
  40705. void *pBuf, /* Pointer to buffer */
  40706. int nByte, /* Number of bytes to copy */
  40707. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  40708. DbPage *pDbPage /* Page containing pPayload */
  40709. ){
  40710. if( eOp ){
  40711. /* Copy data from buffer to page (a write operation) */
  40712. int rc = sqlite3PagerWrite(pDbPage);
  40713. if( rc!=SQLITE_OK ){
  40714. return rc;
  40715. }
  40716. memcpy(pPayload, pBuf, nByte);
  40717. }else{
  40718. /* Copy data from page to buffer (a read operation) */
  40719. memcpy(pBuf, pPayload, nByte);
  40720. }
  40721. return SQLITE_OK;
  40722. }
  40723. /*
  40724. ** This function is used to read or overwrite payload information
  40725. ** for the entry that the pCur cursor is pointing to. If the eOp
  40726. ** parameter is 0, this is a read operation (data copied into
  40727. ** buffer pBuf). If it is non-zero, a write (data copied from
  40728. ** buffer pBuf).
  40729. **
  40730. ** A total of "amt" bytes are read or written beginning at "offset".
  40731. ** Data is read to or from the buffer pBuf.
  40732. **
  40733. ** The content being read or written might appear on the main page
  40734. ** or be scattered out on multiple overflow pages.
  40735. **
  40736. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  40737. ** cursor entry uses one or more overflow pages, this function
  40738. ** allocates space for and lazily popluates the overflow page-list
  40739. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  40740. ** cache to make seeking to the supplied offset more efficient.
  40741. **
  40742. ** Once an overflow page-list cache has been allocated, it may be
  40743. ** invalidated if some other cursor writes to the same table, or if
  40744. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  40745. ** mode, the following events may invalidate an overflow page-list cache.
  40746. **
  40747. ** * An incremental vacuum,
  40748. ** * A commit in auto_vacuum="full" mode,
  40749. ** * Creating a table (may require moving an overflow page).
  40750. */
  40751. static int accessPayload(
  40752. BtCursor *pCur, /* Cursor pointing to entry to read from */
  40753. u32 offset, /* Begin reading this far into payload */
  40754. u32 amt, /* Read this many bytes */
  40755. unsigned char *pBuf, /* Write the bytes into this buffer */
  40756. int eOp /* zero to read. non-zero to write. */
  40757. ){
  40758. unsigned char *aPayload;
  40759. int rc = SQLITE_OK;
  40760. u32 nKey;
  40761. int iIdx = 0;
  40762. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  40763. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  40764. assert( pPage );
  40765. assert( pCur->eState==CURSOR_VALID );
  40766. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  40767. assert( cursorHoldsMutex(pCur) );
  40768. getCellInfo(pCur);
  40769. aPayload = pCur->info.pCell + pCur->info.nHeader;
  40770. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  40771. if( NEVER(offset+amt > nKey+pCur->info.nData)
  40772. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  40773. ){
  40774. /* Trying to read or write past the end of the data is an error */
  40775. return SQLITE_CORRUPT_BKPT;
  40776. }
  40777. /* Check if data must be read/written to/from the btree page itself. */
  40778. if( offset<pCur->info.nLocal ){
  40779. int a = amt;
  40780. if( a+offset>pCur->info.nLocal ){
  40781. a = pCur->info.nLocal - offset;
  40782. }
  40783. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  40784. offset = 0;
  40785. pBuf += a;
  40786. amt -= a;
  40787. }else{
  40788. offset -= pCur->info.nLocal;
  40789. }
  40790. if( rc==SQLITE_OK && amt>0 ){
  40791. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  40792. Pgno nextPage;
  40793. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  40794. #ifndef SQLITE_OMIT_INCRBLOB
  40795. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  40796. ** has not been allocated, allocate it now. The array is sized at
  40797. ** one entry for each overflow page in the overflow chain. The
  40798. ** page number of the first overflow page is stored in aOverflow[0],
  40799. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  40800. ** (the cache is lazily populated).
  40801. */
  40802. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  40803. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  40804. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  40805. /* nOvfl is always positive. If it were zero, fetchPayload would have
  40806. ** been used instead of this routine. */
  40807. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  40808. rc = SQLITE_NOMEM;
  40809. }
  40810. }
  40811. /* If the overflow page-list cache has been allocated and the
  40812. ** entry for the first required overflow page is valid, skip
  40813. ** directly to it.
  40814. */
  40815. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  40816. iIdx = (offset/ovflSize);
  40817. nextPage = pCur->aOverflow[iIdx];
  40818. offset = (offset%ovflSize);
  40819. }
  40820. #endif
  40821. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  40822. #ifndef SQLITE_OMIT_INCRBLOB
  40823. /* If required, populate the overflow page-list cache. */
  40824. if( pCur->aOverflow ){
  40825. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  40826. pCur->aOverflow[iIdx] = nextPage;
  40827. }
  40828. #endif
  40829. if( offset>=ovflSize ){
  40830. /* The only reason to read this page is to obtain the page
  40831. ** number for the next page in the overflow chain. The page
  40832. ** data is not required. So first try to lookup the overflow
  40833. ** page-list cache, if any, then fall back to the getOverflowPage()
  40834. ** function.
  40835. */
  40836. #ifndef SQLITE_OMIT_INCRBLOB
  40837. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  40838. nextPage = pCur->aOverflow[iIdx+1];
  40839. } else
  40840. #endif
  40841. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  40842. offset -= ovflSize;
  40843. }else{
  40844. /* Need to read this page properly. It contains some of the
  40845. ** range of data that is being read (eOp==0) or written (eOp!=0).
  40846. */
  40847. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  40848. sqlite3_file *fd;
  40849. #endif
  40850. int a = amt;
  40851. if( a + offset > ovflSize ){
  40852. a = ovflSize - offset;
  40853. }
  40854. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  40855. /* If all the following are true:
  40856. **
  40857. ** 1) this is a read operation, and
  40858. ** 2) data is required from the start of this overflow page, and
  40859. ** 3) the database is file-backed, and
  40860. ** 4) there is no open write-transaction, and
  40861. ** 5) the database is not a WAL database,
  40862. **
  40863. ** then data can be read directly from the database file into the
  40864. ** output buffer, bypassing the page-cache altogether. This speeds
  40865. ** up loading large records that span many overflow pages.
  40866. */
  40867. if( eOp==0 /* (1) */
  40868. && offset==0 /* (2) */
  40869. && pBt->inTransaction==TRANS_READ /* (4) */
  40870. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  40871. && pBt->pPage1->aData[19]==0x01 /* (5) */
  40872. ){
  40873. u8 aSave[4];
  40874. u8 *aWrite = &pBuf[-4];
  40875. memcpy(aSave, aWrite, 4);
  40876. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  40877. nextPage = get4byte(aWrite);
  40878. memcpy(aWrite, aSave, 4);
  40879. }else
  40880. #endif
  40881. {
  40882. DbPage *pDbPage;
  40883. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  40884. (eOp==0 ? PAGER_GET_READONLY : 0)
  40885. );
  40886. if( rc==SQLITE_OK ){
  40887. aPayload = sqlite3PagerGetData(pDbPage);
  40888. nextPage = get4byte(aPayload);
  40889. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  40890. sqlite3PagerUnref(pDbPage);
  40891. offset = 0;
  40892. }
  40893. }
  40894. amt -= a;
  40895. pBuf += a;
  40896. }
  40897. }
  40898. }
  40899. if( rc==SQLITE_OK && amt>0 ){
  40900. return SQLITE_CORRUPT_BKPT;
  40901. }
  40902. return rc;
  40903. }
  40904. /*
  40905. ** Read part of the key associated with cursor pCur. Exactly
  40906. ** "amt" bytes will be transfered into pBuf[]. The transfer
  40907. ** begins at "offset".
  40908. **
  40909. ** The caller must ensure that pCur is pointing to a valid row
  40910. ** in the table.
  40911. **
  40912. ** Return SQLITE_OK on success or an error code if anything goes
  40913. ** wrong. An error is returned if "offset+amt" is larger than
  40914. ** the available payload.
  40915. */
  40916. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  40917. assert( cursorHoldsMutex(pCur) );
  40918. assert( pCur->eState==CURSOR_VALID );
  40919. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  40920. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  40921. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  40922. }
  40923. /*
  40924. ** Read part of the data associated with cursor pCur. Exactly
  40925. ** "amt" bytes will be transfered into pBuf[]. The transfer
  40926. ** begins at "offset".
  40927. **
  40928. ** Return SQLITE_OK on success or an error code if anything goes
  40929. ** wrong. An error is returned if "offset+amt" is larger than
  40930. ** the available payload.
  40931. */
  40932. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  40933. int rc;
  40934. #ifndef SQLITE_OMIT_INCRBLOB
  40935. if ( pCur->eState==CURSOR_INVALID ){
  40936. return SQLITE_ABORT;
  40937. }
  40938. #endif
  40939. assert( cursorHoldsMutex(pCur) );
  40940. rc = restoreCursorPosition(pCur);
  40941. if( rc==SQLITE_OK ){
  40942. assert( pCur->eState==CURSOR_VALID );
  40943. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  40944. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  40945. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  40946. }
  40947. return rc;
  40948. }
  40949. /*
  40950. ** Return a pointer to payload information from the entry that the
  40951. ** pCur cursor is pointing to. The pointer is to the beginning of
  40952. ** the key if skipKey==0 and it points to the beginning of data if
  40953. ** skipKey==1. The number of bytes of available key/data is written
  40954. ** into *pAmt. If *pAmt==0, then the value returned will not be
  40955. ** a valid pointer.
  40956. **
  40957. ** This routine is an optimization. It is common for the entire key
  40958. ** and data to fit on the local page and for there to be no overflow
  40959. ** pages. When that is so, this routine can be used to access the
  40960. ** key and data without making a copy. If the key and/or data spills
  40961. ** onto overflow pages, then accessPayload() must be used to reassemble
  40962. ** the key/data and copy it into a preallocated buffer.
  40963. **
  40964. ** The pointer returned by this routine looks directly into the cached
  40965. ** page of the database. The data might change or move the next time
  40966. ** any btree routine is called.
  40967. */
  40968. static const unsigned char *fetchPayload(
  40969. BtCursor *pCur, /* Cursor pointing to entry to read from */
  40970. int *pAmt, /* Write the number of available bytes here */
  40971. int skipKey /* read beginning at data if this is true */
  40972. ){
  40973. unsigned char *aPayload;
  40974. MemPage *pPage;
  40975. u32 nKey;
  40976. u32 nLocal;
  40977. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  40978. assert( pCur->eState==CURSOR_VALID );
  40979. assert( cursorHoldsMutex(pCur) );
  40980. pPage = pCur->apPage[pCur->iPage];
  40981. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  40982. if( NEVER(pCur->info.nSize==0) ){
  40983. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  40984. &pCur->info);
  40985. }
  40986. aPayload = pCur->info.pCell;
  40987. aPayload += pCur->info.nHeader;
  40988. if( pPage->intKey ){
  40989. nKey = 0;
  40990. }else{
  40991. nKey = (int)pCur->info.nKey;
  40992. }
  40993. if( skipKey ){
  40994. aPayload += nKey;
  40995. nLocal = pCur->info.nLocal - nKey;
  40996. }else{
  40997. nLocal = pCur->info.nLocal;
  40998. assert( nLocal<=nKey );
  40999. }
  41000. *pAmt = nLocal;
  41001. return aPayload;
  41002. }
  41003. /*
  41004. ** For the entry that cursor pCur is point to, return as
  41005. ** many bytes of the key or data as are available on the local
  41006. ** b-tree page. Write the number of available bytes into *pAmt.
  41007. **
  41008. ** The pointer returned is ephemeral. The key/data may move
  41009. ** or be destroyed on the next call to any Btree routine,
  41010. ** including calls from other threads against the same cache.
  41011. ** Hence, a mutex on the BtShared should be held prior to calling
  41012. ** this routine.
  41013. **
  41014. ** These routines is used to get quick access to key and data
  41015. ** in the common case where no overflow pages are used.
  41016. */
  41017. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  41018. const void *p = 0;
  41019. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41020. assert( cursorHoldsMutex(pCur) );
  41021. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  41022. p = (const void*)fetchPayload(pCur, pAmt, 0);
  41023. }
  41024. return p;
  41025. }
  41026. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  41027. const void *p = 0;
  41028. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41029. assert( cursorHoldsMutex(pCur) );
  41030. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  41031. p = (const void*)fetchPayload(pCur, pAmt, 1);
  41032. }
  41033. return p;
  41034. }
  41035. /*
  41036. ** Move the cursor down to a new child page. The newPgno argument is the
  41037. ** page number of the child page to move to.
  41038. **
  41039. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  41040. ** the new child page does not match the flags field of the parent (i.e.
  41041. ** if an intkey page appears to be the parent of a non-intkey page, or
  41042. ** vice-versa).
  41043. */
  41044. static int moveToChild(BtCursor *pCur, u32 newPgno){
  41045. int rc;
  41046. int i = pCur->iPage;
  41047. MemPage *pNewPage;
  41048. BtShared *pBt = pCur->pBt;
  41049. assert( cursorHoldsMutex(pCur) );
  41050. assert( pCur->eState==CURSOR_VALID );
  41051. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  41052. assert( pCur->iPage>=0 );
  41053. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  41054. return SQLITE_CORRUPT_BKPT;
  41055. }
  41056. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  41057. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  41058. if( rc ) return rc;
  41059. pCur->apPage[i+1] = pNewPage;
  41060. pCur->aiIdx[i+1] = 0;
  41061. pCur->iPage++;
  41062. pCur->info.nSize = 0;
  41063. pCur->validNKey = 0;
  41064. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  41065. return SQLITE_CORRUPT_BKPT;
  41066. }
  41067. return SQLITE_OK;
  41068. }
  41069. #if 0
  41070. /*
  41071. ** Page pParent is an internal (non-leaf) tree page. This function
  41072. ** asserts that page number iChild is the left-child if the iIdx'th
  41073. ** cell in page pParent. Or, if iIdx is equal to the total number of
  41074. ** cells in pParent, that page number iChild is the right-child of
  41075. ** the page.
  41076. */
  41077. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  41078. assert( iIdx<=pParent->nCell );
  41079. if( iIdx==pParent->nCell ){
  41080. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  41081. }else{
  41082. assert( get4byte(findCell(pParent, iIdx))==iChild );
  41083. }
  41084. }
  41085. #else
  41086. # define assertParentIndex(x,y,z)
  41087. #endif
  41088. /*
  41089. ** Move the cursor up to the parent page.
  41090. **
  41091. ** pCur->idx is set to the cell index that contains the pointer
  41092. ** to the page we are coming from. If we are coming from the
  41093. ** right-most child page then pCur->idx is set to one more than
  41094. ** the largest cell index.
  41095. */
  41096. static void moveToParent(BtCursor *pCur){
  41097. assert( cursorHoldsMutex(pCur) );
  41098. assert( pCur->eState==CURSOR_VALID );
  41099. assert( pCur->iPage>0 );
  41100. assert( pCur->apPage[pCur->iPage] );
  41101. /* UPDATE: It is actually possible for the condition tested by the assert
  41102. ** below to be untrue if the database file is corrupt. This can occur if
  41103. ** one cursor has modified page pParent while a reference to it is held
  41104. ** by a second cursor. Which can only happen if a single page is linked
  41105. ** into more than one b-tree structure in a corrupt database. */
  41106. #if 0
  41107. assertParentIndex(
  41108. pCur->apPage[pCur->iPage-1],
  41109. pCur->aiIdx[pCur->iPage-1],
  41110. pCur->apPage[pCur->iPage]->pgno
  41111. );
  41112. #endif
  41113. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  41114. releasePage(pCur->apPage[pCur->iPage]);
  41115. pCur->iPage--;
  41116. pCur->info.nSize = 0;
  41117. pCur->validNKey = 0;
  41118. }
  41119. /*
  41120. ** Move the cursor to point to the root page of its b-tree structure.
  41121. **
  41122. ** If the table has a virtual root page, then the cursor is moved to point
  41123. ** to the virtual root page instead of the actual root page. A table has a
  41124. ** virtual root page when the actual root page contains no cells and a
  41125. ** single child page. This can only happen with the table rooted at page 1.
  41126. **
  41127. ** If the b-tree structure is empty, the cursor state is set to
  41128. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  41129. ** cell located on the root (or virtual root) page and the cursor state
  41130. ** is set to CURSOR_VALID.
  41131. **
  41132. ** If this function returns successfully, it may be assumed that the
  41133. ** page-header flags indicate that the [virtual] root-page is the expected
  41134. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  41135. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  41136. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  41137. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  41138. ** b-tree).
  41139. */
  41140. static int moveToRoot(BtCursor *pCur){
  41141. MemPage *pRoot;
  41142. int rc = SQLITE_OK;
  41143. Btree *p = pCur->pBtree;
  41144. BtShared *pBt = p->pBt;
  41145. assert( cursorHoldsMutex(pCur) );
  41146. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  41147. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  41148. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  41149. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  41150. if( pCur->eState==CURSOR_FAULT ){
  41151. assert( pCur->skipNext!=SQLITE_OK );
  41152. return pCur->skipNext;
  41153. }
  41154. sqlite3BtreeClearCursor(pCur);
  41155. }
  41156. if( pCur->iPage>=0 ){
  41157. int i;
  41158. for(i=1; i<=pCur->iPage; i++){
  41159. releasePage(pCur->apPage[i]);
  41160. }
  41161. pCur->iPage = 0;
  41162. }else if( pCur->pgnoRoot==0 ){
  41163. pCur->eState = CURSOR_INVALID;
  41164. return SQLITE_OK;
  41165. }else{
  41166. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
  41167. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  41168. if( rc!=SQLITE_OK ){
  41169. pCur->eState = CURSOR_INVALID;
  41170. return rc;
  41171. }
  41172. pCur->iPage = 0;
  41173. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  41174. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  41175. ** NULL, the caller expects a table b-tree. If this is not the case,
  41176. ** return an SQLITE_CORRUPT error. */
  41177. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  41178. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  41179. return SQLITE_CORRUPT_BKPT;
  41180. }
  41181. }
  41182. /* Assert that the root page is of the correct type. This must be the
  41183. ** case as the call to this function that loaded the root-page (either
  41184. ** this call or a previous invocation) would have detected corruption
  41185. ** if the assumption were not true, and it is not possible for the flags
  41186. ** byte to have been modified while this cursor is holding a reference
  41187. ** to the page. */
  41188. pRoot = pCur->apPage[0];
  41189. assert( pRoot->pgno==pCur->pgnoRoot );
  41190. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  41191. pCur->aiIdx[0] = 0;
  41192. pCur->info.nSize = 0;
  41193. pCur->atLast = 0;
  41194. pCur->validNKey = 0;
  41195. if( pRoot->nCell==0 && !pRoot->leaf ){
  41196. Pgno subpage;
  41197. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  41198. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  41199. pCur->eState = CURSOR_VALID;
  41200. rc = moveToChild(pCur, subpage);
  41201. }else{
  41202. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  41203. }
  41204. return rc;
  41205. }
  41206. /*
  41207. ** Move the cursor down to the left-most leaf entry beneath the
  41208. ** entry to which it is currently pointing.
  41209. **
  41210. ** The left-most leaf is the one with the smallest key - the first
  41211. ** in ascending order.
  41212. */
  41213. static int moveToLeftmost(BtCursor *pCur){
  41214. Pgno pgno;
  41215. int rc = SQLITE_OK;
  41216. MemPage *pPage;
  41217. assert( cursorHoldsMutex(pCur) );
  41218. assert( pCur->eState==CURSOR_VALID );
  41219. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  41220. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  41221. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  41222. rc = moveToChild(pCur, pgno);
  41223. }
  41224. return rc;
  41225. }
  41226. /*
  41227. ** Move the cursor down to the right-most leaf entry beneath the
  41228. ** page to which it is currently pointing. Notice the difference
  41229. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  41230. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  41231. ** finds the right-most entry beneath the *page*.
  41232. **
  41233. ** The right-most entry is the one with the largest key - the last
  41234. ** key in ascending order.
  41235. */
  41236. static int moveToRightmost(BtCursor *pCur){
  41237. Pgno pgno;
  41238. int rc = SQLITE_OK;
  41239. MemPage *pPage = 0;
  41240. assert( cursorHoldsMutex(pCur) );
  41241. assert( pCur->eState==CURSOR_VALID );
  41242. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  41243. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  41244. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  41245. rc = moveToChild(pCur, pgno);
  41246. }
  41247. if( rc==SQLITE_OK ){
  41248. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  41249. pCur->info.nSize = 0;
  41250. pCur->validNKey = 0;
  41251. }
  41252. return rc;
  41253. }
  41254. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  41255. ** on success. Set *pRes to 0 if the cursor actually points to something
  41256. ** or set *pRes to 1 if the table is empty.
  41257. */
  41258. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  41259. int rc;
  41260. assert( cursorHoldsMutex(pCur) );
  41261. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41262. rc = moveToRoot(pCur);
  41263. if( rc==SQLITE_OK ){
  41264. if( pCur->eState==CURSOR_INVALID ){
  41265. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41266. *pRes = 1;
  41267. }else{
  41268. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  41269. *pRes = 0;
  41270. rc = moveToLeftmost(pCur);
  41271. }
  41272. }
  41273. return rc;
  41274. }
  41275. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  41276. ** on success. Set *pRes to 0 if the cursor actually points to something
  41277. ** or set *pRes to 1 if the table is empty.
  41278. */
  41279. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  41280. int rc;
  41281. assert( cursorHoldsMutex(pCur) );
  41282. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41283. /* If the cursor already points to the last entry, this is a no-op. */
  41284. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  41285. #ifdef SQLITE_DEBUG
  41286. /* This block serves to assert() that the cursor really does point
  41287. ** to the last entry in the b-tree. */
  41288. int ii;
  41289. for(ii=0; ii<pCur->iPage; ii++){
  41290. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  41291. }
  41292. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  41293. assert( pCur->apPage[pCur->iPage]->leaf );
  41294. #endif
  41295. return SQLITE_OK;
  41296. }
  41297. rc = moveToRoot(pCur);
  41298. if( rc==SQLITE_OK ){
  41299. if( CURSOR_INVALID==pCur->eState ){
  41300. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41301. *pRes = 1;
  41302. }else{
  41303. assert( pCur->eState==CURSOR_VALID );
  41304. *pRes = 0;
  41305. rc = moveToRightmost(pCur);
  41306. pCur->atLast = rc==SQLITE_OK ?1:0;
  41307. }
  41308. }
  41309. return rc;
  41310. }
  41311. /* Move the cursor so that it points to an entry near the key
  41312. ** specified by pIdxKey or intKey. Return a success code.
  41313. **
  41314. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  41315. ** must be NULL. For index tables, pIdxKey is used and intKey
  41316. ** is ignored.
  41317. **
  41318. ** If an exact match is not found, then the cursor is always
  41319. ** left pointing at a leaf page which would hold the entry if it
  41320. ** were present. The cursor might point to an entry that comes
  41321. ** before or after the key.
  41322. **
  41323. ** An integer is written into *pRes which is the result of
  41324. ** comparing the key with the entry to which the cursor is
  41325. ** pointing. The meaning of the integer written into
  41326. ** *pRes is as follows:
  41327. **
  41328. ** *pRes<0 The cursor is left pointing at an entry that
  41329. ** is smaller than intKey/pIdxKey or if the table is empty
  41330. ** and the cursor is therefore left point to nothing.
  41331. **
  41332. ** *pRes==0 The cursor is left pointing at an entry that
  41333. ** exactly matches intKey/pIdxKey.
  41334. **
  41335. ** *pRes>0 The cursor is left pointing at an entry that
  41336. ** is larger than intKey/pIdxKey.
  41337. **
  41338. */
  41339. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  41340. BtCursor *pCur, /* The cursor to be moved */
  41341. UnpackedRecord *pIdxKey, /* Unpacked index key */
  41342. i64 intKey, /* The table key */
  41343. int biasRight, /* If true, bias the search to the high end */
  41344. int *pRes /* Write search results here */
  41345. ){
  41346. int rc;
  41347. assert( cursorHoldsMutex(pCur) );
  41348. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  41349. assert( pRes );
  41350. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  41351. /* If the cursor is already positioned at the point we are trying
  41352. ** to move to, then just return without doing any work */
  41353. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  41354. && pCur->apPage[0]->intKey
  41355. ){
  41356. if( pCur->info.nKey==intKey ){
  41357. *pRes = 0;
  41358. return SQLITE_OK;
  41359. }
  41360. if( pCur->atLast && pCur->info.nKey<intKey ){
  41361. *pRes = -1;
  41362. return SQLITE_OK;
  41363. }
  41364. }
  41365. rc = moveToRoot(pCur);
  41366. if( rc ){
  41367. return rc;
  41368. }
  41369. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  41370. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  41371. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  41372. if( pCur->eState==CURSOR_INVALID ){
  41373. *pRes = -1;
  41374. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  41375. return SQLITE_OK;
  41376. }
  41377. assert( pCur->apPage[0]->intKey || pIdxKey );
  41378. for(;;){
  41379. int lwr, upr, idx;
  41380. Pgno chldPg;
  41381. MemPage *pPage = pCur->apPage[pCur->iPage];
  41382. int c;
  41383. /* pPage->nCell must be greater than zero. If this is the root-page
  41384. ** the cursor would have been INVALID above and this for(;;) loop
  41385. ** not run. If this is not the root-page, then the moveToChild() routine
  41386. ** would have already detected db corruption. Similarly, pPage must
  41387. ** be the right kind (index or table) of b-tree page. Otherwise
  41388. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  41389. assert( pPage->nCell>0 );
  41390. assert( pPage->intKey==(pIdxKey==0) );
  41391. lwr = 0;
  41392. upr = pPage->nCell-1;
  41393. if( biasRight ){
  41394. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  41395. }else{
  41396. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  41397. }
  41398. for(;;){
  41399. u8 *pCell; /* Pointer to current cell in pPage */
  41400. assert( idx==pCur->aiIdx[pCur->iPage] );
  41401. pCur->info.nSize = 0;
  41402. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  41403. if( pPage->intKey ){
  41404. i64 nCellKey;
  41405. if( pPage->hasData ){
  41406. u32 dummy;
  41407. pCell += getVarint32(pCell, dummy);
  41408. }
  41409. getVarint(pCell, (u64*)&nCellKey);
  41410. if( nCellKey==intKey ){
  41411. c = 0;
  41412. }else if( nCellKey<intKey ){
  41413. c = -1;
  41414. }else{
  41415. assert( nCellKey>intKey );
  41416. c = +1;
  41417. }
  41418. pCur->validNKey = 1;
  41419. pCur->info.nKey = nCellKey;
  41420. }else{
  41421. /* The maximum supported page-size is 65536 bytes. This means that
  41422. ** the maximum number of record bytes stored on an index B-Tree
  41423. ** page is less than 16384 bytes and may be stored as a 2-byte
  41424. ** varint. This information is used to attempt to avoid parsing
  41425. ** the entire cell by checking for the cases where the record is
  41426. ** stored entirely within the b-tree page by inspecting the first
  41427. ** 2 bytes of the cell.
  41428. */
  41429. int nCell = pCell[0];
  41430. if( nCell<=pPage->max1bytePayload
  41431. /* && (pCell+nCell)<pPage->aDataEnd */
  41432. ){
  41433. /* This branch runs if the record-size field of the cell is a
  41434. ** single byte varint and the record fits entirely on the main
  41435. ** b-tree page. */
  41436. testcase( pCell+nCell+1==pPage->aDataEnd );
  41437. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  41438. }else if( !(pCell[1] & 0x80)
  41439. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  41440. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  41441. ){
  41442. /* The record-size field is a 2 byte varint and the record
  41443. ** fits entirely on the main b-tree page. */
  41444. testcase( pCell+nCell+2==pPage->aDataEnd );
  41445. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  41446. }else{
  41447. /* The record flows over onto one or more overflow pages. In
  41448. ** this case the whole cell needs to be parsed, a buffer allocated
  41449. ** and accessPayload() used to retrieve the record into the
  41450. ** buffer before VdbeRecordCompare() can be called. */
  41451. void *pCellKey;
  41452. u8 * const pCellBody = pCell - pPage->childPtrSize;
  41453. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  41454. nCell = (int)pCur->info.nKey;
  41455. pCellKey = sqlite3Malloc( nCell );
  41456. if( pCellKey==0 ){
  41457. rc = SQLITE_NOMEM;
  41458. goto moveto_finish;
  41459. }
  41460. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  41461. if( rc ){
  41462. sqlite3_free(pCellKey);
  41463. goto moveto_finish;
  41464. }
  41465. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  41466. sqlite3_free(pCellKey);
  41467. }
  41468. }
  41469. if( c==0 ){
  41470. if( pPage->intKey && !pPage->leaf ){
  41471. lwr = idx;
  41472. break;
  41473. }else{
  41474. *pRes = 0;
  41475. rc = SQLITE_OK;
  41476. goto moveto_finish;
  41477. }
  41478. }
  41479. if( c<0 ){
  41480. lwr = idx+1;
  41481. }else{
  41482. upr = idx-1;
  41483. }
  41484. if( lwr>upr ){
  41485. break;
  41486. }
  41487. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  41488. }
  41489. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  41490. assert( pPage->isInit );
  41491. if( pPage->leaf ){
  41492. chldPg = 0;
  41493. }else if( lwr>=pPage->nCell ){
  41494. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  41495. }else{
  41496. chldPg = get4byte(findCell(pPage, lwr));
  41497. }
  41498. if( chldPg==0 ){
  41499. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  41500. *pRes = c;
  41501. rc = SQLITE_OK;
  41502. goto moveto_finish;
  41503. }
  41504. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  41505. pCur->info.nSize = 0;
  41506. pCur->validNKey = 0;
  41507. rc = moveToChild(pCur, chldPg);
  41508. if( rc ) goto moveto_finish;
  41509. }
  41510. moveto_finish:
  41511. return rc;
  41512. }
  41513. /*
  41514. ** Return TRUE if the cursor is not pointing at an entry of the table.
  41515. **
  41516. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  41517. ** past the last entry in the table or sqlite3BtreePrev() moves past
  41518. ** the first entry. TRUE is also returned if the table is empty.
  41519. */
  41520. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  41521. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  41522. ** have been deleted? This API will need to change to return an error code
  41523. ** as well as the boolean result value.
  41524. */
  41525. return (CURSOR_VALID!=pCur->eState);
  41526. }
  41527. /*
  41528. ** Advance the cursor to the next entry in the database. If
  41529. ** successful then set *pRes=0. If the cursor
  41530. ** was already pointing to the last entry in the database before
  41531. ** this routine was called, then set *pRes=1.
  41532. */
  41533. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  41534. int rc;
  41535. int idx;
  41536. MemPage *pPage;
  41537. assert( cursorHoldsMutex(pCur) );
  41538. assert( pRes!=0 );
  41539. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  41540. if( pCur->eState!=CURSOR_VALID ){
  41541. rc = restoreCursorPosition(pCur);
  41542. if( rc!=SQLITE_OK ){
  41543. *pRes = 0;
  41544. return rc;
  41545. }
  41546. if( CURSOR_INVALID==pCur->eState ){
  41547. *pRes = 1;
  41548. return SQLITE_OK;
  41549. }
  41550. if( pCur->skipNext ){
  41551. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  41552. pCur->eState = CURSOR_VALID;
  41553. if( pCur->skipNext>0 ){
  41554. pCur->skipNext = 0;
  41555. *pRes = 0;
  41556. return SQLITE_OK;
  41557. }
  41558. pCur->skipNext = 0;
  41559. }
  41560. }
  41561. pPage = pCur->apPage[pCur->iPage];
  41562. idx = ++pCur->aiIdx[pCur->iPage];
  41563. assert( pPage->isInit );
  41564. /* If the database file is corrupt, it is possible for the value of idx
  41565. ** to be invalid here. This can only occur if a second cursor modifies
  41566. ** the page while cursor pCur is holding a reference to it. Which can
  41567. ** only happen if the database is corrupt in such a way as to link the
  41568. ** page into more than one b-tree structure. */
  41569. testcase( idx>pPage->nCell );
  41570. pCur->info.nSize = 0;
  41571. pCur->validNKey = 0;
  41572. if( idx>=pPage->nCell ){
  41573. if( !pPage->leaf ){
  41574. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  41575. if( rc ){
  41576. *pRes = 0;
  41577. return rc;
  41578. }
  41579. rc = moveToLeftmost(pCur);
  41580. *pRes = 0;
  41581. return rc;
  41582. }
  41583. do{
  41584. if( pCur->iPage==0 ){
  41585. *pRes = 1;
  41586. pCur->eState = CURSOR_INVALID;
  41587. return SQLITE_OK;
  41588. }
  41589. moveToParent(pCur);
  41590. pPage = pCur->apPage[pCur->iPage];
  41591. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  41592. *pRes = 0;
  41593. if( pPage->intKey ){
  41594. rc = sqlite3BtreeNext(pCur, pRes);
  41595. }else{
  41596. rc = SQLITE_OK;
  41597. }
  41598. return rc;
  41599. }
  41600. *pRes = 0;
  41601. if( pPage->leaf ){
  41602. return SQLITE_OK;
  41603. }
  41604. rc = moveToLeftmost(pCur);
  41605. return rc;
  41606. }
  41607. /*
  41608. ** Step the cursor to the back to the previous entry in the database. If
  41609. ** successful then set *pRes=0. If the cursor
  41610. ** was already pointing to the first entry in the database before
  41611. ** this routine was called, then set *pRes=1.
  41612. */
  41613. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  41614. int rc;
  41615. MemPage *pPage;
  41616. assert( cursorHoldsMutex(pCur) );
  41617. assert( pRes!=0 );
  41618. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  41619. pCur->atLast = 0;
  41620. if( pCur->eState!=CURSOR_VALID ){
  41621. if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
  41622. rc = btreeRestoreCursorPosition(pCur);
  41623. if( rc!=SQLITE_OK ){
  41624. *pRes = 0;
  41625. return rc;
  41626. }
  41627. }
  41628. if( CURSOR_INVALID==pCur->eState ){
  41629. *pRes = 1;
  41630. return SQLITE_OK;
  41631. }
  41632. if( pCur->skipNext ){
  41633. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  41634. pCur->eState = CURSOR_VALID;
  41635. if( pCur->skipNext<0 ){
  41636. pCur->skipNext = 0;
  41637. *pRes = 0;
  41638. return SQLITE_OK;
  41639. }
  41640. pCur->skipNext = 0;
  41641. }
  41642. }
  41643. pPage = pCur->apPage[pCur->iPage];
  41644. assert( pPage->isInit );
  41645. if( !pPage->leaf ){
  41646. int idx = pCur->aiIdx[pCur->iPage];
  41647. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  41648. if( rc ){
  41649. *pRes = 0;
  41650. return rc;
  41651. }
  41652. rc = moveToRightmost(pCur);
  41653. }else{
  41654. while( pCur->aiIdx[pCur->iPage]==0 ){
  41655. if( pCur->iPage==0 ){
  41656. pCur->eState = CURSOR_INVALID;
  41657. *pRes = 1;
  41658. return SQLITE_OK;
  41659. }
  41660. moveToParent(pCur);
  41661. }
  41662. pCur->info.nSize = 0;
  41663. pCur->validNKey = 0;
  41664. pCur->aiIdx[pCur->iPage]--;
  41665. pPage = pCur->apPage[pCur->iPage];
  41666. if( pPage->intKey && !pPage->leaf ){
  41667. rc = sqlite3BtreePrevious(pCur, pRes);
  41668. }else{
  41669. rc = SQLITE_OK;
  41670. }
  41671. }
  41672. *pRes = 0;
  41673. return rc;
  41674. }
  41675. /*
  41676. ** Allocate a new page from the database file.
  41677. **
  41678. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  41679. ** has already been called on the new page.) The new page has also
  41680. ** been referenced and the calling routine is responsible for calling
  41681. ** sqlite3PagerUnref() on the new page when it is done.
  41682. **
  41683. ** SQLITE_OK is returned on success. Any other return value indicates
  41684. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  41685. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  41686. **
  41687. ** If the "nearby" parameter is not 0, then an effort is made to
  41688. ** locate a page close to the page number "nearby". This can be used in an
  41689. ** attempt to keep related pages close to each other in the database file,
  41690. ** which in turn can make database access faster.
  41691. **
  41692. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  41693. ** anywhere on the free-list, then it is guaranteed to be returned. If
  41694. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  41695. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  41696. ** are no restrictions on which page is returned.
  41697. */
  41698. static int allocateBtreePage(
  41699. BtShared *pBt, /* The btree */
  41700. MemPage **ppPage, /* Store pointer to the allocated page here */
  41701. Pgno *pPgno, /* Store the page number here */
  41702. Pgno nearby, /* Search for a page near this one */
  41703. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  41704. ){
  41705. MemPage *pPage1;
  41706. int rc;
  41707. u32 n; /* Number of pages on the freelist */
  41708. u32 k; /* Number of leaves on the trunk of the freelist */
  41709. MemPage *pTrunk = 0;
  41710. MemPage *pPrevTrunk = 0;
  41711. Pgno mxPage; /* Total size of the database file */
  41712. assert( sqlite3_mutex_held(pBt->mutex) );
  41713. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  41714. pPage1 = pBt->pPage1;
  41715. mxPage = btreePagecount(pBt);
  41716. n = get4byte(&pPage1->aData[36]);
  41717. testcase( n==mxPage-1 );
  41718. if( n>=mxPage ){
  41719. return SQLITE_CORRUPT_BKPT;
  41720. }
  41721. if( n>0 ){
  41722. /* There are pages on the freelist. Reuse one of those pages. */
  41723. Pgno iTrunk;
  41724. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  41725. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  41726. ** shows that the page 'nearby' is somewhere on the free-list, then
  41727. ** the entire-list will be searched for that page.
  41728. */
  41729. #ifndef SQLITE_OMIT_AUTOVACUUM
  41730. if( eMode==BTALLOC_EXACT ){
  41731. if( nearby<=mxPage ){
  41732. u8 eType;
  41733. assert( nearby>0 );
  41734. assert( pBt->autoVacuum );
  41735. rc = ptrmapGet(pBt, nearby, &eType, 0);
  41736. if( rc ) return rc;
  41737. if( eType==PTRMAP_FREEPAGE ){
  41738. searchList = 1;
  41739. }
  41740. }
  41741. }else if( eMode==BTALLOC_LE ){
  41742. searchList = 1;
  41743. }
  41744. #endif
  41745. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  41746. ** first free-list trunk page. iPrevTrunk is initially 1.
  41747. */
  41748. rc = sqlite3PagerWrite(pPage1->pDbPage);
  41749. if( rc ) return rc;
  41750. put4byte(&pPage1->aData[36], n-1);
  41751. /* The code within this loop is run only once if the 'searchList' variable
  41752. ** is not true. Otherwise, it runs once for each trunk-page on the
  41753. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  41754. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  41755. */
  41756. do {
  41757. pPrevTrunk = pTrunk;
  41758. if( pPrevTrunk ){
  41759. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  41760. }else{
  41761. iTrunk = get4byte(&pPage1->aData[32]);
  41762. }
  41763. testcase( iTrunk==mxPage );
  41764. if( iTrunk>mxPage ){
  41765. rc = SQLITE_CORRUPT_BKPT;
  41766. }else{
  41767. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  41768. }
  41769. if( rc ){
  41770. pTrunk = 0;
  41771. goto end_allocate_page;
  41772. }
  41773. assert( pTrunk!=0 );
  41774. assert( pTrunk->aData!=0 );
  41775. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  41776. if( k==0 && !searchList ){
  41777. /* The trunk has no leaves and the list is not being searched.
  41778. ** So extract the trunk page itself and use it as the newly
  41779. ** allocated page */
  41780. assert( pPrevTrunk==0 );
  41781. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41782. if( rc ){
  41783. goto end_allocate_page;
  41784. }
  41785. *pPgno = iTrunk;
  41786. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  41787. *ppPage = pTrunk;
  41788. pTrunk = 0;
  41789. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  41790. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  41791. /* Value of k is out of range. Database corruption */
  41792. rc = SQLITE_CORRUPT_BKPT;
  41793. goto end_allocate_page;
  41794. #ifndef SQLITE_OMIT_AUTOVACUUM
  41795. }else if( searchList
  41796. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  41797. ){
  41798. /* The list is being searched and this trunk page is the page
  41799. ** to allocate, regardless of whether it has leaves.
  41800. */
  41801. *pPgno = iTrunk;
  41802. *ppPage = pTrunk;
  41803. searchList = 0;
  41804. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41805. if( rc ){
  41806. goto end_allocate_page;
  41807. }
  41808. if( k==0 ){
  41809. if( !pPrevTrunk ){
  41810. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  41811. }else{
  41812. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  41813. if( rc!=SQLITE_OK ){
  41814. goto end_allocate_page;
  41815. }
  41816. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  41817. }
  41818. }else{
  41819. /* The trunk page is required by the caller but it contains
  41820. ** pointers to free-list leaves. The first leaf becomes a trunk
  41821. ** page in this case.
  41822. */
  41823. MemPage *pNewTrunk;
  41824. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  41825. if( iNewTrunk>mxPage ){
  41826. rc = SQLITE_CORRUPT_BKPT;
  41827. goto end_allocate_page;
  41828. }
  41829. testcase( iNewTrunk==mxPage );
  41830. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  41831. if( rc!=SQLITE_OK ){
  41832. goto end_allocate_page;
  41833. }
  41834. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  41835. if( rc!=SQLITE_OK ){
  41836. releasePage(pNewTrunk);
  41837. goto end_allocate_page;
  41838. }
  41839. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  41840. put4byte(&pNewTrunk->aData[4], k-1);
  41841. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  41842. releasePage(pNewTrunk);
  41843. if( !pPrevTrunk ){
  41844. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  41845. put4byte(&pPage1->aData[32], iNewTrunk);
  41846. }else{
  41847. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  41848. if( rc ){
  41849. goto end_allocate_page;
  41850. }
  41851. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  41852. }
  41853. }
  41854. pTrunk = 0;
  41855. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  41856. #endif
  41857. }else if( k>0 ){
  41858. /* Extract a leaf from the trunk */
  41859. u32 closest;
  41860. Pgno iPage;
  41861. unsigned char *aData = pTrunk->aData;
  41862. if( nearby>0 ){
  41863. u32 i;
  41864. closest = 0;
  41865. if( eMode==BTALLOC_LE ){
  41866. for(i=0; i<k; i++){
  41867. iPage = get4byte(&aData[8+i*4]);
  41868. if( iPage<=nearby ){
  41869. closest = i;
  41870. break;
  41871. }
  41872. }
  41873. }else{
  41874. int dist;
  41875. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  41876. for(i=1; i<k; i++){
  41877. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  41878. if( d2<dist ){
  41879. closest = i;
  41880. dist = d2;
  41881. }
  41882. }
  41883. }
  41884. }else{
  41885. closest = 0;
  41886. }
  41887. iPage = get4byte(&aData[8+closest*4]);
  41888. testcase( iPage==mxPage );
  41889. if( iPage>mxPage ){
  41890. rc = SQLITE_CORRUPT_BKPT;
  41891. goto end_allocate_page;
  41892. }
  41893. testcase( iPage==mxPage );
  41894. if( !searchList
  41895. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  41896. ){
  41897. int noContent;
  41898. *pPgno = iPage;
  41899. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  41900. ": %d more free pages\n",
  41901. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  41902. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  41903. if( rc ) goto end_allocate_page;
  41904. if( closest<k-1 ){
  41905. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  41906. }
  41907. put4byte(&aData[4], k-1);
  41908. noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
  41909. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  41910. if( rc==SQLITE_OK ){
  41911. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  41912. if( rc!=SQLITE_OK ){
  41913. releasePage(*ppPage);
  41914. }
  41915. }
  41916. searchList = 0;
  41917. }
  41918. }
  41919. releasePage(pPrevTrunk);
  41920. pPrevTrunk = 0;
  41921. }while( searchList );
  41922. }else{
  41923. /* There are no pages on the freelist, so append a new page to the
  41924. ** database image.
  41925. **
  41926. ** Normally, new pages allocated by this block can be requested from the
  41927. ** pager layer with the 'no-content' flag set. This prevents the pager
  41928. ** from trying to read the pages content from disk. However, if the
  41929. ** current transaction has already run one or more incremental-vacuum
  41930. ** steps, then the page we are about to allocate may contain content
  41931. ** that is required in the event of a rollback. In this case, do
  41932. ** not set the no-content flag. This causes the pager to load and journal
  41933. ** the current page content before overwriting it.
  41934. **
  41935. ** Note that the pager will not actually attempt to load or journal
  41936. ** content for any page that really does lie past the end of the database
  41937. ** file on disk. So the effects of disabling the no-content optimization
  41938. ** here are confined to those pages that lie between the end of the
  41939. ** database image and the end of the database file.
  41940. */
  41941. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
  41942. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  41943. if( rc ) return rc;
  41944. pBt->nPage++;
  41945. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  41946. #ifndef SQLITE_OMIT_AUTOVACUUM
  41947. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  41948. /* If *pPgno refers to a pointer-map page, allocate two new pages
  41949. ** at the end of the file instead of one. The first allocated page
  41950. ** becomes a new pointer-map page, the second is used by the caller.
  41951. */
  41952. MemPage *pPg = 0;
  41953. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  41954. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  41955. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  41956. if( rc==SQLITE_OK ){
  41957. rc = sqlite3PagerWrite(pPg->pDbPage);
  41958. releasePage(pPg);
  41959. }
  41960. if( rc ) return rc;
  41961. pBt->nPage++;
  41962. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  41963. }
  41964. #endif
  41965. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  41966. *pPgno = pBt->nPage;
  41967. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  41968. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  41969. if( rc ) return rc;
  41970. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  41971. if( rc!=SQLITE_OK ){
  41972. releasePage(*ppPage);
  41973. }
  41974. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  41975. }
  41976. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  41977. end_allocate_page:
  41978. releasePage(pTrunk);
  41979. releasePage(pPrevTrunk);
  41980. if( rc==SQLITE_OK ){
  41981. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  41982. releasePage(*ppPage);
  41983. return SQLITE_CORRUPT_BKPT;
  41984. }
  41985. (*ppPage)->isInit = 0;
  41986. }else{
  41987. *ppPage = 0;
  41988. }
  41989. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  41990. return rc;
  41991. }
  41992. /*
  41993. ** This function is used to add page iPage to the database file free-list.
  41994. ** It is assumed that the page is not already a part of the free-list.
  41995. **
  41996. ** The value passed as the second argument to this function is optional.
  41997. ** If the caller happens to have a pointer to the MemPage object
  41998. ** corresponding to page iPage handy, it may pass it as the second value.
  41999. ** Otherwise, it may pass NULL.
  42000. **
  42001. ** If a pointer to a MemPage object is passed as the second argument,
  42002. ** its reference count is not altered by this function.
  42003. */
  42004. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  42005. MemPage *pTrunk = 0; /* Free-list trunk page */
  42006. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  42007. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  42008. MemPage *pPage; /* Page being freed. May be NULL. */
  42009. int rc; /* Return Code */
  42010. int nFree; /* Initial number of pages on free-list */
  42011. assert( sqlite3_mutex_held(pBt->mutex) );
  42012. assert( iPage>1 );
  42013. assert( !pMemPage || pMemPage->pgno==iPage );
  42014. if( pMemPage ){
  42015. pPage = pMemPage;
  42016. sqlite3PagerRef(pPage->pDbPage);
  42017. }else{
  42018. pPage = btreePageLookup(pBt, iPage);
  42019. }
  42020. /* Increment the free page count on pPage1 */
  42021. rc = sqlite3PagerWrite(pPage1->pDbPage);
  42022. if( rc ) goto freepage_out;
  42023. nFree = get4byte(&pPage1->aData[36]);
  42024. put4byte(&pPage1->aData[36], nFree+1);
  42025. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  42026. /* If the secure_delete option is enabled, then
  42027. ** always fully overwrite deleted information with zeros.
  42028. */
  42029. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  42030. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  42031. ){
  42032. goto freepage_out;
  42033. }
  42034. memset(pPage->aData, 0, pPage->pBt->pageSize);
  42035. }
  42036. /* If the database supports auto-vacuum, write an entry in the pointer-map
  42037. ** to indicate that the page is free.
  42038. */
  42039. if( ISAUTOVACUUM ){
  42040. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  42041. if( rc ) goto freepage_out;
  42042. }
  42043. /* Now manipulate the actual database free-list structure. There are two
  42044. ** possibilities. If the free-list is currently empty, or if the first
  42045. ** trunk page in the free-list is full, then this page will become a
  42046. ** new free-list trunk page. Otherwise, it will become a leaf of the
  42047. ** first trunk page in the current free-list. This block tests if it
  42048. ** is possible to add the page as a new free-list leaf.
  42049. */
  42050. if( nFree!=0 ){
  42051. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  42052. iTrunk = get4byte(&pPage1->aData[32]);
  42053. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  42054. if( rc!=SQLITE_OK ){
  42055. goto freepage_out;
  42056. }
  42057. nLeaf = get4byte(&pTrunk->aData[4]);
  42058. assert( pBt->usableSize>32 );
  42059. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  42060. rc = SQLITE_CORRUPT_BKPT;
  42061. goto freepage_out;
  42062. }
  42063. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  42064. /* In this case there is room on the trunk page to insert the page
  42065. ** being freed as a new leaf.
  42066. **
  42067. ** Note that the trunk page is not really full until it contains
  42068. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  42069. ** coded. But due to a coding error in versions of SQLite prior to
  42070. ** 3.6.0, databases with freelist trunk pages holding more than
  42071. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  42072. ** to maintain backwards compatibility with older versions of SQLite,
  42073. ** we will continue to restrict the number of entries to usableSize/4 - 8
  42074. ** for now. At some point in the future (once everyone has upgraded
  42075. ** to 3.6.0 or later) we should consider fixing the conditional above
  42076. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  42077. */
  42078. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  42079. if( rc==SQLITE_OK ){
  42080. put4byte(&pTrunk->aData[4], nLeaf+1);
  42081. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  42082. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  42083. sqlite3PagerDontWrite(pPage->pDbPage);
  42084. }
  42085. rc = btreeSetHasContent(pBt, iPage);
  42086. }
  42087. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  42088. goto freepage_out;
  42089. }
  42090. }
  42091. /* If control flows to this point, then it was not possible to add the
  42092. ** the page being freed as a leaf page of the first trunk in the free-list.
  42093. ** Possibly because the free-list is empty, or possibly because the
  42094. ** first trunk in the free-list is full. Either way, the page being freed
  42095. ** will become the new first trunk page in the free-list.
  42096. */
  42097. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  42098. goto freepage_out;
  42099. }
  42100. rc = sqlite3PagerWrite(pPage->pDbPage);
  42101. if( rc!=SQLITE_OK ){
  42102. goto freepage_out;
  42103. }
  42104. put4byte(pPage->aData, iTrunk);
  42105. put4byte(&pPage->aData[4], 0);
  42106. put4byte(&pPage1->aData[32], iPage);
  42107. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  42108. freepage_out:
  42109. if( pPage ){
  42110. pPage->isInit = 0;
  42111. }
  42112. releasePage(pPage);
  42113. releasePage(pTrunk);
  42114. return rc;
  42115. }
  42116. static void freePage(MemPage *pPage, int *pRC){
  42117. if( (*pRC)==SQLITE_OK ){
  42118. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  42119. }
  42120. }
  42121. /*
  42122. ** Free any overflow pages associated with the given Cell.
  42123. */
  42124. static int clearCell(MemPage *pPage, unsigned char *pCell){
  42125. BtShared *pBt = pPage->pBt;
  42126. CellInfo info;
  42127. Pgno ovflPgno;
  42128. int rc;
  42129. int nOvfl;
  42130. u32 ovflPageSize;
  42131. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42132. btreeParseCellPtr(pPage, pCell, &info);
  42133. if( info.iOverflow==0 ){
  42134. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  42135. }
  42136. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  42137. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  42138. }
  42139. ovflPgno = get4byte(&pCell[info.iOverflow]);
  42140. assert( pBt->usableSize > 4 );
  42141. ovflPageSize = pBt->usableSize - 4;
  42142. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  42143. assert( ovflPgno==0 || nOvfl>0 );
  42144. while( nOvfl-- ){
  42145. Pgno iNext = 0;
  42146. MemPage *pOvfl = 0;
  42147. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  42148. /* 0 is not a legal page number and page 1 cannot be an
  42149. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  42150. ** file the database must be corrupt. */
  42151. return SQLITE_CORRUPT_BKPT;
  42152. }
  42153. if( nOvfl ){
  42154. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  42155. if( rc ) return rc;
  42156. }
  42157. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  42158. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  42159. ){
  42160. /* There is no reason any cursor should have an outstanding reference
  42161. ** to an overflow page belonging to a cell that is being deleted/updated.
  42162. ** So if there exists more than one reference to this page, then it
  42163. ** must not really be an overflow page and the database must be corrupt.
  42164. ** It is helpful to detect this before calling freePage2(), as
  42165. ** freePage2() may zero the page contents if secure-delete mode is
  42166. ** enabled. If this 'overflow' page happens to be a page that the
  42167. ** caller is iterating through or using in some other way, this
  42168. ** can be problematic.
  42169. */
  42170. rc = SQLITE_CORRUPT_BKPT;
  42171. }else{
  42172. rc = freePage2(pBt, pOvfl, ovflPgno);
  42173. }
  42174. if( pOvfl ){
  42175. sqlite3PagerUnref(pOvfl->pDbPage);
  42176. }
  42177. if( rc ) return rc;
  42178. ovflPgno = iNext;
  42179. }
  42180. return SQLITE_OK;
  42181. }
  42182. /*
  42183. ** Create the byte sequence used to represent a cell on page pPage
  42184. ** and write that byte sequence into pCell[]. Overflow pages are
  42185. ** allocated and filled in as necessary. The calling procedure
  42186. ** is responsible for making sure sufficient space has been allocated
  42187. ** for pCell[].
  42188. **
  42189. ** Note that pCell does not necessary need to point to the pPage->aData
  42190. ** area. pCell might point to some temporary storage. The cell will
  42191. ** be constructed in this temporary area then copied into pPage->aData
  42192. ** later.
  42193. */
  42194. static int fillInCell(
  42195. MemPage *pPage, /* The page that contains the cell */
  42196. unsigned char *pCell, /* Complete text of the cell */
  42197. const void *pKey, i64 nKey, /* The key */
  42198. const void *pData,int nData, /* The data */
  42199. int nZero, /* Extra zero bytes to append to pData */
  42200. int *pnSize /* Write cell size here */
  42201. ){
  42202. int nPayload;
  42203. const u8 *pSrc;
  42204. int nSrc, n, rc;
  42205. int spaceLeft;
  42206. MemPage *pOvfl = 0;
  42207. MemPage *pToRelease = 0;
  42208. unsigned char *pPrior;
  42209. unsigned char *pPayload;
  42210. BtShared *pBt = pPage->pBt;
  42211. Pgno pgnoOvfl = 0;
  42212. int nHeader;
  42213. CellInfo info;
  42214. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42215. /* pPage is not necessarily writeable since pCell might be auxiliary
  42216. ** buffer space that is separate from the pPage buffer area */
  42217. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  42218. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42219. /* Fill in the header. */
  42220. nHeader = 0;
  42221. if( !pPage->leaf ){
  42222. nHeader += 4;
  42223. }
  42224. if( pPage->hasData ){
  42225. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  42226. }else{
  42227. nData = nZero = 0;
  42228. }
  42229. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  42230. btreeParseCellPtr(pPage, pCell, &info);
  42231. assert( info.nHeader==nHeader );
  42232. assert( info.nKey==nKey );
  42233. assert( info.nData==(u32)(nData+nZero) );
  42234. /* Fill in the payload */
  42235. nPayload = nData + nZero;
  42236. if( pPage->intKey ){
  42237. pSrc = pData;
  42238. nSrc = nData;
  42239. nData = 0;
  42240. }else{
  42241. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  42242. return SQLITE_CORRUPT_BKPT;
  42243. }
  42244. nPayload += (int)nKey;
  42245. pSrc = pKey;
  42246. nSrc = (int)nKey;
  42247. }
  42248. *pnSize = info.nSize;
  42249. spaceLeft = info.nLocal;
  42250. pPayload = &pCell[nHeader];
  42251. pPrior = &pCell[info.iOverflow];
  42252. while( nPayload>0 ){
  42253. if( spaceLeft==0 ){
  42254. #ifndef SQLITE_OMIT_AUTOVACUUM
  42255. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  42256. if( pBt->autoVacuum ){
  42257. do{
  42258. pgnoOvfl++;
  42259. } while(
  42260. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  42261. );
  42262. }
  42263. #endif
  42264. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  42265. #ifndef SQLITE_OMIT_AUTOVACUUM
  42266. /* If the database supports auto-vacuum, and the second or subsequent
  42267. ** overflow page is being allocated, add an entry to the pointer-map
  42268. ** for that page now.
  42269. **
  42270. ** If this is the first overflow page, then write a partial entry
  42271. ** to the pointer-map. If we write nothing to this pointer-map slot,
  42272. ** then the optimistic overflow chain processing in clearCell()
  42273. ** may misinterpret the uninitialized values and delete the
  42274. ** wrong pages from the database.
  42275. */
  42276. if( pBt->autoVacuum && rc==SQLITE_OK ){
  42277. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  42278. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  42279. if( rc ){
  42280. releasePage(pOvfl);
  42281. }
  42282. }
  42283. #endif
  42284. if( rc ){
  42285. releasePage(pToRelease);
  42286. return rc;
  42287. }
  42288. /* If pToRelease is not zero than pPrior points into the data area
  42289. ** of pToRelease. Make sure pToRelease is still writeable. */
  42290. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  42291. /* If pPrior is part of the data area of pPage, then make sure pPage
  42292. ** is still writeable */
  42293. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  42294. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42295. put4byte(pPrior, pgnoOvfl);
  42296. releasePage(pToRelease);
  42297. pToRelease = pOvfl;
  42298. pPrior = pOvfl->aData;
  42299. put4byte(pPrior, 0);
  42300. pPayload = &pOvfl->aData[4];
  42301. spaceLeft = pBt->usableSize - 4;
  42302. }
  42303. n = nPayload;
  42304. if( n>spaceLeft ) n = spaceLeft;
  42305. /* If pToRelease is not zero than pPayload points into the data area
  42306. ** of pToRelease. Make sure pToRelease is still writeable. */
  42307. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  42308. /* If pPayload is part of the data area of pPage, then make sure pPage
  42309. ** is still writeable */
  42310. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  42311. || sqlite3PagerIswriteable(pPage->pDbPage) );
  42312. if( nSrc>0 ){
  42313. if( n>nSrc ) n = nSrc;
  42314. assert( pSrc );
  42315. memcpy(pPayload, pSrc, n);
  42316. }else{
  42317. memset(pPayload, 0, n);
  42318. }
  42319. nPayload -= n;
  42320. pPayload += n;
  42321. pSrc += n;
  42322. nSrc -= n;
  42323. spaceLeft -= n;
  42324. if( nSrc==0 ){
  42325. nSrc = nData;
  42326. pSrc = pData;
  42327. }
  42328. }
  42329. releasePage(pToRelease);
  42330. return SQLITE_OK;
  42331. }
  42332. /*
  42333. ** Remove the i-th cell from pPage. This routine effects pPage only.
  42334. ** The cell content is not freed or deallocated. It is assumed that
  42335. ** the cell content has been copied someplace else. This routine just
  42336. ** removes the reference to the cell from pPage.
  42337. **
  42338. ** "sz" must be the number of bytes in the cell.
  42339. */
  42340. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  42341. u32 pc; /* Offset to cell content of cell being deleted */
  42342. u8 *data; /* pPage->aData */
  42343. u8 *ptr; /* Used to move bytes around within data[] */
  42344. u8 *endPtr; /* End of loop */
  42345. int rc; /* The return code */
  42346. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  42347. if( *pRC ) return;
  42348. assert( idx>=0 && idx<pPage->nCell );
  42349. assert( sz==cellSize(pPage, idx) );
  42350. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42351. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42352. data = pPage->aData;
  42353. ptr = &pPage->aCellIdx[2*idx];
  42354. pc = get2byte(ptr);
  42355. hdr = pPage->hdrOffset;
  42356. testcase( pc==get2byte(&data[hdr+5]) );
  42357. testcase( pc+sz==pPage->pBt->usableSize );
  42358. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  42359. *pRC = SQLITE_CORRUPT_BKPT;
  42360. return;
  42361. }
  42362. rc = freeSpace(pPage, pc, sz);
  42363. if( rc ){
  42364. *pRC = rc;
  42365. return;
  42366. }
  42367. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  42368. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  42369. while( ptr<endPtr ){
  42370. *(u16*)ptr = *(u16*)&ptr[2];
  42371. ptr += 2;
  42372. }
  42373. pPage->nCell--;
  42374. put2byte(&data[hdr+3], pPage->nCell);
  42375. pPage->nFree += 2;
  42376. }
  42377. /*
  42378. ** Insert a new cell on pPage at cell index "i". pCell points to the
  42379. ** content of the cell.
  42380. **
  42381. ** If the cell content will fit on the page, then put it there. If it
  42382. ** will not fit, then make a copy of the cell content into pTemp if
  42383. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  42384. ** in pPage->apOvfl[] and make it point to the cell content (either
  42385. ** in pTemp or the original pCell) and also record its index.
  42386. ** Allocating a new entry in pPage->aCell[] implies that
  42387. ** pPage->nOverflow is incremented.
  42388. **
  42389. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  42390. ** cell. The caller will overwrite them after this function returns. If
  42391. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  42392. ** (but pCell+nSkip is always valid).
  42393. */
  42394. static void insertCell(
  42395. MemPage *pPage, /* Page into which we are copying */
  42396. int i, /* New cell becomes the i-th cell of the page */
  42397. u8 *pCell, /* Content of the new cell */
  42398. int sz, /* Bytes of content in pCell */
  42399. u8 *pTemp, /* Temp storage space for pCell, if needed */
  42400. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  42401. int *pRC /* Read and write return code from here */
  42402. ){
  42403. int idx = 0; /* Where to write new cell content in data[] */
  42404. int j; /* Loop counter */
  42405. int end; /* First byte past the last cell pointer in data[] */
  42406. int ins; /* Index in data[] where new cell pointer is inserted */
  42407. int cellOffset; /* Address of first cell pointer in data[] */
  42408. u8 *data; /* The content of the whole page */
  42409. u8 *ptr; /* Used for moving information around in data[] */
  42410. u8 *endPtr; /* End of the loop */
  42411. int nSkip = (iChild ? 4 : 0);
  42412. if( *pRC ) return;
  42413. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  42414. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  42415. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  42416. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  42417. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42418. /* The cell should normally be sized correctly. However, when moving a
  42419. ** malformed cell from a leaf page to an interior page, if the cell size
  42420. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  42421. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  42422. ** the term after the || in the following assert(). */
  42423. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  42424. if( pPage->nOverflow || sz+2>pPage->nFree ){
  42425. if( pTemp ){
  42426. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  42427. pCell = pTemp;
  42428. }
  42429. if( iChild ){
  42430. put4byte(pCell, iChild);
  42431. }
  42432. j = pPage->nOverflow++;
  42433. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  42434. pPage->apOvfl[j] = pCell;
  42435. pPage->aiOvfl[j] = (u16)i;
  42436. }else{
  42437. int rc = sqlite3PagerWrite(pPage->pDbPage);
  42438. if( rc!=SQLITE_OK ){
  42439. *pRC = rc;
  42440. return;
  42441. }
  42442. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42443. data = pPage->aData;
  42444. cellOffset = pPage->cellOffset;
  42445. end = cellOffset + 2*pPage->nCell;
  42446. ins = cellOffset + 2*i;
  42447. rc = allocateSpace(pPage, sz, &idx);
  42448. if( rc ){ *pRC = rc; return; }
  42449. /* The allocateSpace() routine guarantees the following two properties
  42450. ** if it returns success */
  42451. assert( idx >= end+2 );
  42452. assert( idx+sz <= (int)pPage->pBt->usableSize );
  42453. pPage->nCell++;
  42454. pPage->nFree -= (u16)(2 + sz);
  42455. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  42456. if( iChild ){
  42457. put4byte(&data[idx], iChild);
  42458. }
  42459. ptr = &data[end];
  42460. endPtr = &data[ins];
  42461. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  42462. while( ptr>endPtr ){
  42463. *(u16*)ptr = *(u16*)&ptr[-2];
  42464. ptr -= 2;
  42465. }
  42466. put2byte(&data[ins], idx);
  42467. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  42468. #ifndef SQLITE_OMIT_AUTOVACUUM
  42469. if( pPage->pBt->autoVacuum ){
  42470. /* The cell may contain a pointer to an overflow page. If so, write
  42471. ** the entry for the overflow page into the pointer map.
  42472. */
  42473. ptrmapPutOvflPtr(pPage, pCell, pRC);
  42474. }
  42475. #endif
  42476. }
  42477. }
  42478. /*
  42479. ** Add a list of cells to a page. The page should be initially empty.
  42480. ** The cells are guaranteed to fit on the page.
  42481. */
  42482. static void assemblePage(
  42483. MemPage *pPage, /* The page to be assemblied */
  42484. int nCell, /* The number of cells to add to this page */
  42485. u8 **apCell, /* Pointers to cell bodies */
  42486. u16 *aSize /* Sizes of the cells */
  42487. ){
  42488. int i; /* Loop counter */
  42489. u8 *pCellptr; /* Address of next cell pointer */
  42490. int cellbody; /* Address of next cell body */
  42491. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  42492. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  42493. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  42494. assert( pPage->nOverflow==0 );
  42495. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42496. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  42497. && (int)MX_CELL(pPage->pBt)<=10921);
  42498. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  42499. /* Check that the page has just been zeroed by zeroPage() */
  42500. assert( pPage->nCell==0 );
  42501. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  42502. pCellptr = &pPage->aCellIdx[nCell*2];
  42503. cellbody = nUsable;
  42504. for(i=nCell-1; i>=0; i--){
  42505. u16 sz = aSize[i];
  42506. pCellptr -= 2;
  42507. cellbody -= sz;
  42508. put2byte(pCellptr, cellbody);
  42509. memcpy(&data[cellbody], apCell[i], sz);
  42510. }
  42511. put2byte(&data[hdr+3], nCell);
  42512. put2byte(&data[hdr+5], cellbody);
  42513. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  42514. pPage->nCell = (u16)nCell;
  42515. }
  42516. /*
  42517. ** The following parameters determine how many adjacent pages get involved
  42518. ** in a balancing operation. NN is the number of neighbors on either side
  42519. ** of the page that participate in the balancing operation. NB is the
  42520. ** total number of pages that participate, including the target page and
  42521. ** NN neighbors on either side.
  42522. **
  42523. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  42524. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  42525. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  42526. ** The value of NN appears to give the best results overall.
  42527. */
  42528. #define NN 1 /* Number of neighbors on either side of pPage */
  42529. #define NB (NN*2+1) /* Total pages involved in the balance */
  42530. #ifndef SQLITE_OMIT_QUICKBALANCE
  42531. /*
  42532. ** This version of balance() handles the common special case where
  42533. ** a new entry is being inserted on the extreme right-end of the
  42534. ** tree, in other words, when the new entry will become the largest
  42535. ** entry in the tree.
  42536. **
  42537. ** Instead of trying to balance the 3 right-most leaf pages, just add
  42538. ** a new page to the right-hand side and put the one new entry in
  42539. ** that page. This leaves the right side of the tree somewhat
  42540. ** unbalanced. But odds are that we will be inserting new entries
  42541. ** at the end soon afterwards so the nearly empty page will quickly
  42542. ** fill up. On average.
  42543. **
  42544. ** pPage is the leaf page which is the right-most page in the tree.
  42545. ** pParent is its parent. pPage must have a single overflow entry
  42546. ** which is also the right-most entry on the page.
  42547. **
  42548. ** The pSpace buffer is used to store a temporary copy of the divider
  42549. ** cell that will be inserted into pParent. Such a cell consists of a 4
  42550. ** byte page number followed by a variable length integer. In other
  42551. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  42552. ** least 13 bytes in size.
  42553. */
  42554. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  42555. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  42556. MemPage *pNew; /* Newly allocated page */
  42557. int rc; /* Return Code */
  42558. Pgno pgnoNew; /* Page number of pNew */
  42559. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  42560. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  42561. assert( pPage->nOverflow==1 );
  42562. /* This error condition is now caught prior to reaching this function */
  42563. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  42564. /* Allocate a new page. This page will become the right-sibling of
  42565. ** pPage. Make the parent page writable, so that the new divider cell
  42566. ** may be inserted. If both these operations are successful, proceed.
  42567. */
  42568. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  42569. if( rc==SQLITE_OK ){
  42570. u8 *pOut = &pSpace[4];
  42571. u8 *pCell = pPage->apOvfl[0];
  42572. u16 szCell = cellSizePtr(pPage, pCell);
  42573. u8 *pStop;
  42574. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  42575. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  42576. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  42577. assemblePage(pNew, 1, &pCell, &szCell);
  42578. /* If this is an auto-vacuum database, update the pointer map
  42579. ** with entries for the new page, and any pointer from the
  42580. ** cell on the page to an overflow page. If either of these
  42581. ** operations fails, the return code is set, but the contents
  42582. ** of the parent page are still manipulated by thh code below.
  42583. ** That is Ok, at this point the parent page is guaranteed to
  42584. ** be marked as dirty. Returning an error code will cause a
  42585. ** rollback, undoing any changes made to the parent page.
  42586. */
  42587. if( ISAUTOVACUUM ){
  42588. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  42589. if( szCell>pNew->minLocal ){
  42590. ptrmapPutOvflPtr(pNew, pCell, &rc);
  42591. }
  42592. }
  42593. /* Create a divider cell to insert into pParent. The divider cell
  42594. ** consists of a 4-byte page number (the page number of pPage) and
  42595. ** a variable length key value (which must be the same value as the
  42596. ** largest key on pPage).
  42597. **
  42598. ** To find the largest key value on pPage, first find the right-most
  42599. ** cell on pPage. The first two fields of this cell are the
  42600. ** record-length (a variable length integer at most 32-bits in size)
  42601. ** and the key value (a variable length integer, may have any value).
  42602. ** The first of the while(...) loops below skips over the record-length
  42603. ** field. The second while(...) loop copies the key value from the
  42604. ** cell on pPage into the pSpace buffer.
  42605. */
  42606. pCell = findCell(pPage, pPage->nCell-1);
  42607. pStop = &pCell[9];
  42608. while( (*(pCell++)&0x80) && pCell<pStop );
  42609. pStop = &pCell[9];
  42610. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  42611. /* Insert the new divider cell into pParent. */
  42612. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  42613. 0, pPage->pgno, &rc);
  42614. /* Set the right-child pointer of pParent to point to the new page. */
  42615. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  42616. /* Release the reference to the new page. */
  42617. releasePage(pNew);
  42618. }
  42619. return rc;
  42620. }
  42621. #endif /* SQLITE_OMIT_QUICKBALANCE */
  42622. #if 0
  42623. /*
  42624. ** This function does not contribute anything to the operation of SQLite.
  42625. ** it is sometimes activated temporarily while debugging code responsible
  42626. ** for setting pointer-map entries.
  42627. */
  42628. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  42629. int i, j;
  42630. for(i=0; i<nPage; i++){
  42631. Pgno n;
  42632. u8 e;
  42633. MemPage *pPage = apPage[i];
  42634. BtShared *pBt = pPage->pBt;
  42635. assert( pPage->isInit );
  42636. for(j=0; j<pPage->nCell; j++){
  42637. CellInfo info;
  42638. u8 *z;
  42639. z = findCell(pPage, j);
  42640. btreeParseCellPtr(pPage, z, &info);
  42641. if( info.iOverflow ){
  42642. Pgno ovfl = get4byte(&z[info.iOverflow]);
  42643. ptrmapGet(pBt, ovfl, &e, &n);
  42644. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  42645. }
  42646. if( !pPage->leaf ){
  42647. Pgno child = get4byte(z);
  42648. ptrmapGet(pBt, child, &e, &n);
  42649. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  42650. }
  42651. }
  42652. if( !pPage->leaf ){
  42653. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  42654. ptrmapGet(pBt, child, &e, &n);
  42655. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  42656. }
  42657. }
  42658. return 1;
  42659. }
  42660. #endif
  42661. /*
  42662. ** This function is used to copy the contents of the b-tree node stored
  42663. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  42664. ** the pointer-map entries for each child page are updated so that the
  42665. ** parent page stored in the pointer map is page pTo. If pFrom contained
  42666. ** any cells with overflow page pointers, then the corresponding pointer
  42667. ** map entries are also updated so that the parent page is page pTo.
  42668. **
  42669. ** If pFrom is currently carrying any overflow cells (entries in the
  42670. ** MemPage.apOvfl[] array), they are not copied to pTo.
  42671. **
  42672. ** Before returning, page pTo is reinitialized using btreeInitPage().
  42673. **
  42674. ** The performance of this function is not critical. It is only used by
  42675. ** the balance_shallower() and balance_deeper() procedures, neither of
  42676. ** which are called often under normal circumstances.
  42677. */
  42678. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  42679. if( (*pRC)==SQLITE_OK ){
  42680. BtShared * const pBt = pFrom->pBt;
  42681. u8 * const aFrom = pFrom->aData;
  42682. u8 * const aTo = pTo->aData;
  42683. int const iFromHdr = pFrom->hdrOffset;
  42684. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  42685. int rc;
  42686. int iData;
  42687. assert( pFrom->isInit );
  42688. assert( pFrom->nFree>=iToHdr );
  42689. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  42690. /* Copy the b-tree node content from page pFrom to page pTo. */
  42691. iData = get2byte(&aFrom[iFromHdr+5]);
  42692. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  42693. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  42694. /* Reinitialize page pTo so that the contents of the MemPage structure
  42695. ** match the new data. The initialization of pTo can actually fail under
  42696. ** fairly obscure circumstances, even though it is a copy of initialized
  42697. ** page pFrom.
  42698. */
  42699. pTo->isInit = 0;
  42700. rc = btreeInitPage(pTo);
  42701. if( rc!=SQLITE_OK ){
  42702. *pRC = rc;
  42703. return;
  42704. }
  42705. /* If this is an auto-vacuum database, update the pointer-map entries
  42706. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  42707. */
  42708. if( ISAUTOVACUUM ){
  42709. *pRC = setChildPtrmaps(pTo);
  42710. }
  42711. }
  42712. }
  42713. /*
  42714. ** This routine redistributes cells on the iParentIdx'th child of pParent
  42715. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  42716. ** same amount of free space. Usually a single sibling on either side of the
  42717. ** page are used in the balancing, though both siblings might come from one
  42718. ** side if the page is the first or last child of its parent. If the page
  42719. ** has fewer than 2 siblings (something which can only happen if the page
  42720. ** is a root page or a child of a root page) then all available siblings
  42721. ** participate in the balancing.
  42722. **
  42723. ** The number of siblings of the page might be increased or decreased by
  42724. ** one or two in an effort to keep pages nearly full but not over full.
  42725. **
  42726. ** Note that when this routine is called, some of the cells on the page
  42727. ** might not actually be stored in MemPage.aData[]. This can happen
  42728. ** if the page is overfull. This routine ensures that all cells allocated
  42729. ** to the page and its siblings fit into MemPage.aData[] before returning.
  42730. **
  42731. ** In the course of balancing the page and its siblings, cells may be
  42732. ** inserted into or removed from the parent page (pParent). Doing so
  42733. ** may cause the parent page to become overfull or underfull. If this
  42734. ** happens, it is the responsibility of the caller to invoke the correct
  42735. ** balancing routine to fix this problem (see the balance() routine).
  42736. **
  42737. ** If this routine fails for any reason, it might leave the database
  42738. ** in a corrupted state. So if this routine fails, the database should
  42739. ** be rolled back.
  42740. **
  42741. ** The third argument to this function, aOvflSpace, is a pointer to a
  42742. ** buffer big enough to hold one page. If while inserting cells into the parent
  42743. ** page (pParent) the parent page becomes overfull, this buffer is
  42744. ** used to store the parent's overflow cells. Because this function inserts
  42745. ** a maximum of four divider cells into the parent page, and the maximum
  42746. ** size of a cell stored within an internal node is always less than 1/4
  42747. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  42748. ** enough for all overflow cells.
  42749. **
  42750. ** If aOvflSpace is set to a null pointer, this function returns
  42751. ** SQLITE_NOMEM.
  42752. */
  42753. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  42754. #pragma optimize("", off)
  42755. #endif
  42756. static int balance_nonroot(
  42757. MemPage *pParent, /* Parent page of siblings being balanced */
  42758. int iParentIdx, /* Index of "the page" in pParent */
  42759. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  42760. int isRoot, /* True if pParent is a root-page */
  42761. int bBulk /* True if this call is part of a bulk load */
  42762. ){
  42763. BtShared *pBt; /* The whole database */
  42764. int nCell = 0; /* Number of cells in apCell[] */
  42765. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  42766. int nNew = 0; /* Number of pages in apNew[] */
  42767. int nOld; /* Number of pages in apOld[] */
  42768. int i, j, k; /* Loop counters */
  42769. int nxDiv; /* Next divider slot in pParent->aCell[] */
  42770. int rc = SQLITE_OK; /* The return code */
  42771. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  42772. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  42773. int usableSpace; /* Bytes in pPage beyond the header */
  42774. int pageFlags; /* Value of pPage->aData[0] */
  42775. int subtotal; /* Subtotal of bytes in cells on one page */
  42776. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  42777. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  42778. int szScratch; /* Size of scratch memory requested */
  42779. MemPage *apOld[NB]; /* pPage and up to two siblings */
  42780. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  42781. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  42782. u8 *pRight; /* Location in parent of right-sibling pointer */
  42783. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  42784. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  42785. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  42786. u8 **apCell = 0; /* All cells begin balanced */
  42787. u16 *szCell; /* Local size of all cells in apCell[] */
  42788. u8 *aSpace1; /* Space for copies of dividers cells */
  42789. Pgno pgno; /* Temp var to store a page number in */
  42790. pBt = pParent->pBt;
  42791. assert( sqlite3_mutex_held(pBt->mutex) );
  42792. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  42793. #if 0
  42794. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  42795. #endif
  42796. /* At this point pParent may have at most one overflow cell. And if
  42797. ** this overflow cell is present, it must be the cell with
  42798. ** index iParentIdx. This scenario comes about when this function
  42799. ** is called (indirectly) from sqlite3BtreeDelete().
  42800. */
  42801. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  42802. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  42803. if( !aOvflSpace ){
  42804. return SQLITE_NOMEM;
  42805. }
  42806. /* Find the sibling pages to balance. Also locate the cells in pParent
  42807. ** that divide the siblings. An attempt is made to find NN siblings on
  42808. ** either side of pPage. More siblings are taken from one side, however,
  42809. ** if there are fewer than NN siblings on the other side. If pParent
  42810. ** has NB or fewer children then all children of pParent are taken.
  42811. **
  42812. ** This loop also drops the divider cells from the parent page. This
  42813. ** way, the remainder of the function does not have to deal with any
  42814. ** overflow cells in the parent page, since if any existed they will
  42815. ** have already been removed.
  42816. */
  42817. i = pParent->nOverflow + pParent->nCell;
  42818. if( i<2 ){
  42819. nxDiv = 0;
  42820. }else{
  42821. assert( bBulk==0 || bBulk==1 );
  42822. if( iParentIdx==0 ){
  42823. nxDiv = 0;
  42824. }else if( iParentIdx==i ){
  42825. nxDiv = i-2+bBulk;
  42826. }else{
  42827. assert( bBulk==0 );
  42828. nxDiv = iParentIdx-1;
  42829. }
  42830. i = 2-bBulk;
  42831. }
  42832. nOld = i+1;
  42833. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  42834. pRight = &pParent->aData[pParent->hdrOffset+8];
  42835. }else{
  42836. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  42837. }
  42838. pgno = get4byte(pRight);
  42839. while( 1 ){
  42840. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  42841. if( rc ){
  42842. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  42843. goto balance_cleanup;
  42844. }
  42845. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  42846. if( (i--)==0 ) break;
  42847. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  42848. apDiv[i] = pParent->apOvfl[0];
  42849. pgno = get4byte(apDiv[i]);
  42850. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  42851. pParent->nOverflow = 0;
  42852. }else{
  42853. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  42854. pgno = get4byte(apDiv[i]);
  42855. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  42856. /* Drop the cell from the parent page. apDiv[i] still points to
  42857. ** the cell within the parent, even though it has been dropped.
  42858. ** This is safe because dropping a cell only overwrites the first
  42859. ** four bytes of it, and this function does not need the first
  42860. ** four bytes of the divider cell. So the pointer is safe to use
  42861. ** later on.
  42862. **
  42863. ** But not if we are in secure-delete mode. In secure-delete mode,
  42864. ** the dropCell() routine will overwrite the entire cell with zeroes.
  42865. ** In this case, temporarily copy the cell into the aOvflSpace[]
  42866. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  42867. ** is allocated. */
  42868. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  42869. int iOff;
  42870. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  42871. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  42872. rc = SQLITE_CORRUPT_BKPT;
  42873. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  42874. goto balance_cleanup;
  42875. }else{
  42876. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  42877. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  42878. }
  42879. }
  42880. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  42881. }
  42882. }
  42883. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  42884. ** alignment */
  42885. nMaxCells = (nMaxCells + 3)&~3;
  42886. /*
  42887. ** Allocate space for memory structures
  42888. */
  42889. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  42890. szScratch =
  42891. nMaxCells*sizeof(u8*) /* apCell */
  42892. + nMaxCells*sizeof(u16) /* szCell */
  42893. + pBt->pageSize /* aSpace1 */
  42894. + k*nOld; /* Page copies (apCopy) */
  42895. apCell = sqlite3ScratchMalloc( szScratch );
  42896. if( apCell==0 ){
  42897. rc = SQLITE_NOMEM;
  42898. goto balance_cleanup;
  42899. }
  42900. szCell = (u16*)&apCell[nMaxCells];
  42901. aSpace1 = (u8*)&szCell[nMaxCells];
  42902. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  42903. /*
  42904. ** Load pointers to all cells on sibling pages and the divider cells
  42905. ** into the local apCell[] array. Make copies of the divider cells
  42906. ** into space obtained from aSpace1[] and remove the divider cells
  42907. ** from pParent.
  42908. **
  42909. ** If the siblings are on leaf pages, then the child pointers of the
  42910. ** divider cells are stripped from the cells before they are copied
  42911. ** into aSpace1[]. In this way, all cells in apCell[] are without
  42912. ** child pointers. If siblings are not leaves, then all cell in
  42913. ** apCell[] include child pointers. Either way, all cells in apCell[]
  42914. ** are alike.
  42915. **
  42916. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  42917. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  42918. */
  42919. leafCorrection = apOld[0]->leaf*4;
  42920. leafData = apOld[0]->hasData;
  42921. for(i=0; i<nOld; i++){
  42922. int limit;
  42923. /* Before doing anything else, take a copy of the i'th original sibling
  42924. ** The rest of this function will use data from the copies rather
  42925. ** that the original pages since the original pages will be in the
  42926. ** process of being overwritten. */
  42927. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  42928. memcpy(pOld, apOld[i], sizeof(MemPage));
  42929. pOld->aData = (void*)&pOld[1];
  42930. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  42931. limit = pOld->nCell+pOld->nOverflow;
  42932. if( pOld->nOverflow>0 ){
  42933. for(j=0; j<limit; j++){
  42934. assert( nCell<nMaxCells );
  42935. apCell[nCell] = findOverflowCell(pOld, j);
  42936. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  42937. nCell++;
  42938. }
  42939. }else{
  42940. u8 *aData = pOld->aData;
  42941. u16 maskPage = pOld->maskPage;
  42942. u16 cellOffset = pOld->cellOffset;
  42943. for(j=0; j<limit; j++){
  42944. assert( nCell<nMaxCells );
  42945. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  42946. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  42947. nCell++;
  42948. }
  42949. }
  42950. if( i<nOld-1 && !leafData){
  42951. u16 sz = (u16)szNew[i];
  42952. u8 *pTemp;
  42953. assert( nCell<nMaxCells );
  42954. szCell[nCell] = sz;
  42955. pTemp = &aSpace1[iSpace1];
  42956. iSpace1 += sz;
  42957. assert( sz<=pBt->maxLocal+23 );
  42958. assert( iSpace1 <= (int)pBt->pageSize );
  42959. memcpy(pTemp, apDiv[i], sz);
  42960. apCell[nCell] = pTemp+leafCorrection;
  42961. assert( leafCorrection==0 || leafCorrection==4 );
  42962. szCell[nCell] = szCell[nCell] - leafCorrection;
  42963. if( !pOld->leaf ){
  42964. assert( leafCorrection==0 );
  42965. assert( pOld->hdrOffset==0 );
  42966. /* The right pointer of the child page pOld becomes the left
  42967. ** pointer of the divider cell */
  42968. memcpy(apCell[nCell], &pOld->aData[8], 4);
  42969. }else{
  42970. assert( leafCorrection==4 );
  42971. if( szCell[nCell]<4 ){
  42972. /* Do not allow any cells smaller than 4 bytes. */
  42973. szCell[nCell] = 4;
  42974. }
  42975. }
  42976. nCell++;
  42977. }
  42978. }
  42979. /*
  42980. ** Figure out the number of pages needed to hold all nCell cells.
  42981. ** Store this number in "k". Also compute szNew[] which is the total
  42982. ** size of all cells on the i-th page and cntNew[] which is the index
  42983. ** in apCell[] of the cell that divides page i from page i+1.
  42984. ** cntNew[k] should equal nCell.
  42985. **
  42986. ** Values computed by this block:
  42987. **
  42988. ** k: The total number of sibling pages
  42989. ** szNew[i]: Spaced used on the i-th sibling page.
  42990. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  42991. ** the right of the i-th sibling page.
  42992. ** usableSpace: Number of bytes of space available on each sibling.
  42993. **
  42994. */
  42995. usableSpace = pBt->usableSize - 12 + leafCorrection;
  42996. for(subtotal=k=i=0; i<nCell; i++){
  42997. assert( i<nMaxCells );
  42998. subtotal += szCell[i] + 2;
  42999. if( subtotal > usableSpace ){
  43000. szNew[k] = subtotal - szCell[i];
  43001. cntNew[k] = i;
  43002. if( leafData ){ i--; }
  43003. subtotal = 0;
  43004. k++;
  43005. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  43006. }
  43007. }
  43008. szNew[k] = subtotal;
  43009. cntNew[k] = nCell;
  43010. k++;
  43011. /*
  43012. ** The packing computed by the previous block is biased toward the siblings
  43013. ** on the left side. The left siblings are always nearly full, while the
  43014. ** right-most sibling might be nearly empty. This block of code attempts
  43015. ** to adjust the packing of siblings to get a better balance.
  43016. **
  43017. ** This adjustment is more than an optimization. The packing above might
  43018. ** be so out of balance as to be illegal. For example, the right-most
  43019. ** sibling might be completely empty. This adjustment is not optional.
  43020. */
  43021. for(i=k-1; i>0; i--){
  43022. int szRight = szNew[i]; /* Size of sibling on the right */
  43023. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  43024. int r; /* Index of right-most cell in left sibling */
  43025. int d; /* Index of first cell to the left of right sibling */
  43026. r = cntNew[i-1] - 1;
  43027. d = r + 1 - leafData;
  43028. assert( d<nMaxCells );
  43029. assert( r<nMaxCells );
  43030. while( szRight==0
  43031. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  43032. ){
  43033. szRight += szCell[d] + 2;
  43034. szLeft -= szCell[r] + 2;
  43035. cntNew[i-1]--;
  43036. r = cntNew[i-1] - 1;
  43037. d = r + 1 - leafData;
  43038. }
  43039. szNew[i] = szRight;
  43040. szNew[i-1] = szLeft;
  43041. }
  43042. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  43043. ** a virtual root page. A virtual root page is when the real root
  43044. ** page is page 1 and we are the only child of that page.
  43045. **
  43046. ** UPDATE: The assert() below is not necessarily true if the database
  43047. ** file is corrupt. The corruption will be detected and reported later
  43048. ** in this procedure so there is no need to act upon it now.
  43049. */
  43050. #if 0
  43051. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  43052. #endif
  43053. TRACE(("BALANCE: old: %d %d %d ",
  43054. apOld[0]->pgno,
  43055. nOld>=2 ? apOld[1]->pgno : 0,
  43056. nOld>=3 ? apOld[2]->pgno : 0
  43057. ));
  43058. /*
  43059. ** Allocate k new pages. Reuse old pages where possible.
  43060. */
  43061. if( apOld[0]->pgno<=1 ){
  43062. rc = SQLITE_CORRUPT_BKPT;
  43063. goto balance_cleanup;
  43064. }
  43065. pageFlags = apOld[0]->aData[0];
  43066. for(i=0; i<k; i++){
  43067. MemPage *pNew;
  43068. if( i<nOld ){
  43069. pNew = apNew[i] = apOld[i];
  43070. apOld[i] = 0;
  43071. rc = sqlite3PagerWrite(pNew->pDbPage);
  43072. nNew++;
  43073. if( rc ) goto balance_cleanup;
  43074. }else{
  43075. assert( i>0 );
  43076. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  43077. if( rc ) goto balance_cleanup;
  43078. apNew[i] = pNew;
  43079. nNew++;
  43080. /* Set the pointer-map entry for the new sibling page. */
  43081. if( ISAUTOVACUUM ){
  43082. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  43083. if( rc!=SQLITE_OK ){
  43084. goto balance_cleanup;
  43085. }
  43086. }
  43087. }
  43088. }
  43089. /* Free any old pages that were not reused as new pages.
  43090. */
  43091. while( i<nOld ){
  43092. freePage(apOld[i], &rc);
  43093. if( rc ) goto balance_cleanup;
  43094. releasePage(apOld[i]);
  43095. apOld[i] = 0;
  43096. i++;
  43097. }
  43098. /*
  43099. ** Put the new pages in accending order. This helps to
  43100. ** keep entries in the disk file in order so that a scan
  43101. ** of the table is a linear scan through the file. That
  43102. ** in turn helps the operating system to deliver pages
  43103. ** from the disk more rapidly.
  43104. **
  43105. ** An O(n^2) insertion sort algorithm is used, but since
  43106. ** n is never more than NB (a small constant), that should
  43107. ** not be a problem.
  43108. **
  43109. ** When NB==3, this one optimization makes the database
  43110. ** about 25% faster for large insertions and deletions.
  43111. */
  43112. for(i=0; i<k-1; i++){
  43113. int minV = apNew[i]->pgno;
  43114. int minI = i;
  43115. for(j=i+1; j<k; j++){
  43116. if( apNew[j]->pgno<(unsigned)minV ){
  43117. minI = j;
  43118. minV = apNew[j]->pgno;
  43119. }
  43120. }
  43121. if( minI>i ){
  43122. MemPage *pT;
  43123. pT = apNew[i];
  43124. apNew[i] = apNew[minI];
  43125. apNew[minI] = pT;
  43126. }
  43127. }
  43128. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  43129. apNew[0]->pgno, szNew[0],
  43130. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  43131. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  43132. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  43133. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  43134. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  43135. put4byte(pRight, apNew[nNew-1]->pgno);
  43136. /*
  43137. ** Evenly distribute the data in apCell[] across the new pages.
  43138. ** Insert divider cells into pParent as necessary.
  43139. */
  43140. j = 0;
  43141. for(i=0; i<nNew; i++){
  43142. /* Assemble the new sibling page. */
  43143. MemPage *pNew = apNew[i];
  43144. assert( j<nMaxCells );
  43145. zeroPage(pNew, pageFlags);
  43146. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  43147. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  43148. assert( pNew->nOverflow==0 );
  43149. j = cntNew[i];
  43150. /* If the sibling page assembled above was not the right-most sibling,
  43151. ** insert a divider cell into the parent page.
  43152. */
  43153. assert( i<nNew-1 || j==nCell );
  43154. if( j<nCell ){
  43155. u8 *pCell;
  43156. u8 *pTemp;
  43157. int sz;
  43158. assert( j<nMaxCells );
  43159. pCell = apCell[j];
  43160. sz = szCell[j] + leafCorrection;
  43161. pTemp = &aOvflSpace[iOvflSpace];
  43162. if( !pNew->leaf ){
  43163. memcpy(&pNew->aData[8], pCell, 4);
  43164. }else if( leafData ){
  43165. /* If the tree is a leaf-data tree, and the siblings are leaves,
  43166. ** then there is no divider cell in apCell[]. Instead, the divider
  43167. ** cell consists of the integer key for the right-most cell of
  43168. ** the sibling-page assembled above only.
  43169. */
  43170. CellInfo info;
  43171. j--;
  43172. btreeParseCellPtr(pNew, apCell[j], &info);
  43173. pCell = pTemp;
  43174. sz = 4 + putVarint(&pCell[4], info.nKey);
  43175. pTemp = 0;
  43176. }else{
  43177. pCell -= 4;
  43178. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  43179. ** previously stored on a leaf node, and its reported size was 4
  43180. ** bytes, then it may actually be smaller than this
  43181. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  43182. ** any cell). But it is important to pass the correct size to
  43183. ** insertCell(), so reparse the cell now.
  43184. **
  43185. ** Note that this can never happen in an SQLite data file, as all
  43186. ** cells are at least 4 bytes. It only happens in b-trees used
  43187. ** to evaluate "IN (SELECT ...)" and similar clauses.
  43188. */
  43189. if( szCell[j]==4 ){
  43190. assert(leafCorrection==4);
  43191. sz = cellSizePtr(pParent, pCell);
  43192. }
  43193. }
  43194. iOvflSpace += sz;
  43195. assert( sz<=pBt->maxLocal+23 );
  43196. assert( iOvflSpace <= (int)pBt->pageSize );
  43197. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  43198. if( rc!=SQLITE_OK ) goto balance_cleanup;
  43199. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  43200. j++;
  43201. nxDiv++;
  43202. }
  43203. }
  43204. assert( j==nCell );
  43205. assert( nOld>0 );
  43206. assert( nNew>0 );
  43207. if( (pageFlags & PTF_LEAF)==0 ){
  43208. u8 *zChild = &apCopy[nOld-1]->aData[8];
  43209. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  43210. }
  43211. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  43212. /* The root page of the b-tree now contains no cells. The only sibling
  43213. ** page is the right-child of the parent. Copy the contents of the
  43214. ** child page into the parent, decreasing the overall height of the
  43215. ** b-tree structure by one. This is described as the "balance-shallower"
  43216. ** sub-algorithm in some documentation.
  43217. **
  43218. ** If this is an auto-vacuum database, the call to copyNodeContent()
  43219. ** sets all pointer-map entries corresponding to database image pages
  43220. ** for which the pointer is stored within the content being copied.
  43221. **
  43222. ** The second assert below verifies that the child page is defragmented
  43223. ** (it must be, as it was just reconstructed using assemblePage()). This
  43224. ** is important if the parent page happens to be page 1 of the database
  43225. ** image. */
  43226. assert( nNew==1 );
  43227. assert( apNew[0]->nFree ==
  43228. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  43229. );
  43230. copyNodeContent(apNew[0], pParent, &rc);
  43231. freePage(apNew[0], &rc);
  43232. }else if( ISAUTOVACUUM ){
  43233. /* Fix the pointer-map entries for all the cells that were shifted around.
  43234. ** There are several different types of pointer-map entries that need to
  43235. ** be dealt with by this routine. Some of these have been set already, but
  43236. ** many have not. The following is a summary:
  43237. **
  43238. ** 1) The entries associated with new sibling pages that were not
  43239. ** siblings when this function was called. These have already
  43240. ** been set. We don't need to worry about old siblings that were
  43241. ** moved to the free-list - the freePage() code has taken care
  43242. ** of those.
  43243. **
  43244. ** 2) The pointer-map entries associated with the first overflow
  43245. ** page in any overflow chains used by new divider cells. These
  43246. ** have also already been taken care of by the insertCell() code.
  43247. **
  43248. ** 3) If the sibling pages are not leaves, then the child pages of
  43249. ** cells stored on the sibling pages may need to be updated.
  43250. **
  43251. ** 4) If the sibling pages are not internal intkey nodes, then any
  43252. ** overflow pages used by these cells may need to be updated
  43253. ** (internal intkey nodes never contain pointers to overflow pages).
  43254. **
  43255. ** 5) If the sibling pages are not leaves, then the pointer-map
  43256. ** entries for the right-child pages of each sibling may need
  43257. ** to be updated.
  43258. **
  43259. ** Cases 1 and 2 are dealt with above by other code. The next
  43260. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  43261. ** setting a pointer map entry is a relatively expensive operation, this
  43262. ** code only sets pointer map entries for child or overflow pages that have
  43263. ** actually moved between pages. */
  43264. MemPage *pNew = apNew[0];
  43265. MemPage *pOld = apCopy[0];
  43266. int nOverflow = pOld->nOverflow;
  43267. int iNextOld = pOld->nCell + nOverflow;
  43268. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  43269. j = 0; /* Current 'old' sibling page */
  43270. k = 0; /* Current 'new' sibling page */
  43271. for(i=0; i<nCell; i++){
  43272. int isDivider = 0;
  43273. while( i==iNextOld ){
  43274. /* Cell i is the cell immediately following the last cell on old
  43275. ** sibling page j. If the siblings are not leaf pages of an
  43276. ** intkey b-tree, then cell i was a divider cell. */
  43277. assert( j+1 < ArraySize(apCopy) );
  43278. assert( j+1 < nOld );
  43279. pOld = apCopy[++j];
  43280. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  43281. if( pOld->nOverflow ){
  43282. nOverflow = pOld->nOverflow;
  43283. iOverflow = i + !leafData + pOld->aiOvfl[0];
  43284. }
  43285. isDivider = !leafData;
  43286. }
  43287. assert(nOverflow>0 || iOverflow<i );
  43288. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  43289. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  43290. if( i==iOverflow ){
  43291. isDivider = 1;
  43292. if( (--nOverflow)>0 ){
  43293. iOverflow++;
  43294. }
  43295. }
  43296. if( i==cntNew[k] ){
  43297. /* Cell i is the cell immediately following the last cell on new
  43298. ** sibling page k. If the siblings are not leaf pages of an
  43299. ** intkey b-tree, then cell i is a divider cell. */
  43300. pNew = apNew[++k];
  43301. if( !leafData ) continue;
  43302. }
  43303. assert( j<nOld );
  43304. assert( k<nNew );
  43305. /* If the cell was originally divider cell (and is not now) or
  43306. ** an overflow cell, or if the cell was located on a different sibling
  43307. ** page before the balancing, then the pointer map entries associated
  43308. ** with any child or overflow pages need to be updated. */
  43309. if( isDivider || pOld->pgno!=pNew->pgno ){
  43310. if( !leafCorrection ){
  43311. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  43312. }
  43313. if( szCell[i]>pNew->minLocal ){
  43314. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  43315. }
  43316. }
  43317. }
  43318. if( !leafCorrection ){
  43319. for(i=0; i<nNew; i++){
  43320. u32 key = get4byte(&apNew[i]->aData[8]);
  43321. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  43322. }
  43323. }
  43324. #if 0
  43325. /* The ptrmapCheckPages() contains assert() statements that verify that
  43326. ** all pointer map pages are set correctly. This is helpful while
  43327. ** debugging. This is usually disabled because a corrupt database may
  43328. ** cause an assert() statement to fail. */
  43329. ptrmapCheckPages(apNew, nNew);
  43330. ptrmapCheckPages(&pParent, 1);
  43331. #endif
  43332. }
  43333. assert( pParent->isInit );
  43334. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  43335. nOld, nNew, nCell));
  43336. /*
  43337. ** Cleanup before returning.
  43338. */
  43339. balance_cleanup:
  43340. sqlite3ScratchFree(apCell);
  43341. for(i=0; i<nOld; i++){
  43342. releasePage(apOld[i]);
  43343. }
  43344. for(i=0; i<nNew; i++){
  43345. releasePage(apNew[i]);
  43346. }
  43347. return rc;
  43348. }
  43349. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  43350. #pragma optimize("", on)
  43351. #endif
  43352. /*
  43353. ** This function is called when the root page of a b-tree structure is
  43354. ** overfull (has one or more overflow pages).
  43355. **
  43356. ** A new child page is allocated and the contents of the current root
  43357. ** page, including overflow cells, are copied into the child. The root
  43358. ** page is then overwritten to make it an empty page with the right-child
  43359. ** pointer pointing to the new page.
  43360. **
  43361. ** Before returning, all pointer-map entries corresponding to pages
  43362. ** that the new child-page now contains pointers to are updated. The
  43363. ** entry corresponding to the new right-child pointer of the root
  43364. ** page is also updated.
  43365. **
  43366. ** If successful, *ppChild is set to contain a reference to the child
  43367. ** page and SQLITE_OK is returned. In this case the caller is required
  43368. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  43369. ** an error code is returned and *ppChild is set to 0.
  43370. */
  43371. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  43372. int rc; /* Return value from subprocedures */
  43373. MemPage *pChild = 0; /* Pointer to a new child page */
  43374. Pgno pgnoChild = 0; /* Page number of the new child page */
  43375. BtShared *pBt = pRoot->pBt; /* The BTree */
  43376. assert( pRoot->nOverflow>0 );
  43377. assert( sqlite3_mutex_held(pBt->mutex) );
  43378. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  43379. ** page that will become the new right-child of pPage. Copy the contents
  43380. ** of the node stored on pRoot into the new child page.
  43381. */
  43382. rc = sqlite3PagerWrite(pRoot->pDbPage);
  43383. if( rc==SQLITE_OK ){
  43384. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  43385. copyNodeContent(pRoot, pChild, &rc);
  43386. if( ISAUTOVACUUM ){
  43387. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  43388. }
  43389. }
  43390. if( rc ){
  43391. *ppChild = 0;
  43392. releasePage(pChild);
  43393. return rc;
  43394. }
  43395. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  43396. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  43397. assert( pChild->nCell==pRoot->nCell );
  43398. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  43399. /* Copy the overflow cells from pRoot to pChild */
  43400. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  43401. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  43402. memcpy(pChild->apOvfl, pRoot->apOvfl,
  43403. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  43404. pChild->nOverflow = pRoot->nOverflow;
  43405. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  43406. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  43407. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  43408. *ppChild = pChild;
  43409. return SQLITE_OK;
  43410. }
  43411. /*
  43412. ** The page that pCur currently points to has just been modified in
  43413. ** some way. This function figures out if this modification means the
  43414. ** tree needs to be balanced, and if so calls the appropriate balancing
  43415. ** routine. Balancing routines are:
  43416. **
  43417. ** balance_quick()
  43418. ** balance_deeper()
  43419. ** balance_nonroot()
  43420. */
  43421. static int balance(BtCursor *pCur){
  43422. int rc = SQLITE_OK;
  43423. const int nMin = pCur->pBt->usableSize * 2 / 3;
  43424. u8 aBalanceQuickSpace[13];
  43425. u8 *pFree = 0;
  43426. TESTONLY( int balance_quick_called = 0 );
  43427. TESTONLY( int balance_deeper_called = 0 );
  43428. do {
  43429. int iPage = pCur->iPage;
  43430. MemPage *pPage = pCur->apPage[iPage];
  43431. if( iPage==0 ){
  43432. if( pPage->nOverflow ){
  43433. /* The root page of the b-tree is overfull. In this case call the
  43434. ** balance_deeper() function to create a new child for the root-page
  43435. ** and copy the current contents of the root-page to it. The
  43436. ** next iteration of the do-loop will balance the child page.
  43437. */
  43438. assert( (balance_deeper_called++)==0 );
  43439. rc = balance_deeper(pPage, &pCur->apPage[1]);
  43440. if( rc==SQLITE_OK ){
  43441. pCur->iPage = 1;
  43442. pCur->aiIdx[0] = 0;
  43443. pCur->aiIdx[1] = 0;
  43444. assert( pCur->apPage[1]->nOverflow );
  43445. }
  43446. }else{
  43447. break;
  43448. }
  43449. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  43450. break;
  43451. }else{
  43452. MemPage * const pParent = pCur->apPage[iPage-1];
  43453. int const iIdx = pCur->aiIdx[iPage-1];
  43454. rc = sqlite3PagerWrite(pParent->pDbPage);
  43455. if( rc==SQLITE_OK ){
  43456. #ifndef SQLITE_OMIT_QUICKBALANCE
  43457. if( pPage->hasData
  43458. && pPage->nOverflow==1
  43459. && pPage->aiOvfl[0]==pPage->nCell
  43460. && pParent->pgno!=1
  43461. && pParent->nCell==iIdx
  43462. ){
  43463. /* Call balance_quick() to create a new sibling of pPage on which
  43464. ** to store the overflow cell. balance_quick() inserts a new cell
  43465. ** into pParent, which may cause pParent overflow. If this
  43466. ** happens, the next interation of the do-loop will balance pParent
  43467. ** use either balance_nonroot() or balance_deeper(). Until this
  43468. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  43469. ** buffer.
  43470. **
  43471. ** The purpose of the following assert() is to check that only a
  43472. ** single call to balance_quick() is made for each call to this
  43473. ** function. If this were not verified, a subtle bug involving reuse
  43474. ** of the aBalanceQuickSpace[] might sneak in.
  43475. */
  43476. assert( (balance_quick_called++)==0 );
  43477. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  43478. }else
  43479. #endif
  43480. {
  43481. /* In this case, call balance_nonroot() to redistribute cells
  43482. ** between pPage and up to 2 of its sibling pages. This involves
  43483. ** modifying the contents of pParent, which may cause pParent to
  43484. ** become overfull or underfull. The next iteration of the do-loop
  43485. ** will balance the parent page to correct this.
  43486. **
  43487. ** If the parent page becomes overfull, the overflow cell or cells
  43488. ** are stored in the pSpace buffer allocated immediately below.
  43489. ** A subsequent iteration of the do-loop will deal with this by
  43490. ** calling balance_nonroot() (balance_deeper() may be called first,
  43491. ** but it doesn't deal with overflow cells - just moves them to a
  43492. ** different page). Once this subsequent call to balance_nonroot()
  43493. ** has completed, it is safe to release the pSpace buffer used by
  43494. ** the previous call, as the overflow cell data will have been
  43495. ** copied either into the body of a database page or into the new
  43496. ** pSpace buffer passed to the latter call to balance_nonroot().
  43497. */
  43498. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  43499. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  43500. if( pFree ){
  43501. /* If pFree is not NULL, it points to the pSpace buffer used
  43502. ** by a previous call to balance_nonroot(). Its contents are
  43503. ** now stored either on real database pages or within the
  43504. ** new pSpace buffer, so it may be safely freed here. */
  43505. sqlite3PageFree(pFree);
  43506. }
  43507. /* The pSpace buffer will be freed after the next call to
  43508. ** balance_nonroot(), or just before this function returns, whichever
  43509. ** comes first. */
  43510. pFree = pSpace;
  43511. }
  43512. }
  43513. pPage->nOverflow = 0;
  43514. /* The next iteration of the do-loop balances the parent page. */
  43515. releasePage(pPage);
  43516. pCur->iPage--;
  43517. }
  43518. }while( rc==SQLITE_OK );
  43519. if( pFree ){
  43520. sqlite3PageFree(pFree);
  43521. }
  43522. return rc;
  43523. }
  43524. /*
  43525. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  43526. ** and the data is given by (pData,nData). The cursor is used only to
  43527. ** define what table the record should be inserted into. The cursor
  43528. ** is left pointing at a random location.
  43529. **
  43530. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  43531. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  43532. **
  43533. ** If the seekResult parameter is non-zero, then a successful call to
  43534. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  43535. ** been performed. seekResult is the search result returned (a negative
  43536. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  43537. ** a positive value if pCur points at an etry that is larger than
  43538. ** (pKey, nKey)).
  43539. **
  43540. ** If the seekResult parameter is non-zero, then the caller guarantees that
  43541. ** cursor pCur is pointing at the existing copy of a row that is to be
  43542. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  43543. ** point to any entry or to no entry at all and so this function has to seek
  43544. ** the cursor before the new key can be inserted.
  43545. */
  43546. SQLITE_PRIVATE int sqlite3BtreeInsert(
  43547. BtCursor *pCur, /* Insert data into the table of this cursor */
  43548. const void *pKey, i64 nKey, /* The key of the new record */
  43549. const void *pData, int nData, /* The data of the new record */
  43550. int nZero, /* Number of extra 0 bytes to append to data */
  43551. int appendBias, /* True if this is likely an append */
  43552. int seekResult /* Result of prior MovetoUnpacked() call */
  43553. ){
  43554. int rc;
  43555. int loc = seekResult; /* -1: before desired location +1: after */
  43556. int szNew = 0;
  43557. int idx;
  43558. MemPage *pPage;
  43559. Btree *p = pCur->pBtree;
  43560. BtShared *pBt = p->pBt;
  43561. unsigned char *oldCell;
  43562. unsigned char *newCell = 0;
  43563. if( pCur->eState==CURSOR_FAULT ){
  43564. assert( pCur->skipNext!=SQLITE_OK );
  43565. return pCur->skipNext;
  43566. }
  43567. assert( cursorHoldsMutex(pCur) );
  43568. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  43569. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43570. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  43571. /* Assert that the caller has been consistent. If this cursor was opened
  43572. ** expecting an index b-tree, then the caller should be inserting blob
  43573. ** keys with no associated data. If the cursor was opened expecting an
  43574. ** intkey table, the caller should be inserting integer keys with a
  43575. ** blob of associated data. */
  43576. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  43577. /* Save the positions of any other cursors open on this table.
  43578. **
  43579. ** In some cases, the call to btreeMoveto() below is a no-op. For
  43580. ** example, when inserting data into a table with auto-generated integer
  43581. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  43582. ** integer key to use. It then calls this function to actually insert the
  43583. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  43584. ** that the cursor is already where it needs to be and returns without
  43585. ** doing any work. To avoid thwarting these optimizations, it is important
  43586. ** not to clear the cursor here.
  43587. */
  43588. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  43589. if( rc ) return rc;
  43590. /* If this is an insert into a table b-tree, invalidate any incrblob
  43591. ** cursors open on the row being replaced (assuming this is a replace
  43592. ** operation - if it is not, the following is a no-op). */
  43593. if( pCur->pKeyInfo==0 ){
  43594. invalidateIncrblobCursors(p, nKey, 0);
  43595. }
  43596. if( !loc ){
  43597. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  43598. if( rc ) return rc;
  43599. }
  43600. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  43601. pPage = pCur->apPage[pCur->iPage];
  43602. assert( pPage->intKey || nKey>=0 );
  43603. assert( pPage->leaf || !pPage->intKey );
  43604. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  43605. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  43606. loc==0 ? "overwrite" : "new entry"));
  43607. assert( pPage->isInit );
  43608. allocateTempSpace(pBt);
  43609. newCell = pBt->pTmpSpace;
  43610. if( newCell==0 ) return SQLITE_NOMEM;
  43611. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  43612. if( rc ) goto end_insert;
  43613. assert( szNew==cellSizePtr(pPage, newCell) );
  43614. assert( szNew <= MX_CELL_SIZE(pBt) );
  43615. idx = pCur->aiIdx[pCur->iPage];
  43616. if( loc==0 ){
  43617. u16 szOld;
  43618. assert( idx<pPage->nCell );
  43619. rc = sqlite3PagerWrite(pPage->pDbPage);
  43620. if( rc ){
  43621. goto end_insert;
  43622. }
  43623. oldCell = findCell(pPage, idx);
  43624. if( !pPage->leaf ){
  43625. memcpy(newCell, oldCell, 4);
  43626. }
  43627. szOld = cellSizePtr(pPage, oldCell);
  43628. rc = clearCell(pPage, oldCell);
  43629. dropCell(pPage, idx, szOld, &rc);
  43630. if( rc ) goto end_insert;
  43631. }else if( loc<0 && pPage->nCell>0 ){
  43632. assert( pPage->leaf );
  43633. idx = ++pCur->aiIdx[pCur->iPage];
  43634. }else{
  43635. assert( pPage->leaf );
  43636. }
  43637. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  43638. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  43639. /* If no error has occurred and pPage has an overflow cell, call balance()
  43640. ** to redistribute the cells within the tree. Since balance() may move
  43641. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  43642. ** variables.
  43643. **
  43644. ** Previous versions of SQLite called moveToRoot() to move the cursor
  43645. ** back to the root page as balance() used to invalidate the contents
  43646. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  43647. ** set the cursor state to "invalid". This makes common insert operations
  43648. ** slightly faster.
  43649. **
  43650. ** There is a subtle but important optimization here too. When inserting
  43651. ** multiple records into an intkey b-tree using a single cursor (as can
  43652. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  43653. ** is advantageous to leave the cursor pointing to the last entry in
  43654. ** the b-tree if possible. If the cursor is left pointing to the last
  43655. ** entry in the table, and the next row inserted has an integer key
  43656. ** larger than the largest existing key, it is possible to insert the
  43657. ** row without seeking the cursor. This can be a big performance boost.
  43658. */
  43659. pCur->info.nSize = 0;
  43660. pCur->validNKey = 0;
  43661. if( rc==SQLITE_OK && pPage->nOverflow ){
  43662. rc = balance(pCur);
  43663. /* Must make sure nOverflow is reset to zero even if the balance()
  43664. ** fails. Internal data structure corruption will result otherwise.
  43665. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  43666. ** from trying to save the current position of the cursor. */
  43667. pCur->apPage[pCur->iPage]->nOverflow = 0;
  43668. pCur->eState = CURSOR_INVALID;
  43669. }
  43670. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  43671. end_insert:
  43672. return rc;
  43673. }
  43674. /*
  43675. ** Delete the entry that the cursor is pointing to. The cursor
  43676. ** is left pointing at a arbitrary location.
  43677. */
  43678. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  43679. Btree *p = pCur->pBtree;
  43680. BtShared *pBt = p->pBt;
  43681. int rc; /* Return code */
  43682. MemPage *pPage; /* Page to delete cell from */
  43683. unsigned char *pCell; /* Pointer to cell to delete */
  43684. int iCellIdx; /* Index of cell to delete */
  43685. int iCellDepth; /* Depth of node containing pCell */
  43686. assert( cursorHoldsMutex(pCur) );
  43687. assert( pBt->inTransaction==TRANS_WRITE );
  43688. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43689. assert( pCur->wrFlag );
  43690. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  43691. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  43692. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  43693. || NEVER(pCur->eState!=CURSOR_VALID)
  43694. ){
  43695. return SQLITE_ERROR; /* Something has gone awry. */
  43696. }
  43697. iCellDepth = pCur->iPage;
  43698. iCellIdx = pCur->aiIdx[iCellDepth];
  43699. pPage = pCur->apPage[iCellDepth];
  43700. pCell = findCell(pPage, iCellIdx);
  43701. /* If the page containing the entry to delete is not a leaf page, move
  43702. ** the cursor to the largest entry in the tree that is smaller than
  43703. ** the entry being deleted. This cell will replace the cell being deleted
  43704. ** from the internal node. The 'previous' entry is used for this instead
  43705. ** of the 'next' entry, as the previous entry is always a part of the
  43706. ** sub-tree headed by the child page of the cell being deleted. This makes
  43707. ** balancing the tree following the delete operation easier. */
  43708. if( !pPage->leaf ){
  43709. int notUsed;
  43710. rc = sqlite3BtreePrevious(pCur, &notUsed);
  43711. if( rc ) return rc;
  43712. }
  43713. /* Save the positions of any other cursors open on this table before
  43714. ** making any modifications. Make the page containing the entry to be
  43715. ** deleted writable. Then free any overflow pages associated with the
  43716. ** entry and finally remove the cell itself from within the page.
  43717. */
  43718. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  43719. if( rc ) return rc;
  43720. /* If this is a delete operation to remove a row from a table b-tree,
  43721. ** invalidate any incrblob cursors open on the row being deleted. */
  43722. if( pCur->pKeyInfo==0 ){
  43723. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  43724. }
  43725. rc = sqlite3PagerWrite(pPage->pDbPage);
  43726. if( rc ) return rc;
  43727. rc = clearCell(pPage, pCell);
  43728. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  43729. if( rc ) return rc;
  43730. /* If the cell deleted was not located on a leaf page, then the cursor
  43731. ** is currently pointing to the largest entry in the sub-tree headed
  43732. ** by the child-page of the cell that was just deleted from an internal
  43733. ** node. The cell from the leaf node needs to be moved to the internal
  43734. ** node to replace the deleted cell. */
  43735. if( !pPage->leaf ){
  43736. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  43737. int nCell;
  43738. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  43739. unsigned char *pTmp;
  43740. pCell = findCell(pLeaf, pLeaf->nCell-1);
  43741. nCell = cellSizePtr(pLeaf, pCell);
  43742. assert( MX_CELL_SIZE(pBt) >= nCell );
  43743. allocateTempSpace(pBt);
  43744. pTmp = pBt->pTmpSpace;
  43745. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  43746. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  43747. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  43748. if( rc ) return rc;
  43749. }
  43750. /* Balance the tree. If the entry deleted was located on a leaf page,
  43751. ** then the cursor still points to that page. In this case the first
  43752. ** call to balance() repairs the tree, and the if(...) condition is
  43753. ** never true.
  43754. **
  43755. ** Otherwise, if the entry deleted was on an internal node page, then
  43756. ** pCur is pointing to the leaf page from which a cell was removed to
  43757. ** replace the cell deleted from the internal node. This is slightly
  43758. ** tricky as the leaf node may be underfull, and the internal node may
  43759. ** be either under or overfull. In this case run the balancing algorithm
  43760. ** on the leaf node first. If the balance proceeds far enough up the
  43761. ** tree that we can be sure that any problem in the internal node has
  43762. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  43763. ** walk the cursor up the tree to the internal node and balance it as
  43764. ** well. */
  43765. rc = balance(pCur);
  43766. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  43767. while( pCur->iPage>iCellDepth ){
  43768. releasePage(pCur->apPage[pCur->iPage--]);
  43769. }
  43770. rc = balance(pCur);
  43771. }
  43772. if( rc==SQLITE_OK ){
  43773. moveToRoot(pCur);
  43774. }
  43775. return rc;
  43776. }
  43777. /*
  43778. ** Create a new BTree table. Write into *piTable the page
  43779. ** number for the root page of the new table.
  43780. **
  43781. ** The type of type is determined by the flags parameter. Only the
  43782. ** following values of flags are currently in use. Other values for
  43783. ** flags might not work:
  43784. **
  43785. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  43786. ** BTREE_ZERODATA Used for SQL indices
  43787. */
  43788. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  43789. BtShared *pBt = p->pBt;
  43790. MemPage *pRoot;
  43791. Pgno pgnoRoot;
  43792. int rc;
  43793. int ptfFlags; /* Page-type flage for the root page of new table */
  43794. assert( sqlite3BtreeHoldsMutex(p) );
  43795. assert( pBt->inTransaction==TRANS_WRITE );
  43796. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  43797. #ifdef SQLITE_OMIT_AUTOVACUUM
  43798. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  43799. if( rc ){
  43800. return rc;
  43801. }
  43802. #else
  43803. if( pBt->autoVacuum ){
  43804. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  43805. MemPage *pPageMove; /* The page to move to. */
  43806. /* Creating a new table may probably require moving an existing database
  43807. ** to make room for the new tables root page. In case this page turns
  43808. ** out to be an overflow page, delete all overflow page-map caches
  43809. ** held by open cursors.
  43810. */
  43811. invalidateAllOverflowCache(pBt);
  43812. /* Read the value of meta[3] from the database to determine where the
  43813. ** root page of the new table should go. meta[3] is the largest root-page
  43814. ** created so far, so the new root-page is (meta[3]+1).
  43815. */
  43816. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  43817. pgnoRoot++;
  43818. /* The new root-page may not be allocated on a pointer-map page, or the
  43819. ** PENDING_BYTE page.
  43820. */
  43821. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  43822. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  43823. pgnoRoot++;
  43824. }
  43825. assert( pgnoRoot>=3 );
  43826. /* Allocate a page. The page that currently resides at pgnoRoot will
  43827. ** be moved to the allocated page (unless the allocated page happens
  43828. ** to reside at pgnoRoot).
  43829. */
  43830. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  43831. if( rc!=SQLITE_OK ){
  43832. return rc;
  43833. }
  43834. if( pgnoMove!=pgnoRoot ){
  43835. /* pgnoRoot is the page that will be used for the root-page of
  43836. ** the new table (assuming an error did not occur). But we were
  43837. ** allocated pgnoMove. If required (i.e. if it was not allocated
  43838. ** by extending the file), the current page at position pgnoMove
  43839. ** is already journaled.
  43840. */
  43841. u8 eType = 0;
  43842. Pgno iPtrPage = 0;
  43843. /* Save the positions of any open cursors. This is required in
  43844. ** case they are holding a reference to an xFetch reference
  43845. ** corresponding to page pgnoRoot. */
  43846. rc = saveAllCursors(pBt, 0, 0);
  43847. releasePage(pPageMove);
  43848. if( rc!=SQLITE_OK ){
  43849. return rc;
  43850. }
  43851. /* Move the page currently at pgnoRoot to pgnoMove. */
  43852. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  43853. if( rc!=SQLITE_OK ){
  43854. return rc;
  43855. }
  43856. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  43857. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  43858. rc = SQLITE_CORRUPT_BKPT;
  43859. }
  43860. if( rc!=SQLITE_OK ){
  43861. releasePage(pRoot);
  43862. return rc;
  43863. }
  43864. assert( eType!=PTRMAP_ROOTPAGE );
  43865. assert( eType!=PTRMAP_FREEPAGE );
  43866. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  43867. releasePage(pRoot);
  43868. /* Obtain the page at pgnoRoot */
  43869. if( rc!=SQLITE_OK ){
  43870. return rc;
  43871. }
  43872. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  43873. if( rc!=SQLITE_OK ){
  43874. return rc;
  43875. }
  43876. rc = sqlite3PagerWrite(pRoot->pDbPage);
  43877. if( rc!=SQLITE_OK ){
  43878. releasePage(pRoot);
  43879. return rc;
  43880. }
  43881. }else{
  43882. pRoot = pPageMove;
  43883. }
  43884. /* Update the pointer-map and meta-data with the new root-page number. */
  43885. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  43886. if( rc ){
  43887. releasePage(pRoot);
  43888. return rc;
  43889. }
  43890. /* When the new root page was allocated, page 1 was made writable in
  43891. ** order either to increase the database filesize, or to decrement the
  43892. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  43893. */
  43894. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  43895. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  43896. if( NEVER(rc) ){
  43897. releasePage(pRoot);
  43898. return rc;
  43899. }
  43900. }else{
  43901. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  43902. if( rc ) return rc;
  43903. }
  43904. #endif
  43905. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  43906. if( createTabFlags & BTREE_INTKEY ){
  43907. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  43908. }else{
  43909. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  43910. }
  43911. zeroPage(pRoot, ptfFlags);
  43912. sqlite3PagerUnref(pRoot->pDbPage);
  43913. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  43914. *piTable = (int)pgnoRoot;
  43915. return SQLITE_OK;
  43916. }
  43917. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  43918. int rc;
  43919. sqlite3BtreeEnter(p);
  43920. rc = btreeCreateTable(p, piTable, flags);
  43921. sqlite3BtreeLeave(p);
  43922. return rc;
  43923. }
  43924. /*
  43925. ** Erase the given database page and all its children. Return
  43926. ** the page to the freelist.
  43927. */
  43928. static int clearDatabasePage(
  43929. BtShared *pBt, /* The BTree that contains the table */
  43930. Pgno pgno, /* Page number to clear */
  43931. int freePageFlag, /* Deallocate page if true */
  43932. int *pnChange /* Add number of Cells freed to this counter */
  43933. ){
  43934. MemPage *pPage;
  43935. int rc;
  43936. unsigned char *pCell;
  43937. int i;
  43938. assert( sqlite3_mutex_held(pBt->mutex) );
  43939. if( pgno>btreePagecount(pBt) ){
  43940. return SQLITE_CORRUPT_BKPT;
  43941. }
  43942. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  43943. if( rc ) return rc;
  43944. for(i=0; i<pPage->nCell; i++){
  43945. pCell = findCell(pPage, i);
  43946. if( !pPage->leaf ){
  43947. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  43948. if( rc ) goto cleardatabasepage_out;
  43949. }
  43950. rc = clearCell(pPage, pCell);
  43951. if( rc ) goto cleardatabasepage_out;
  43952. }
  43953. if( !pPage->leaf ){
  43954. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  43955. if( rc ) goto cleardatabasepage_out;
  43956. }else if( pnChange ){
  43957. assert( pPage->intKey );
  43958. *pnChange += pPage->nCell;
  43959. }
  43960. if( freePageFlag ){
  43961. freePage(pPage, &rc);
  43962. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  43963. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  43964. }
  43965. cleardatabasepage_out:
  43966. releasePage(pPage);
  43967. return rc;
  43968. }
  43969. /*
  43970. ** Delete all information from a single table in the database. iTable is
  43971. ** the page number of the root of the table. After this routine returns,
  43972. ** the root page is empty, but still exists.
  43973. **
  43974. ** This routine will fail with SQLITE_LOCKED if there are any open
  43975. ** read cursors on the table. Open write cursors are moved to the
  43976. ** root of the table.
  43977. **
  43978. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  43979. ** integer value pointed to by pnChange is incremented by the number of
  43980. ** entries in the table.
  43981. */
  43982. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  43983. int rc;
  43984. BtShared *pBt = p->pBt;
  43985. sqlite3BtreeEnter(p);
  43986. assert( p->inTrans==TRANS_WRITE );
  43987. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  43988. if( SQLITE_OK==rc ){
  43989. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  43990. ** is the root of a table b-tree - if it is not, the following call is
  43991. ** a no-op). */
  43992. invalidateIncrblobCursors(p, 0, 1);
  43993. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  43994. }
  43995. sqlite3BtreeLeave(p);
  43996. return rc;
  43997. }
  43998. /*
  43999. ** Erase all information in a table and add the root of the table to
  44000. ** the freelist. Except, the root of the principle table (the one on
  44001. ** page 1) is never added to the freelist.
  44002. **
  44003. ** This routine will fail with SQLITE_LOCKED if there are any open
  44004. ** cursors on the table.
  44005. **
  44006. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  44007. ** root page in the database file, then the last root page
  44008. ** in the database file is moved into the slot formerly occupied by
  44009. ** iTable and that last slot formerly occupied by the last root page
  44010. ** is added to the freelist instead of iTable. In this say, all
  44011. ** root pages are kept at the beginning of the database file, which
  44012. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  44013. ** page number that used to be the last root page in the file before
  44014. ** the move. If no page gets moved, *piMoved is set to 0.
  44015. ** The last root page is recorded in meta[3] and the value of
  44016. ** meta[3] is updated by this procedure.
  44017. */
  44018. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  44019. int rc;
  44020. MemPage *pPage = 0;
  44021. BtShared *pBt = p->pBt;
  44022. assert( sqlite3BtreeHoldsMutex(p) );
  44023. assert( p->inTrans==TRANS_WRITE );
  44024. /* It is illegal to drop a table if any cursors are open on the
  44025. ** database. This is because in auto-vacuum mode the backend may
  44026. ** need to move another root-page to fill a gap left by the deleted
  44027. ** root page. If an open cursor was using this page a problem would
  44028. ** occur.
  44029. **
  44030. ** This error is caught long before control reaches this point.
  44031. */
  44032. if( NEVER(pBt->pCursor) ){
  44033. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  44034. return SQLITE_LOCKED_SHAREDCACHE;
  44035. }
  44036. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  44037. if( rc ) return rc;
  44038. rc = sqlite3BtreeClearTable(p, iTable, 0);
  44039. if( rc ){
  44040. releasePage(pPage);
  44041. return rc;
  44042. }
  44043. *piMoved = 0;
  44044. if( iTable>1 ){
  44045. #ifdef SQLITE_OMIT_AUTOVACUUM
  44046. freePage(pPage, &rc);
  44047. releasePage(pPage);
  44048. #else
  44049. if( pBt->autoVacuum ){
  44050. Pgno maxRootPgno;
  44051. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  44052. if( iTable==maxRootPgno ){
  44053. /* If the table being dropped is the table with the largest root-page
  44054. ** number in the database, put the root page on the free list.
  44055. */
  44056. freePage(pPage, &rc);
  44057. releasePage(pPage);
  44058. if( rc!=SQLITE_OK ){
  44059. return rc;
  44060. }
  44061. }else{
  44062. /* The table being dropped does not have the largest root-page
  44063. ** number in the database. So move the page that does into the
  44064. ** gap left by the deleted root-page.
  44065. */
  44066. MemPage *pMove;
  44067. releasePage(pPage);
  44068. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  44069. if( rc!=SQLITE_OK ){
  44070. return rc;
  44071. }
  44072. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  44073. releasePage(pMove);
  44074. if( rc!=SQLITE_OK ){
  44075. return rc;
  44076. }
  44077. pMove = 0;
  44078. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  44079. freePage(pMove, &rc);
  44080. releasePage(pMove);
  44081. if( rc!=SQLITE_OK ){
  44082. return rc;
  44083. }
  44084. *piMoved = maxRootPgno;
  44085. }
  44086. /* Set the new 'max-root-page' value in the database header. This
  44087. ** is the old value less one, less one more if that happens to
  44088. ** be a root-page number, less one again if that is the
  44089. ** PENDING_BYTE_PAGE.
  44090. */
  44091. maxRootPgno--;
  44092. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  44093. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  44094. maxRootPgno--;
  44095. }
  44096. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  44097. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  44098. }else{
  44099. freePage(pPage, &rc);
  44100. releasePage(pPage);
  44101. }
  44102. #endif
  44103. }else{
  44104. /* If sqlite3BtreeDropTable was called on page 1.
  44105. ** This really never should happen except in a corrupt
  44106. ** database.
  44107. */
  44108. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  44109. releasePage(pPage);
  44110. }
  44111. return rc;
  44112. }
  44113. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  44114. int rc;
  44115. sqlite3BtreeEnter(p);
  44116. rc = btreeDropTable(p, iTable, piMoved);
  44117. sqlite3BtreeLeave(p);
  44118. return rc;
  44119. }
  44120. /*
  44121. ** This function may only be called if the b-tree connection already
  44122. ** has a read or write transaction open on the database.
  44123. **
  44124. ** Read the meta-information out of a database file. Meta[0]
  44125. ** is the number of free pages currently in the database. Meta[1]
  44126. ** through meta[15] are available for use by higher layers. Meta[0]
  44127. ** is read-only, the others are read/write.
  44128. **
  44129. ** The schema layer numbers meta values differently. At the schema
  44130. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  44131. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  44132. */
  44133. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  44134. BtShared *pBt = p->pBt;
  44135. sqlite3BtreeEnter(p);
  44136. assert( p->inTrans>TRANS_NONE );
  44137. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  44138. assert( pBt->pPage1 );
  44139. assert( idx>=0 && idx<=15 );
  44140. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  44141. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  44142. ** database, mark the database as read-only. */
  44143. #ifdef SQLITE_OMIT_AUTOVACUUM
  44144. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  44145. pBt->btsFlags |= BTS_READ_ONLY;
  44146. }
  44147. #endif
  44148. sqlite3BtreeLeave(p);
  44149. }
  44150. /*
  44151. ** Write meta-information back into the database. Meta[0] is
  44152. ** read-only and may not be written.
  44153. */
  44154. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  44155. BtShared *pBt = p->pBt;
  44156. unsigned char *pP1;
  44157. int rc;
  44158. assert( idx>=1 && idx<=15 );
  44159. sqlite3BtreeEnter(p);
  44160. assert( p->inTrans==TRANS_WRITE );
  44161. assert( pBt->pPage1!=0 );
  44162. pP1 = pBt->pPage1->aData;
  44163. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  44164. if( rc==SQLITE_OK ){
  44165. put4byte(&pP1[36 + idx*4], iMeta);
  44166. #ifndef SQLITE_OMIT_AUTOVACUUM
  44167. if( idx==BTREE_INCR_VACUUM ){
  44168. assert( pBt->autoVacuum || iMeta==0 );
  44169. assert( iMeta==0 || iMeta==1 );
  44170. pBt->incrVacuum = (u8)iMeta;
  44171. }
  44172. #endif
  44173. }
  44174. sqlite3BtreeLeave(p);
  44175. return rc;
  44176. }
  44177. #ifndef SQLITE_OMIT_BTREECOUNT
  44178. /*
  44179. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  44180. ** number of entries in the b-tree and write the result to *pnEntry.
  44181. **
  44182. ** SQLITE_OK is returned if the operation is successfully executed.
  44183. ** Otherwise, if an error is encountered (i.e. an IO error or database
  44184. ** corruption) an SQLite error code is returned.
  44185. */
  44186. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  44187. i64 nEntry = 0; /* Value to return in *pnEntry */
  44188. int rc; /* Return code */
  44189. if( pCur->pgnoRoot==0 ){
  44190. *pnEntry = 0;
  44191. return SQLITE_OK;
  44192. }
  44193. rc = moveToRoot(pCur);
  44194. /* Unless an error occurs, the following loop runs one iteration for each
  44195. ** page in the B-Tree structure (not including overflow pages).
  44196. */
  44197. while( rc==SQLITE_OK ){
  44198. int iIdx; /* Index of child node in parent */
  44199. MemPage *pPage; /* Current page of the b-tree */
  44200. /* If this is a leaf page or the tree is not an int-key tree, then
  44201. ** this page contains countable entries. Increment the entry counter
  44202. ** accordingly.
  44203. */
  44204. pPage = pCur->apPage[pCur->iPage];
  44205. if( pPage->leaf || !pPage->intKey ){
  44206. nEntry += pPage->nCell;
  44207. }
  44208. /* pPage is a leaf node. This loop navigates the cursor so that it
  44209. ** points to the first interior cell that it points to the parent of
  44210. ** the next page in the tree that has not yet been visited. The
  44211. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  44212. ** of the page, or to the number of cells in the page if the next page
  44213. ** to visit is the right-child of its parent.
  44214. **
  44215. ** If all pages in the tree have been visited, return SQLITE_OK to the
  44216. ** caller.
  44217. */
  44218. if( pPage->leaf ){
  44219. do {
  44220. if( pCur->iPage==0 ){
  44221. /* All pages of the b-tree have been visited. Return successfully. */
  44222. *pnEntry = nEntry;
  44223. return SQLITE_OK;
  44224. }
  44225. moveToParent(pCur);
  44226. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  44227. pCur->aiIdx[pCur->iPage]++;
  44228. pPage = pCur->apPage[pCur->iPage];
  44229. }
  44230. /* Descend to the child node of the cell that the cursor currently
  44231. ** points at. This is the right-child if (iIdx==pPage->nCell).
  44232. */
  44233. iIdx = pCur->aiIdx[pCur->iPage];
  44234. if( iIdx==pPage->nCell ){
  44235. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  44236. }else{
  44237. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  44238. }
  44239. }
  44240. /* An error has occurred. Return an error code. */
  44241. return rc;
  44242. }
  44243. #endif
  44244. /*
  44245. ** Return the pager associated with a BTree. This routine is used for
  44246. ** testing and debugging only.
  44247. */
  44248. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  44249. return p->pBt->pPager;
  44250. }
  44251. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44252. /*
  44253. ** Append a message to the error message string.
  44254. */
  44255. static void checkAppendMsg(
  44256. IntegrityCk *pCheck,
  44257. char *zMsg1,
  44258. const char *zFormat,
  44259. ...
  44260. ){
  44261. va_list ap;
  44262. if( !pCheck->mxErr ) return;
  44263. pCheck->mxErr--;
  44264. pCheck->nErr++;
  44265. va_start(ap, zFormat);
  44266. if( pCheck->errMsg.nChar ){
  44267. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  44268. }
  44269. if( zMsg1 ){
  44270. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  44271. }
  44272. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  44273. va_end(ap);
  44274. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  44275. pCheck->mallocFailed = 1;
  44276. }
  44277. }
  44278. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44279. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44280. /*
  44281. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  44282. ** corresponds to page iPg is already set.
  44283. */
  44284. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  44285. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  44286. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  44287. }
  44288. /*
  44289. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  44290. */
  44291. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  44292. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  44293. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  44294. }
  44295. /*
  44296. ** Add 1 to the reference count for page iPage. If this is the second
  44297. ** reference to the page, add an error message to pCheck->zErrMsg.
  44298. ** Return 1 if there are 2 ore more references to the page and 0 if
  44299. ** if this is the first reference to the page.
  44300. **
  44301. ** Also check that the page number is in bounds.
  44302. */
  44303. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  44304. if( iPage==0 ) return 1;
  44305. if( iPage>pCheck->nPage ){
  44306. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  44307. return 1;
  44308. }
  44309. if( getPageReferenced(pCheck, iPage) ){
  44310. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  44311. return 1;
  44312. }
  44313. setPageReferenced(pCheck, iPage);
  44314. return 0;
  44315. }
  44316. #ifndef SQLITE_OMIT_AUTOVACUUM
  44317. /*
  44318. ** Check that the entry in the pointer-map for page iChild maps to
  44319. ** page iParent, pointer type ptrType. If not, append an error message
  44320. ** to pCheck.
  44321. */
  44322. static void checkPtrmap(
  44323. IntegrityCk *pCheck, /* Integrity check context */
  44324. Pgno iChild, /* Child page number */
  44325. u8 eType, /* Expected pointer map type */
  44326. Pgno iParent, /* Expected pointer map parent page number */
  44327. char *zContext /* Context description (used for error msg) */
  44328. ){
  44329. int rc;
  44330. u8 ePtrmapType;
  44331. Pgno iPtrmapParent;
  44332. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  44333. if( rc!=SQLITE_OK ){
  44334. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  44335. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  44336. return;
  44337. }
  44338. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  44339. checkAppendMsg(pCheck, zContext,
  44340. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  44341. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  44342. }
  44343. }
  44344. #endif
  44345. /*
  44346. ** Check the integrity of the freelist or of an overflow page list.
  44347. ** Verify that the number of pages on the list is N.
  44348. */
  44349. static void checkList(
  44350. IntegrityCk *pCheck, /* Integrity checking context */
  44351. int isFreeList, /* True for a freelist. False for overflow page list */
  44352. int iPage, /* Page number for first page in the list */
  44353. int N, /* Expected number of pages in the list */
  44354. char *zContext /* Context for error messages */
  44355. ){
  44356. int i;
  44357. int expected = N;
  44358. int iFirst = iPage;
  44359. while( N-- > 0 && pCheck->mxErr ){
  44360. DbPage *pOvflPage;
  44361. unsigned char *pOvflData;
  44362. if( iPage<1 ){
  44363. checkAppendMsg(pCheck, zContext,
  44364. "%d of %d pages missing from overflow list starting at %d",
  44365. N+1, expected, iFirst);
  44366. break;
  44367. }
  44368. if( checkRef(pCheck, iPage, zContext) ) break;
  44369. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  44370. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  44371. break;
  44372. }
  44373. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  44374. if( isFreeList ){
  44375. int n = get4byte(&pOvflData[4]);
  44376. #ifndef SQLITE_OMIT_AUTOVACUUM
  44377. if( pCheck->pBt->autoVacuum ){
  44378. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  44379. }
  44380. #endif
  44381. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  44382. checkAppendMsg(pCheck, zContext,
  44383. "freelist leaf count too big on page %d", iPage);
  44384. N--;
  44385. }else{
  44386. for(i=0; i<n; i++){
  44387. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  44388. #ifndef SQLITE_OMIT_AUTOVACUUM
  44389. if( pCheck->pBt->autoVacuum ){
  44390. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  44391. }
  44392. #endif
  44393. checkRef(pCheck, iFreePage, zContext);
  44394. }
  44395. N -= n;
  44396. }
  44397. }
  44398. #ifndef SQLITE_OMIT_AUTOVACUUM
  44399. else{
  44400. /* If this database supports auto-vacuum and iPage is not the last
  44401. ** page in this overflow list, check that the pointer-map entry for
  44402. ** the following page matches iPage.
  44403. */
  44404. if( pCheck->pBt->autoVacuum && N>0 ){
  44405. i = get4byte(pOvflData);
  44406. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  44407. }
  44408. }
  44409. #endif
  44410. iPage = get4byte(pOvflData);
  44411. sqlite3PagerUnref(pOvflPage);
  44412. }
  44413. }
  44414. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44415. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44416. /*
  44417. ** Do various sanity checks on a single page of a tree. Return
  44418. ** the tree depth. Root pages return 0. Parents of root pages
  44419. ** return 1, and so forth.
  44420. **
  44421. ** These checks are done:
  44422. **
  44423. ** 1. Make sure that cells and freeblocks do not overlap
  44424. ** but combine to completely cover the page.
  44425. ** NO 2. Make sure cell keys are in order.
  44426. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  44427. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  44428. ** 5. Check the integrity of overflow pages.
  44429. ** 6. Recursively call checkTreePage on all children.
  44430. ** 7. Verify that the depth of all children is the same.
  44431. ** 8. Make sure this page is at least 33% full or else it is
  44432. ** the root of the tree.
  44433. */
  44434. static int checkTreePage(
  44435. IntegrityCk *pCheck, /* Context for the sanity check */
  44436. int iPage, /* Page number of the page to check */
  44437. char *zParentContext, /* Parent context */
  44438. i64 *pnParentMinKey,
  44439. i64 *pnParentMaxKey
  44440. ){
  44441. MemPage *pPage;
  44442. int i, rc, depth, d2, pgno, cnt;
  44443. int hdr, cellStart;
  44444. int nCell;
  44445. u8 *data;
  44446. BtShared *pBt;
  44447. int usableSize;
  44448. char zContext[100];
  44449. char *hit = 0;
  44450. i64 nMinKey = 0;
  44451. i64 nMaxKey = 0;
  44452. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  44453. /* Check that the page exists
  44454. */
  44455. pBt = pCheck->pBt;
  44456. usableSize = pBt->usableSize;
  44457. if( iPage==0 ) return 0;
  44458. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  44459. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  44460. checkAppendMsg(pCheck, zContext,
  44461. "unable to get the page. error code=%d", rc);
  44462. return 0;
  44463. }
  44464. /* Clear MemPage.isInit to make sure the corruption detection code in
  44465. ** btreeInitPage() is executed. */
  44466. pPage->isInit = 0;
  44467. if( (rc = btreeInitPage(pPage))!=0 ){
  44468. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  44469. checkAppendMsg(pCheck, zContext,
  44470. "btreeInitPage() returns error code %d", rc);
  44471. releasePage(pPage);
  44472. return 0;
  44473. }
  44474. /* Check out all the cells.
  44475. */
  44476. depth = 0;
  44477. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  44478. u8 *pCell;
  44479. u32 sz;
  44480. CellInfo info;
  44481. /* Check payload overflow pages
  44482. */
  44483. sqlite3_snprintf(sizeof(zContext), zContext,
  44484. "On tree page %d cell %d: ", iPage, i);
  44485. pCell = findCell(pPage,i);
  44486. btreeParseCellPtr(pPage, pCell, &info);
  44487. sz = info.nData;
  44488. if( !pPage->intKey ) sz += (int)info.nKey;
  44489. /* For intKey pages, check that the keys are in order.
  44490. */
  44491. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  44492. else{
  44493. if( info.nKey <= nMaxKey ){
  44494. checkAppendMsg(pCheck, zContext,
  44495. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  44496. }
  44497. nMaxKey = info.nKey;
  44498. }
  44499. assert( sz==info.nPayload );
  44500. if( (sz>info.nLocal)
  44501. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  44502. ){
  44503. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  44504. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  44505. #ifndef SQLITE_OMIT_AUTOVACUUM
  44506. if( pBt->autoVacuum ){
  44507. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  44508. }
  44509. #endif
  44510. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  44511. }
  44512. /* Check sanity of left child page.
  44513. */
  44514. if( !pPage->leaf ){
  44515. pgno = get4byte(pCell);
  44516. #ifndef SQLITE_OMIT_AUTOVACUUM
  44517. if( pBt->autoVacuum ){
  44518. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  44519. }
  44520. #endif
  44521. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  44522. if( i>0 && d2!=depth ){
  44523. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  44524. }
  44525. depth = d2;
  44526. }
  44527. }
  44528. if( !pPage->leaf ){
  44529. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  44530. sqlite3_snprintf(sizeof(zContext), zContext,
  44531. "On page %d at right child: ", iPage);
  44532. #ifndef SQLITE_OMIT_AUTOVACUUM
  44533. if( pBt->autoVacuum ){
  44534. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  44535. }
  44536. #endif
  44537. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  44538. }
  44539. /* For intKey leaf pages, check that the min/max keys are in order
  44540. ** with any left/parent/right pages.
  44541. */
  44542. if( pPage->leaf && pPage->intKey ){
  44543. /* if we are a left child page */
  44544. if( pnParentMinKey ){
  44545. /* if we are the left most child page */
  44546. if( !pnParentMaxKey ){
  44547. if( nMaxKey > *pnParentMinKey ){
  44548. checkAppendMsg(pCheck, zContext,
  44549. "Rowid %lld out of order (max larger than parent min of %lld)",
  44550. nMaxKey, *pnParentMinKey);
  44551. }
  44552. }else{
  44553. if( nMinKey <= *pnParentMinKey ){
  44554. checkAppendMsg(pCheck, zContext,
  44555. "Rowid %lld out of order (min less than parent min of %lld)",
  44556. nMinKey, *pnParentMinKey);
  44557. }
  44558. if( nMaxKey > *pnParentMaxKey ){
  44559. checkAppendMsg(pCheck, zContext,
  44560. "Rowid %lld out of order (max larger than parent max of %lld)",
  44561. nMaxKey, *pnParentMaxKey);
  44562. }
  44563. *pnParentMinKey = nMaxKey;
  44564. }
  44565. /* else if we're a right child page */
  44566. } else if( pnParentMaxKey ){
  44567. if( nMinKey <= *pnParentMaxKey ){
  44568. checkAppendMsg(pCheck, zContext,
  44569. "Rowid %lld out of order (min less than parent max of %lld)",
  44570. nMinKey, *pnParentMaxKey);
  44571. }
  44572. }
  44573. }
  44574. /* Check for complete coverage of the page
  44575. */
  44576. data = pPage->aData;
  44577. hdr = pPage->hdrOffset;
  44578. hit = sqlite3PageMalloc( pBt->pageSize );
  44579. if( hit==0 ){
  44580. pCheck->mallocFailed = 1;
  44581. }else{
  44582. int contentOffset = get2byteNotZero(&data[hdr+5]);
  44583. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  44584. memset(hit+contentOffset, 0, usableSize-contentOffset);
  44585. memset(hit, 1, contentOffset);
  44586. nCell = get2byte(&data[hdr+3]);
  44587. cellStart = hdr + 12 - 4*pPage->leaf;
  44588. for(i=0; i<nCell; i++){
  44589. int pc = get2byte(&data[cellStart+i*2]);
  44590. u32 size = 65536;
  44591. int j;
  44592. if( pc<=usableSize-4 ){
  44593. size = cellSizePtr(pPage, &data[pc]);
  44594. }
  44595. if( (int)(pc+size-1)>=usableSize ){
  44596. checkAppendMsg(pCheck, 0,
  44597. "Corruption detected in cell %d on page %d",i,iPage);
  44598. }else{
  44599. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  44600. }
  44601. }
  44602. i = get2byte(&data[hdr+1]);
  44603. while( i>0 ){
  44604. int size, j;
  44605. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  44606. size = get2byte(&data[i+2]);
  44607. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  44608. for(j=i+size-1; j>=i; j--) hit[j]++;
  44609. j = get2byte(&data[i]);
  44610. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  44611. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  44612. i = j;
  44613. }
  44614. for(i=cnt=0; i<usableSize; i++){
  44615. if( hit[i]==0 ){
  44616. cnt++;
  44617. }else if( hit[i]>1 ){
  44618. checkAppendMsg(pCheck, 0,
  44619. "Multiple uses for byte %d of page %d", i, iPage);
  44620. break;
  44621. }
  44622. }
  44623. if( cnt!=data[hdr+7] ){
  44624. checkAppendMsg(pCheck, 0,
  44625. "Fragmentation of %d bytes reported as %d on page %d",
  44626. cnt, data[hdr+7], iPage);
  44627. }
  44628. }
  44629. sqlite3PageFree(hit);
  44630. releasePage(pPage);
  44631. return depth+1;
  44632. }
  44633. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44634. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  44635. /*
  44636. ** This routine does a complete check of the given BTree file. aRoot[] is
  44637. ** an array of pages numbers were each page number is the root page of
  44638. ** a table. nRoot is the number of entries in aRoot.
  44639. **
  44640. ** A read-only or read-write transaction must be opened before calling
  44641. ** this function.
  44642. **
  44643. ** Write the number of error seen in *pnErr. Except for some memory
  44644. ** allocation errors, an error message held in memory obtained from
  44645. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  44646. ** returned. If a memory allocation error occurs, NULL is returned.
  44647. */
  44648. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  44649. Btree *p, /* The btree to be checked */
  44650. int *aRoot, /* An array of root pages numbers for individual trees */
  44651. int nRoot, /* Number of entries in aRoot[] */
  44652. int mxErr, /* Stop reporting errors after this many */
  44653. int *pnErr /* Write number of errors seen to this variable */
  44654. ){
  44655. Pgno i;
  44656. int nRef;
  44657. IntegrityCk sCheck;
  44658. BtShared *pBt = p->pBt;
  44659. char zErr[100];
  44660. sqlite3BtreeEnter(p);
  44661. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  44662. nRef = sqlite3PagerRefcount(pBt->pPager);
  44663. sCheck.pBt = pBt;
  44664. sCheck.pPager = pBt->pPager;
  44665. sCheck.nPage = btreePagecount(sCheck.pBt);
  44666. sCheck.mxErr = mxErr;
  44667. sCheck.nErr = 0;
  44668. sCheck.mallocFailed = 0;
  44669. *pnErr = 0;
  44670. if( sCheck.nPage==0 ){
  44671. sqlite3BtreeLeave(p);
  44672. return 0;
  44673. }
  44674. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  44675. if( !sCheck.aPgRef ){
  44676. *pnErr = 1;
  44677. sqlite3BtreeLeave(p);
  44678. return 0;
  44679. }
  44680. i = PENDING_BYTE_PAGE(pBt);
  44681. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  44682. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  44683. sCheck.errMsg.useMalloc = 2;
  44684. /* Check the integrity of the freelist
  44685. */
  44686. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  44687. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  44688. /* Check all the tables.
  44689. */
  44690. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  44691. if( aRoot[i]==0 ) continue;
  44692. #ifndef SQLITE_OMIT_AUTOVACUUM
  44693. if( pBt->autoVacuum && aRoot[i]>1 ){
  44694. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  44695. }
  44696. #endif
  44697. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  44698. }
  44699. /* Make sure every page in the file is referenced
  44700. */
  44701. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  44702. #ifdef SQLITE_OMIT_AUTOVACUUM
  44703. if( getPageReferenced(&sCheck, i)==0 ){
  44704. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  44705. }
  44706. #else
  44707. /* If the database supports auto-vacuum, make sure no tables contain
  44708. ** references to pointer-map pages.
  44709. */
  44710. if( getPageReferenced(&sCheck, i)==0 &&
  44711. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  44712. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  44713. }
  44714. if( getPageReferenced(&sCheck, i)!=0 &&
  44715. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  44716. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  44717. }
  44718. #endif
  44719. }
  44720. /* Make sure this analysis did not leave any unref() pages.
  44721. ** This is an internal consistency check; an integrity check
  44722. ** of the integrity check.
  44723. */
  44724. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  44725. checkAppendMsg(&sCheck, 0,
  44726. "Outstanding page count goes from %d to %d during this analysis",
  44727. nRef, sqlite3PagerRefcount(pBt->pPager)
  44728. );
  44729. }
  44730. /* Clean up and report errors.
  44731. */
  44732. sqlite3BtreeLeave(p);
  44733. sqlite3_free(sCheck.aPgRef);
  44734. if( sCheck.mallocFailed ){
  44735. sqlite3StrAccumReset(&sCheck.errMsg);
  44736. *pnErr = sCheck.nErr+1;
  44737. return 0;
  44738. }
  44739. *pnErr = sCheck.nErr;
  44740. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  44741. return sqlite3StrAccumFinish(&sCheck.errMsg);
  44742. }
  44743. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  44744. /*
  44745. ** Return the full pathname of the underlying database file. Return
  44746. ** an empty string if the database is in-memory or a TEMP database.
  44747. **
  44748. ** The pager filename is invariant as long as the pager is
  44749. ** open so it is safe to access without the BtShared mutex.
  44750. */
  44751. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  44752. assert( p->pBt->pPager!=0 );
  44753. return sqlite3PagerFilename(p->pBt->pPager, 1);
  44754. }
  44755. /*
  44756. ** Return the pathname of the journal file for this database. The return
  44757. ** value of this routine is the same regardless of whether the journal file
  44758. ** has been created or not.
  44759. **
  44760. ** The pager journal filename is invariant as long as the pager is
  44761. ** open so it is safe to access without the BtShared mutex.
  44762. */
  44763. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  44764. assert( p->pBt->pPager!=0 );
  44765. return sqlite3PagerJournalname(p->pBt->pPager);
  44766. }
  44767. /*
  44768. ** Return non-zero if a transaction is active.
  44769. */
  44770. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  44771. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  44772. return (p && (p->inTrans==TRANS_WRITE));
  44773. }
  44774. #ifndef SQLITE_OMIT_WAL
  44775. /*
  44776. ** Run a checkpoint on the Btree passed as the first argument.
  44777. **
  44778. ** Return SQLITE_LOCKED if this or any other connection has an open
  44779. ** transaction on the shared-cache the argument Btree is connected to.
  44780. **
  44781. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  44782. */
  44783. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  44784. int rc = SQLITE_OK;
  44785. if( p ){
  44786. BtShared *pBt = p->pBt;
  44787. sqlite3BtreeEnter(p);
  44788. if( pBt->inTransaction!=TRANS_NONE ){
  44789. rc = SQLITE_LOCKED;
  44790. }else{
  44791. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  44792. }
  44793. sqlite3BtreeLeave(p);
  44794. }
  44795. return rc;
  44796. }
  44797. #endif
  44798. /*
  44799. ** Return non-zero if a read (or write) transaction is active.
  44800. */
  44801. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  44802. assert( p );
  44803. assert( sqlite3_mutex_held(p->db->mutex) );
  44804. return p->inTrans!=TRANS_NONE;
  44805. }
  44806. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  44807. assert( p );
  44808. assert( sqlite3_mutex_held(p->db->mutex) );
  44809. return p->nBackup!=0;
  44810. }
  44811. /*
  44812. ** This function returns a pointer to a blob of memory associated with
  44813. ** a single shared-btree. The memory is used by client code for its own
  44814. ** purposes (for example, to store a high-level schema associated with
  44815. ** the shared-btree). The btree layer manages reference counting issues.
  44816. **
  44817. ** The first time this is called on a shared-btree, nBytes bytes of memory
  44818. ** are allocated, zeroed, and returned to the caller. For each subsequent
  44819. ** call the nBytes parameter is ignored and a pointer to the same blob
  44820. ** of memory returned.
  44821. **
  44822. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  44823. ** allocated, a null pointer is returned. If the blob has already been
  44824. ** allocated, it is returned as normal.
  44825. **
  44826. ** Just before the shared-btree is closed, the function passed as the
  44827. ** xFree argument when the memory allocation was made is invoked on the
  44828. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  44829. ** on the memory, the btree layer does that.
  44830. */
  44831. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  44832. BtShared *pBt = p->pBt;
  44833. sqlite3BtreeEnter(p);
  44834. if( !pBt->pSchema && nBytes ){
  44835. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  44836. pBt->xFreeSchema = xFree;
  44837. }
  44838. sqlite3BtreeLeave(p);
  44839. return pBt->pSchema;
  44840. }
  44841. /*
  44842. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  44843. ** btree as the argument handle holds an exclusive lock on the
  44844. ** sqlite_master table. Otherwise SQLITE_OK.
  44845. */
  44846. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  44847. int rc;
  44848. assert( sqlite3_mutex_held(p->db->mutex) );
  44849. sqlite3BtreeEnter(p);
  44850. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  44851. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  44852. sqlite3BtreeLeave(p);
  44853. return rc;
  44854. }
  44855. #ifndef SQLITE_OMIT_SHARED_CACHE
  44856. /*
  44857. ** Obtain a lock on the table whose root page is iTab. The
  44858. ** lock is a write lock if isWritelock is true or a read lock
  44859. ** if it is false.
  44860. */
  44861. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  44862. int rc = SQLITE_OK;
  44863. assert( p->inTrans!=TRANS_NONE );
  44864. if( p->sharable ){
  44865. u8 lockType = READ_LOCK + isWriteLock;
  44866. assert( READ_LOCK+1==WRITE_LOCK );
  44867. assert( isWriteLock==0 || isWriteLock==1 );
  44868. sqlite3BtreeEnter(p);
  44869. rc = querySharedCacheTableLock(p, iTab, lockType);
  44870. if( rc==SQLITE_OK ){
  44871. rc = setSharedCacheTableLock(p, iTab, lockType);
  44872. }
  44873. sqlite3BtreeLeave(p);
  44874. }
  44875. return rc;
  44876. }
  44877. #endif
  44878. #ifndef SQLITE_OMIT_INCRBLOB
  44879. /*
  44880. ** Argument pCsr must be a cursor opened for writing on an
  44881. ** INTKEY table currently pointing at a valid table entry.
  44882. ** This function modifies the data stored as part of that entry.
  44883. **
  44884. ** Only the data content may only be modified, it is not possible to
  44885. ** change the length of the data stored. If this function is called with
  44886. ** parameters that attempt to write past the end of the existing data,
  44887. ** no modifications are made and SQLITE_CORRUPT is returned.
  44888. */
  44889. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  44890. int rc;
  44891. assert( cursorHoldsMutex(pCsr) );
  44892. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  44893. assert( pCsr->isIncrblobHandle );
  44894. rc = restoreCursorPosition(pCsr);
  44895. if( rc!=SQLITE_OK ){
  44896. return rc;
  44897. }
  44898. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  44899. if( pCsr->eState!=CURSOR_VALID ){
  44900. return SQLITE_ABORT;
  44901. }
  44902. /* Save the positions of all other cursors open on this table. This is
  44903. ** required in case any of them are holding references to an xFetch
  44904. ** version of the b-tree page modified by the accessPayload call below.
  44905. **
  44906. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  44907. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  44908. ** saveAllCursors can only return SQLITE_OK.
  44909. */
  44910. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  44911. assert( rc==SQLITE_OK );
  44912. /* Check some assumptions:
  44913. ** (a) the cursor is open for writing,
  44914. ** (b) there is a read/write transaction open,
  44915. ** (c) the connection holds a write-lock on the table (if required),
  44916. ** (d) there are no conflicting read-locks, and
  44917. ** (e) the cursor points at a valid row of an intKey table.
  44918. */
  44919. if( !pCsr->wrFlag ){
  44920. return SQLITE_READONLY;
  44921. }
  44922. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  44923. && pCsr->pBt->inTransaction==TRANS_WRITE );
  44924. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  44925. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  44926. assert( pCsr->apPage[pCsr->iPage]->intKey );
  44927. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  44928. }
  44929. /*
  44930. ** Set a flag on this cursor to cache the locations of pages from the
  44931. ** overflow list for the current row. This is used by cursors opened
  44932. ** for incremental blob IO only.
  44933. **
  44934. ** This function sets a flag only. The actual page location cache
  44935. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  44936. ** accessPayload() (the worker function for sqlite3BtreeData() and
  44937. ** sqlite3BtreePutData()).
  44938. */
  44939. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  44940. assert( cursorHoldsMutex(pCur) );
  44941. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  44942. invalidateOverflowCache(pCur);
  44943. pCur->isIncrblobHandle = 1;
  44944. }
  44945. #endif
  44946. /*
  44947. ** Set both the "read version" (single byte at byte offset 18) and
  44948. ** "write version" (single byte at byte offset 19) fields in the database
  44949. ** header to iVersion.
  44950. */
  44951. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  44952. BtShared *pBt = pBtree->pBt;
  44953. int rc; /* Return code */
  44954. assert( iVersion==1 || iVersion==2 );
  44955. /* If setting the version fields to 1, do not automatically open the
  44956. ** WAL connection, even if the version fields are currently set to 2.
  44957. */
  44958. pBt->btsFlags &= ~BTS_NO_WAL;
  44959. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  44960. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  44961. if( rc==SQLITE_OK ){
  44962. u8 *aData = pBt->pPage1->aData;
  44963. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  44964. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  44965. if( rc==SQLITE_OK ){
  44966. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  44967. if( rc==SQLITE_OK ){
  44968. aData[18] = (u8)iVersion;
  44969. aData[19] = (u8)iVersion;
  44970. }
  44971. }
  44972. }
  44973. }
  44974. pBt->btsFlags &= ~BTS_NO_WAL;
  44975. return rc;
  44976. }
  44977. /*
  44978. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  44979. ** values are 0 and BTREE_BULKLOAD.
  44980. */
  44981. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  44982. assert( mask==BTREE_BULKLOAD || mask==0 );
  44983. pCsr->hints = mask;
  44984. }
  44985. /************** End of btree.c ***********************************************/
  44986. /************** Begin file backup.c ******************************************/
  44987. /*
  44988. ** 2009 January 28
  44989. **
  44990. ** The author disclaims copyright to this source code. In place of
  44991. ** a legal notice, here is a blessing:
  44992. **
  44993. ** May you do good and not evil.
  44994. ** May you find forgiveness for yourself and forgive others.
  44995. ** May you share freely, never taking more than you give.
  44996. **
  44997. *************************************************************************
  44998. ** This file contains the implementation of the sqlite3_backup_XXX()
  44999. ** API functions and the related features.
  45000. */
  45001. /*
  45002. ** Structure allocated for each backup operation.
  45003. */
  45004. struct sqlite3_backup {
  45005. sqlite3* pDestDb; /* Destination database handle */
  45006. Btree *pDest; /* Destination b-tree file */
  45007. u32 iDestSchema; /* Original schema cookie in destination */
  45008. int bDestLocked; /* True once a write-transaction is open on pDest */
  45009. Pgno iNext; /* Page number of the next source page to copy */
  45010. sqlite3* pSrcDb; /* Source database handle */
  45011. Btree *pSrc; /* Source b-tree file */
  45012. int rc; /* Backup process error code */
  45013. /* These two variables are set by every call to backup_step(). They are
  45014. ** read by calls to backup_remaining() and backup_pagecount().
  45015. */
  45016. Pgno nRemaining; /* Number of pages left to copy */
  45017. Pgno nPagecount; /* Total number of pages to copy */
  45018. int isAttached; /* True once backup has been registered with pager */
  45019. sqlite3_backup *pNext; /* Next backup associated with source pager */
  45020. };
  45021. /*
  45022. ** THREAD SAFETY NOTES:
  45023. **
  45024. ** Once it has been created using backup_init(), a single sqlite3_backup
  45025. ** structure may be accessed via two groups of thread-safe entry points:
  45026. **
  45027. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  45028. ** backup_finish(). Both these functions obtain the source database
  45029. ** handle mutex and the mutex associated with the source BtShared
  45030. ** structure, in that order.
  45031. **
  45032. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  45033. ** invoked by the pager layer to report various state changes in
  45034. ** the page cache associated with the source database. The mutex
  45035. ** associated with the source database BtShared structure will always
  45036. ** be held when either of these functions are invoked.
  45037. **
  45038. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  45039. ** backup_pagecount() are not thread-safe functions. If they are called
  45040. ** while some other thread is calling backup_step() or backup_finish(),
  45041. ** the values returned may be invalid. There is no way for a call to
  45042. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  45043. ** or backup_pagecount().
  45044. **
  45045. ** Depending on the SQLite configuration, the database handles and/or
  45046. ** the Btree objects may have their own mutexes that require locking.
  45047. ** Non-sharable Btrees (in-memory databases for example), do not have
  45048. ** associated mutexes.
  45049. */
  45050. /*
  45051. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  45052. ** in connection handle pDb. If such a database cannot be found, return
  45053. ** a NULL pointer and write an error message to pErrorDb.
  45054. **
  45055. ** If the "temp" database is requested, it may need to be opened by this
  45056. ** function. If an error occurs while doing so, return 0 and write an
  45057. ** error message to pErrorDb.
  45058. */
  45059. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  45060. int i = sqlite3FindDbName(pDb, zDb);
  45061. if( i==1 ){
  45062. Parse *pParse;
  45063. int rc = 0;
  45064. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  45065. if( pParse==0 ){
  45066. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  45067. rc = SQLITE_NOMEM;
  45068. }else{
  45069. pParse->db = pDb;
  45070. if( sqlite3OpenTempDatabase(pParse) ){
  45071. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  45072. rc = SQLITE_ERROR;
  45073. }
  45074. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  45075. sqlite3StackFree(pErrorDb, pParse);
  45076. }
  45077. if( rc ){
  45078. return 0;
  45079. }
  45080. }
  45081. if( i<0 ){
  45082. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  45083. return 0;
  45084. }
  45085. return pDb->aDb[i].pBt;
  45086. }
  45087. /*
  45088. ** Attempt to set the page size of the destination to match the page size
  45089. ** of the source.
  45090. */
  45091. static int setDestPgsz(sqlite3_backup *p){
  45092. int rc;
  45093. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  45094. return rc;
  45095. }
  45096. /*
  45097. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  45098. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  45099. ** a pointer to the new sqlite3_backup object.
  45100. **
  45101. ** If an error occurs, NULL is returned and an error code and error message
  45102. ** stored in database handle pDestDb.
  45103. */
  45104. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  45105. sqlite3* pDestDb, /* Database to write to */
  45106. const char *zDestDb, /* Name of database within pDestDb */
  45107. sqlite3* pSrcDb, /* Database connection to read from */
  45108. const char *zSrcDb /* Name of database within pSrcDb */
  45109. ){
  45110. sqlite3_backup *p; /* Value to return */
  45111. /* Lock the source database handle. The destination database
  45112. ** handle is not locked in this routine, but it is locked in
  45113. ** sqlite3_backup_step(). The user is required to ensure that no
  45114. ** other thread accesses the destination handle for the duration
  45115. ** of the backup operation. Any attempt to use the destination
  45116. ** database connection while a backup is in progress may cause
  45117. ** a malfunction or a deadlock.
  45118. */
  45119. sqlite3_mutex_enter(pSrcDb->mutex);
  45120. sqlite3_mutex_enter(pDestDb->mutex);
  45121. if( pSrcDb==pDestDb ){
  45122. sqlite3Error(
  45123. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  45124. );
  45125. p = 0;
  45126. }else {
  45127. /* Allocate space for a new sqlite3_backup object...
  45128. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  45129. ** call to sqlite3_backup_init() and is destroyed by a call to
  45130. ** sqlite3_backup_finish(). */
  45131. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  45132. if( !p ){
  45133. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  45134. }
  45135. }
  45136. /* If the allocation succeeded, populate the new object. */
  45137. if( p ){
  45138. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  45139. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  45140. p->pDestDb = pDestDb;
  45141. p->pSrcDb = pSrcDb;
  45142. p->iNext = 1;
  45143. p->isAttached = 0;
  45144. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  45145. /* One (or both) of the named databases did not exist or an OOM
  45146. ** error was hit. The error has already been written into the
  45147. ** pDestDb handle. All that is left to do here is free the
  45148. ** sqlite3_backup structure.
  45149. */
  45150. sqlite3_free(p);
  45151. p = 0;
  45152. }
  45153. }
  45154. if( p ){
  45155. p->pSrc->nBackup++;
  45156. }
  45157. sqlite3_mutex_leave(pDestDb->mutex);
  45158. sqlite3_mutex_leave(pSrcDb->mutex);
  45159. return p;
  45160. }
  45161. /*
  45162. ** Argument rc is an SQLite error code. Return true if this error is
  45163. ** considered fatal if encountered during a backup operation. All errors
  45164. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  45165. */
  45166. static int isFatalError(int rc){
  45167. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  45168. }
  45169. /*
  45170. ** Parameter zSrcData points to a buffer containing the data for
  45171. ** page iSrcPg from the source database. Copy this data into the
  45172. ** destination database.
  45173. */
  45174. static int backupOnePage(
  45175. sqlite3_backup *p, /* Backup handle */
  45176. Pgno iSrcPg, /* Source database page to backup */
  45177. const u8 *zSrcData, /* Source database page data */
  45178. int bUpdate /* True for an update, false otherwise */
  45179. ){
  45180. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  45181. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  45182. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  45183. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  45184. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  45185. #ifdef SQLITE_HAS_CODEC
  45186. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  45187. ** guaranteed that the shared-mutex is held by this thread, handle
  45188. ** p->pSrc may not actually be the owner. */
  45189. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  45190. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  45191. #endif
  45192. int rc = SQLITE_OK;
  45193. i64 iOff;
  45194. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  45195. assert( p->bDestLocked );
  45196. assert( !isFatalError(p->rc) );
  45197. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  45198. assert( zSrcData );
  45199. /* Catch the case where the destination is an in-memory database and the
  45200. ** page sizes of the source and destination differ.
  45201. */
  45202. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  45203. rc = SQLITE_READONLY;
  45204. }
  45205. #ifdef SQLITE_HAS_CODEC
  45206. /* Backup is not possible if the page size of the destination is changing
  45207. ** and a codec is in use.
  45208. */
  45209. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  45210. rc = SQLITE_READONLY;
  45211. }
  45212. /* Backup is not possible if the number of bytes of reserve space differ
  45213. ** between source and destination. If there is a difference, try to
  45214. ** fix the destination to agree with the source. If that is not possible,
  45215. ** then the backup cannot proceed.
  45216. */
  45217. if( nSrcReserve!=nDestReserve ){
  45218. u32 newPgsz = nSrcPgsz;
  45219. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  45220. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  45221. }
  45222. #endif
  45223. /* This loop runs once for each destination page spanned by the source
  45224. ** page. For each iteration, variable iOff is set to the byte offset
  45225. ** of the destination page.
  45226. */
  45227. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  45228. DbPage *pDestPg = 0;
  45229. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  45230. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  45231. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  45232. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  45233. ){
  45234. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  45235. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  45236. u8 *zOut = &zDestData[iOff%nDestPgsz];
  45237. /* Copy the data from the source page into the destination page.
  45238. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  45239. ** and the pager code use this trick (clearing the first byte
  45240. ** of the page 'extra' space to invalidate the Btree layers
  45241. ** cached parse of the page). MemPage.isInit is marked
  45242. ** "MUST BE FIRST" for this purpose.
  45243. */
  45244. memcpy(zOut, zIn, nCopy);
  45245. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  45246. if( iOff==0 && bUpdate==0 ){
  45247. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  45248. }
  45249. }
  45250. sqlite3PagerUnref(pDestPg);
  45251. }
  45252. return rc;
  45253. }
  45254. /*
  45255. ** If pFile is currently larger than iSize bytes, then truncate it to
  45256. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  45257. ** this function is a no-op.
  45258. **
  45259. ** Return SQLITE_OK if everything is successful, or an SQLite error
  45260. ** code if an error occurs.
  45261. */
  45262. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  45263. i64 iCurrent;
  45264. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  45265. if( rc==SQLITE_OK && iCurrent>iSize ){
  45266. rc = sqlite3OsTruncate(pFile, iSize);
  45267. }
  45268. return rc;
  45269. }
  45270. /*
  45271. ** Register this backup object with the associated source pager for
  45272. ** callbacks when pages are changed or the cache invalidated.
  45273. */
  45274. static void attachBackupObject(sqlite3_backup *p){
  45275. sqlite3_backup **pp;
  45276. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  45277. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  45278. p->pNext = *pp;
  45279. *pp = p;
  45280. p->isAttached = 1;
  45281. }
  45282. /*
  45283. ** Copy nPage pages from the source b-tree to the destination.
  45284. */
  45285. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  45286. int rc;
  45287. int destMode; /* Destination journal mode */
  45288. int pgszSrc = 0; /* Source page size */
  45289. int pgszDest = 0; /* Destination page size */
  45290. sqlite3_mutex_enter(p->pSrcDb->mutex);
  45291. sqlite3BtreeEnter(p->pSrc);
  45292. if( p->pDestDb ){
  45293. sqlite3_mutex_enter(p->pDestDb->mutex);
  45294. }
  45295. rc = p->rc;
  45296. if( !isFatalError(rc) ){
  45297. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  45298. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  45299. int ii; /* Iterator variable */
  45300. int nSrcPage = -1; /* Size of source db in pages */
  45301. int bCloseTrans = 0; /* True if src db requires unlocking */
  45302. /* If the source pager is currently in a write-transaction, return
  45303. ** SQLITE_BUSY immediately.
  45304. */
  45305. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  45306. rc = SQLITE_BUSY;
  45307. }else{
  45308. rc = SQLITE_OK;
  45309. }
  45310. /* Lock the destination database, if it is not locked already. */
  45311. if( SQLITE_OK==rc && p->bDestLocked==0
  45312. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  45313. ){
  45314. p->bDestLocked = 1;
  45315. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  45316. }
  45317. /* If there is no open read-transaction on the source database, open
  45318. ** one now. If a transaction is opened here, then it will be closed
  45319. ** before this function exits.
  45320. */
  45321. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  45322. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  45323. bCloseTrans = 1;
  45324. }
  45325. /* Do not allow backup if the destination database is in WAL mode
  45326. ** and the page sizes are different between source and destination */
  45327. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  45328. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  45329. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  45330. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  45331. rc = SQLITE_READONLY;
  45332. }
  45333. /* Now that there is a read-lock on the source database, query the
  45334. ** source pager for the number of pages in the database.
  45335. */
  45336. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  45337. assert( nSrcPage>=0 );
  45338. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  45339. const Pgno iSrcPg = p->iNext; /* Source page number */
  45340. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  45341. DbPage *pSrcPg; /* Source page object */
  45342. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  45343. PAGER_GET_READONLY);
  45344. if( rc==SQLITE_OK ){
  45345. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  45346. sqlite3PagerUnref(pSrcPg);
  45347. }
  45348. }
  45349. p->iNext++;
  45350. }
  45351. if( rc==SQLITE_OK ){
  45352. p->nPagecount = nSrcPage;
  45353. p->nRemaining = nSrcPage+1-p->iNext;
  45354. if( p->iNext>(Pgno)nSrcPage ){
  45355. rc = SQLITE_DONE;
  45356. }else if( !p->isAttached ){
  45357. attachBackupObject(p);
  45358. }
  45359. }
  45360. /* Update the schema version field in the destination database. This
  45361. ** is to make sure that the schema-version really does change in
  45362. ** the case where the source and destination databases have the
  45363. ** same schema version.
  45364. */
  45365. if( rc==SQLITE_DONE ){
  45366. if( nSrcPage==0 ){
  45367. rc = sqlite3BtreeNewDb(p->pDest);
  45368. nSrcPage = 1;
  45369. }
  45370. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  45371. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  45372. }
  45373. if( rc==SQLITE_OK ){
  45374. if( p->pDestDb ){
  45375. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  45376. }
  45377. if( destMode==PAGER_JOURNALMODE_WAL ){
  45378. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  45379. }
  45380. }
  45381. if( rc==SQLITE_OK ){
  45382. int nDestTruncate;
  45383. /* Set nDestTruncate to the final number of pages in the destination
  45384. ** database. The complication here is that the destination page
  45385. ** size may be different to the source page size.
  45386. **
  45387. ** If the source page size is smaller than the destination page size,
  45388. ** round up. In this case the call to sqlite3OsTruncate() below will
  45389. ** fix the size of the file. However it is important to call
  45390. ** sqlite3PagerTruncateImage() here so that any pages in the
  45391. ** destination file that lie beyond the nDestTruncate page mark are
  45392. ** journalled by PagerCommitPhaseOne() before they are destroyed
  45393. ** by the file truncation.
  45394. */
  45395. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  45396. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  45397. if( pgszSrc<pgszDest ){
  45398. int ratio = pgszDest/pgszSrc;
  45399. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  45400. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  45401. nDestTruncate--;
  45402. }
  45403. }else{
  45404. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  45405. }
  45406. assert( nDestTruncate>0 );
  45407. if( pgszSrc<pgszDest ){
  45408. /* If the source page-size is smaller than the destination page-size,
  45409. ** two extra things may need to happen:
  45410. **
  45411. ** * The destination may need to be truncated, and
  45412. **
  45413. ** * Data stored on the pages immediately following the
  45414. ** pending-byte page in the source database may need to be
  45415. ** copied into the destination database.
  45416. */
  45417. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  45418. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  45419. Pgno iPg;
  45420. int nDstPage;
  45421. i64 iOff;
  45422. i64 iEnd;
  45423. assert( pFile );
  45424. assert( nDestTruncate==0
  45425. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  45426. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  45427. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  45428. ));
  45429. /* This block ensures that all data required to recreate the original
  45430. ** database has been stored in the journal for pDestPager and the
  45431. ** journal synced to disk. So at this point we may safely modify
  45432. ** the database file in any way, knowing that if a power failure
  45433. ** occurs, the original database will be reconstructed from the
  45434. ** journal file. */
  45435. sqlite3PagerPagecount(pDestPager, &nDstPage);
  45436. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  45437. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  45438. DbPage *pPg;
  45439. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  45440. if( rc==SQLITE_OK ){
  45441. rc = sqlite3PagerWrite(pPg);
  45442. sqlite3PagerUnref(pPg);
  45443. }
  45444. }
  45445. }
  45446. if( rc==SQLITE_OK ){
  45447. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  45448. }
  45449. /* Write the extra pages and truncate the database file as required */
  45450. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  45451. for(
  45452. iOff=PENDING_BYTE+pgszSrc;
  45453. rc==SQLITE_OK && iOff<iEnd;
  45454. iOff+=pgszSrc
  45455. ){
  45456. PgHdr *pSrcPg = 0;
  45457. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  45458. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  45459. if( rc==SQLITE_OK ){
  45460. u8 *zData = sqlite3PagerGetData(pSrcPg);
  45461. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  45462. }
  45463. sqlite3PagerUnref(pSrcPg);
  45464. }
  45465. if( rc==SQLITE_OK ){
  45466. rc = backupTruncateFile(pFile, iSize);
  45467. }
  45468. /* Sync the database file to disk. */
  45469. if( rc==SQLITE_OK ){
  45470. rc = sqlite3PagerSync(pDestPager);
  45471. }
  45472. }else{
  45473. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  45474. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  45475. }
  45476. /* Finish committing the transaction to the destination database. */
  45477. if( SQLITE_OK==rc
  45478. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  45479. ){
  45480. rc = SQLITE_DONE;
  45481. }
  45482. }
  45483. }
  45484. /* If bCloseTrans is true, then this function opened a read transaction
  45485. ** on the source database. Close the read transaction here. There is
  45486. ** no need to check the return values of the btree methods here, as
  45487. ** "committing" a read-only transaction cannot fail.
  45488. */
  45489. if( bCloseTrans ){
  45490. TESTONLY( int rc2 );
  45491. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  45492. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  45493. assert( rc2==SQLITE_OK );
  45494. }
  45495. if( rc==SQLITE_IOERR_NOMEM ){
  45496. rc = SQLITE_NOMEM;
  45497. }
  45498. p->rc = rc;
  45499. }
  45500. if( p->pDestDb ){
  45501. sqlite3_mutex_leave(p->pDestDb->mutex);
  45502. }
  45503. sqlite3BtreeLeave(p->pSrc);
  45504. sqlite3_mutex_leave(p->pSrcDb->mutex);
  45505. return rc;
  45506. }
  45507. /*
  45508. ** Release all resources associated with an sqlite3_backup* handle.
  45509. */
  45510. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  45511. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  45512. sqlite3 *pSrcDb; /* Source database connection */
  45513. int rc; /* Value to return */
  45514. /* Enter the mutexes */
  45515. if( p==0 ) return SQLITE_OK;
  45516. pSrcDb = p->pSrcDb;
  45517. sqlite3_mutex_enter(pSrcDb->mutex);
  45518. sqlite3BtreeEnter(p->pSrc);
  45519. if( p->pDestDb ){
  45520. sqlite3_mutex_enter(p->pDestDb->mutex);
  45521. }
  45522. /* Detach this backup from the source pager. */
  45523. if( p->pDestDb ){
  45524. p->pSrc->nBackup--;
  45525. }
  45526. if( p->isAttached ){
  45527. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  45528. while( *pp!=p ){
  45529. pp = &(*pp)->pNext;
  45530. }
  45531. *pp = p->pNext;
  45532. }
  45533. /* If a transaction is still open on the Btree, roll it back. */
  45534. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  45535. /* Set the error code of the destination database handle. */
  45536. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  45537. sqlite3Error(p->pDestDb, rc, 0);
  45538. /* Exit the mutexes and free the backup context structure. */
  45539. if( p->pDestDb ){
  45540. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  45541. }
  45542. sqlite3BtreeLeave(p->pSrc);
  45543. if( p->pDestDb ){
  45544. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  45545. ** call to sqlite3_backup_init() and is destroyed by a call to
  45546. ** sqlite3_backup_finish(). */
  45547. sqlite3_free(p);
  45548. }
  45549. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  45550. return rc;
  45551. }
  45552. /*
  45553. ** Return the number of pages still to be backed up as of the most recent
  45554. ** call to sqlite3_backup_step().
  45555. */
  45556. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  45557. return p->nRemaining;
  45558. }
  45559. /*
  45560. ** Return the total number of pages in the source database as of the most
  45561. ** recent call to sqlite3_backup_step().
  45562. */
  45563. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  45564. return p->nPagecount;
  45565. }
  45566. /*
  45567. ** This function is called after the contents of page iPage of the
  45568. ** source database have been modified. If page iPage has already been
  45569. ** copied into the destination database, then the data written to the
  45570. ** destination is now invalidated. The destination copy of iPage needs
  45571. ** to be updated with the new data before the backup operation is
  45572. ** complete.
  45573. **
  45574. ** It is assumed that the mutex associated with the BtShared object
  45575. ** corresponding to the source database is held when this function is
  45576. ** called.
  45577. */
  45578. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  45579. sqlite3_backup *p; /* Iterator variable */
  45580. for(p=pBackup; p; p=p->pNext){
  45581. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  45582. if( !isFatalError(p->rc) && iPage<p->iNext ){
  45583. /* The backup process p has already copied page iPage. But now it
  45584. ** has been modified by a transaction on the source pager. Copy
  45585. ** the new data into the backup.
  45586. */
  45587. int rc;
  45588. assert( p->pDestDb );
  45589. sqlite3_mutex_enter(p->pDestDb->mutex);
  45590. rc = backupOnePage(p, iPage, aData, 1);
  45591. sqlite3_mutex_leave(p->pDestDb->mutex);
  45592. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  45593. if( rc!=SQLITE_OK ){
  45594. p->rc = rc;
  45595. }
  45596. }
  45597. }
  45598. }
  45599. /*
  45600. ** Restart the backup process. This is called when the pager layer
  45601. ** detects that the database has been modified by an external database
  45602. ** connection. In this case there is no way of knowing which of the
  45603. ** pages that have been copied into the destination database are still
  45604. ** valid and which are not, so the entire process needs to be restarted.
  45605. **
  45606. ** It is assumed that the mutex associated with the BtShared object
  45607. ** corresponding to the source database is held when this function is
  45608. ** called.
  45609. */
  45610. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  45611. sqlite3_backup *p; /* Iterator variable */
  45612. for(p=pBackup; p; p=p->pNext){
  45613. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  45614. p->iNext = 1;
  45615. }
  45616. }
  45617. #ifndef SQLITE_OMIT_VACUUM
  45618. /*
  45619. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  45620. ** must be active for both files.
  45621. **
  45622. ** The size of file pTo may be reduced by this operation. If anything
  45623. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  45624. ** transaction is committed before returning.
  45625. */
  45626. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  45627. int rc;
  45628. sqlite3_file *pFd; /* File descriptor for database pTo */
  45629. sqlite3_backup b;
  45630. sqlite3BtreeEnter(pTo);
  45631. sqlite3BtreeEnter(pFrom);
  45632. assert( sqlite3BtreeIsInTrans(pTo) );
  45633. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  45634. if( pFd->pMethods ){
  45635. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  45636. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  45637. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45638. if( rc ) goto copy_finished;
  45639. }
  45640. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  45641. ** to 0. This is used by the implementations of sqlite3_backup_step()
  45642. ** and sqlite3_backup_finish() to detect that they are being called
  45643. ** from this function, not directly by the user.
  45644. */
  45645. memset(&b, 0, sizeof(b));
  45646. b.pSrcDb = pFrom->db;
  45647. b.pSrc = pFrom;
  45648. b.pDest = pTo;
  45649. b.iNext = 1;
  45650. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  45651. ** file. By passing this as the number of pages to copy to
  45652. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  45653. ** within a single call (unless an error occurs). The assert() statement
  45654. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  45655. ** or an error code.
  45656. */
  45657. sqlite3_backup_step(&b, 0x7FFFFFFF);
  45658. assert( b.rc!=SQLITE_OK );
  45659. rc = sqlite3_backup_finish(&b);
  45660. if( rc==SQLITE_OK ){
  45661. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  45662. }else{
  45663. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  45664. }
  45665. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  45666. copy_finished:
  45667. sqlite3BtreeLeave(pFrom);
  45668. sqlite3BtreeLeave(pTo);
  45669. return rc;
  45670. }
  45671. #endif /* SQLITE_OMIT_VACUUM */
  45672. /************** End of backup.c **********************************************/
  45673. /************** Begin file vdbemem.c *****************************************/
  45674. /*
  45675. ** 2004 May 26
  45676. **
  45677. ** The author disclaims copyright to this source code. In place of
  45678. ** a legal notice, here is a blessing:
  45679. **
  45680. ** May you do good and not evil.
  45681. ** May you find forgiveness for yourself and forgive others.
  45682. ** May you share freely, never taking more than you give.
  45683. **
  45684. *************************************************************************
  45685. **
  45686. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  45687. ** stores a single value in the VDBE. Mem is an opaque structure visible
  45688. ** only within the VDBE. Interface routines refer to a Mem using the
  45689. ** name sqlite_value
  45690. */
  45691. /*
  45692. ** If pMem is an object with a valid string representation, this routine
  45693. ** ensures the internal encoding for the string representation is
  45694. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  45695. **
  45696. ** If pMem is not a string object, or the encoding of the string
  45697. ** representation is already stored using the requested encoding, then this
  45698. ** routine is a no-op.
  45699. **
  45700. ** SQLITE_OK is returned if the conversion is successful (or not required).
  45701. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  45702. ** between formats.
  45703. */
  45704. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  45705. #ifndef SQLITE_OMIT_UTF16
  45706. int rc;
  45707. #endif
  45708. assert( (pMem->flags&MEM_RowSet)==0 );
  45709. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  45710. || desiredEnc==SQLITE_UTF16BE );
  45711. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  45712. return SQLITE_OK;
  45713. }
  45714. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45715. #ifdef SQLITE_OMIT_UTF16
  45716. return SQLITE_ERROR;
  45717. #else
  45718. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  45719. ** then the encoding of the value may not have changed.
  45720. */
  45721. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  45722. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  45723. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  45724. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  45725. return rc;
  45726. #endif
  45727. }
  45728. /*
  45729. ** Make sure pMem->z points to a writable allocation of at least
  45730. ** n bytes.
  45731. **
  45732. ** If the third argument passed to this function is true, then memory
  45733. ** cell pMem must contain a string or blob. In this case the content is
  45734. ** preserved. Otherwise, if the third parameter to this function is false,
  45735. ** any current string or blob value may be discarded.
  45736. **
  45737. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  45738. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  45739. ** not set, Mem.n is zeroed.
  45740. */
  45741. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  45742. assert( 1 >=
  45743. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  45744. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  45745. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  45746. ((pMem->flags&MEM_Static) ? 1 : 0)
  45747. );
  45748. assert( (pMem->flags&MEM_RowSet)==0 );
  45749. /* If the preserve flag is set to true, then the memory cell must already
  45750. ** contain a valid string or blob value. */
  45751. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  45752. if( n<32 ) n = 32;
  45753. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  45754. if( preserve && pMem->z==pMem->zMalloc ){
  45755. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  45756. preserve = 0;
  45757. }else{
  45758. sqlite3DbFree(pMem->db, pMem->zMalloc);
  45759. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  45760. }
  45761. }
  45762. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  45763. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  45764. }
  45765. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  45766. assert( pMem->xDel!=SQLITE_DYNAMIC );
  45767. pMem->xDel((void *)(pMem->z));
  45768. }
  45769. pMem->z = pMem->zMalloc;
  45770. if( pMem->z==0 ){
  45771. pMem->flags = MEM_Null;
  45772. }else{
  45773. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  45774. }
  45775. pMem->xDel = 0;
  45776. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  45777. }
  45778. /*
  45779. ** Make the given Mem object MEM_Dyn. In other words, make it so
  45780. ** that any TEXT or BLOB content is stored in memory obtained from
  45781. ** malloc(). In this way, we know that the memory is safe to be
  45782. ** overwritten or altered.
  45783. **
  45784. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  45785. */
  45786. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  45787. int f;
  45788. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45789. assert( (pMem->flags&MEM_RowSet)==0 );
  45790. ExpandBlob(pMem);
  45791. f = pMem->flags;
  45792. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  45793. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  45794. return SQLITE_NOMEM;
  45795. }
  45796. pMem->z[pMem->n] = 0;
  45797. pMem->z[pMem->n+1] = 0;
  45798. pMem->flags |= MEM_Term;
  45799. #ifdef SQLITE_DEBUG
  45800. pMem->pScopyFrom = 0;
  45801. #endif
  45802. }
  45803. return SQLITE_OK;
  45804. }
  45805. /*
  45806. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  45807. ** blob stored in dynamically allocated space.
  45808. */
  45809. #ifndef SQLITE_OMIT_INCRBLOB
  45810. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  45811. if( pMem->flags & MEM_Zero ){
  45812. int nByte;
  45813. assert( pMem->flags&MEM_Blob );
  45814. assert( (pMem->flags&MEM_RowSet)==0 );
  45815. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45816. /* Set nByte to the number of bytes required to store the expanded blob. */
  45817. nByte = pMem->n + pMem->u.nZero;
  45818. if( nByte<=0 ){
  45819. nByte = 1;
  45820. }
  45821. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  45822. return SQLITE_NOMEM;
  45823. }
  45824. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  45825. pMem->n += pMem->u.nZero;
  45826. pMem->flags &= ~(MEM_Zero|MEM_Term);
  45827. }
  45828. return SQLITE_OK;
  45829. }
  45830. #endif
  45831. /*
  45832. ** Make sure the given Mem is \u0000 terminated.
  45833. */
  45834. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  45835. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45836. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  45837. return SQLITE_OK; /* Nothing to do */
  45838. }
  45839. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  45840. return SQLITE_NOMEM;
  45841. }
  45842. pMem->z[pMem->n] = 0;
  45843. pMem->z[pMem->n+1] = 0;
  45844. pMem->flags |= MEM_Term;
  45845. return SQLITE_OK;
  45846. }
  45847. /*
  45848. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  45849. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  45850. ** is a no-op.
  45851. **
  45852. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  45853. **
  45854. ** A MEM_Null value will never be passed to this function. This function is
  45855. ** used for converting values to text for returning to the user (i.e. via
  45856. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  45857. ** keys are strings. In the former case a NULL pointer is returned the
  45858. ** user and the later is an internal programming error.
  45859. */
  45860. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  45861. int rc = SQLITE_OK;
  45862. int fg = pMem->flags;
  45863. const int nByte = 32;
  45864. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45865. assert( !(fg&MEM_Zero) );
  45866. assert( !(fg&(MEM_Str|MEM_Blob)) );
  45867. assert( fg&(MEM_Int|MEM_Real) );
  45868. assert( (pMem->flags&MEM_RowSet)==0 );
  45869. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  45870. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  45871. return SQLITE_NOMEM;
  45872. }
  45873. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  45874. ** string representation of the value. Then, if the required encoding
  45875. ** is UTF-16le or UTF-16be do a translation.
  45876. **
  45877. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  45878. */
  45879. if( fg & MEM_Int ){
  45880. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  45881. }else{
  45882. assert( fg & MEM_Real );
  45883. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  45884. }
  45885. pMem->n = sqlite3Strlen30(pMem->z);
  45886. pMem->enc = SQLITE_UTF8;
  45887. pMem->flags |= MEM_Str|MEM_Term;
  45888. sqlite3VdbeChangeEncoding(pMem, enc);
  45889. return rc;
  45890. }
  45891. /*
  45892. ** Memory cell pMem contains the context of an aggregate function.
  45893. ** This routine calls the finalize method for that function. The
  45894. ** result of the aggregate is stored back into pMem.
  45895. **
  45896. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  45897. ** otherwise.
  45898. */
  45899. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  45900. int rc = SQLITE_OK;
  45901. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  45902. sqlite3_context ctx;
  45903. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  45904. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  45905. memset(&ctx, 0, sizeof(ctx));
  45906. ctx.s.flags = MEM_Null;
  45907. ctx.s.db = pMem->db;
  45908. ctx.pMem = pMem;
  45909. ctx.pFunc = pFunc;
  45910. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  45911. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  45912. sqlite3DbFree(pMem->db, pMem->zMalloc);
  45913. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  45914. rc = ctx.isError;
  45915. }
  45916. return rc;
  45917. }
  45918. /*
  45919. ** If the memory cell contains a string value that must be freed by
  45920. ** invoking an external callback, free it now. Calling this function
  45921. ** does not free any Mem.zMalloc buffer.
  45922. */
  45923. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  45924. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  45925. if( p->flags&MEM_Agg ){
  45926. sqlite3VdbeMemFinalize(p, p->u.pDef);
  45927. assert( (p->flags & MEM_Agg)==0 );
  45928. sqlite3VdbeMemRelease(p);
  45929. }else if( p->flags&MEM_Dyn && p->xDel ){
  45930. assert( (p->flags&MEM_RowSet)==0 );
  45931. assert( p->xDel!=SQLITE_DYNAMIC );
  45932. p->xDel((void *)p->z);
  45933. p->xDel = 0;
  45934. }else if( p->flags&MEM_RowSet ){
  45935. sqlite3RowSetClear(p->u.pRowSet);
  45936. }else if( p->flags&MEM_Frame ){
  45937. sqlite3VdbeMemSetNull(p);
  45938. }
  45939. }
  45940. /*
  45941. ** Release any memory held by the Mem. This may leave the Mem in an
  45942. ** inconsistent state, for example with (Mem.z==0) and
  45943. ** (Mem.type==SQLITE_TEXT).
  45944. */
  45945. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  45946. VdbeMemRelease(p);
  45947. sqlite3DbFree(p->db, p->zMalloc);
  45948. p->z = 0;
  45949. p->zMalloc = 0;
  45950. p->xDel = 0;
  45951. }
  45952. /*
  45953. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  45954. ** If the double is too large, return 0x8000000000000000.
  45955. **
  45956. ** Most systems appear to do this simply by assigning
  45957. ** variables and without the extra range tests. But
  45958. ** there are reports that windows throws an expection
  45959. ** if the floating point value is out of range. (See ticket #2880.)
  45960. ** Because we do not completely understand the problem, we will
  45961. ** take the conservative approach and always do range tests
  45962. ** before attempting the conversion.
  45963. */
  45964. static i64 doubleToInt64(double r){
  45965. #ifdef SQLITE_OMIT_FLOATING_POINT
  45966. /* When floating-point is omitted, double and int64 are the same thing */
  45967. return r;
  45968. #else
  45969. /*
  45970. ** Many compilers we encounter do not define constants for the
  45971. ** minimum and maximum 64-bit integers, or they define them
  45972. ** inconsistently. And many do not understand the "LL" notation.
  45973. ** So we define our own static constants here using nothing
  45974. ** larger than a 32-bit integer constant.
  45975. */
  45976. static const i64 maxInt = LARGEST_INT64;
  45977. static const i64 minInt = SMALLEST_INT64;
  45978. if( r<(double)minInt ){
  45979. return minInt;
  45980. }else if( r>(double)maxInt ){
  45981. /* minInt is correct here - not maxInt. It turns out that assigning
  45982. ** a very large positive number to an integer results in a very large
  45983. ** negative integer. This makes no sense, but it is what x86 hardware
  45984. ** does so for compatibility we will do the same in software. */
  45985. return minInt;
  45986. }else{
  45987. return (i64)r;
  45988. }
  45989. #endif
  45990. }
  45991. /*
  45992. ** Return some kind of integer value which is the best we can do
  45993. ** at representing the value that *pMem describes as an integer.
  45994. ** If pMem is an integer, then the value is exact. If pMem is
  45995. ** a floating-point then the value returned is the integer part.
  45996. ** If pMem is a string or blob, then we make an attempt to convert
  45997. ** it into a integer and return that. If pMem represents an
  45998. ** an SQL-NULL value, return 0.
  45999. **
  46000. ** If pMem represents a string value, its encoding might be changed.
  46001. */
  46002. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  46003. int flags;
  46004. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46005. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46006. flags = pMem->flags;
  46007. if( flags & MEM_Int ){
  46008. return pMem->u.i;
  46009. }else if( flags & MEM_Real ){
  46010. return doubleToInt64(pMem->r);
  46011. }else if( flags & (MEM_Str|MEM_Blob) ){
  46012. i64 value = 0;
  46013. assert( pMem->z || pMem->n==0 );
  46014. testcase( pMem->z==0 );
  46015. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  46016. return value;
  46017. }else{
  46018. return 0;
  46019. }
  46020. }
  46021. /*
  46022. ** Return the best representation of pMem that we can get into a
  46023. ** double. If pMem is already a double or an integer, return its
  46024. ** value. If it is a string or blob, try to convert it to a double.
  46025. ** If it is a NULL, return 0.0.
  46026. */
  46027. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  46028. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46029. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46030. if( pMem->flags & MEM_Real ){
  46031. return pMem->r;
  46032. }else if( pMem->flags & MEM_Int ){
  46033. return (double)pMem->u.i;
  46034. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  46035. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  46036. double val = (double)0;
  46037. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  46038. return val;
  46039. }else{
  46040. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  46041. return (double)0;
  46042. }
  46043. }
  46044. /*
  46045. ** The MEM structure is already a MEM_Real. Try to also make it a
  46046. ** MEM_Int if we can.
  46047. */
  46048. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  46049. assert( pMem->flags & MEM_Real );
  46050. assert( (pMem->flags & MEM_RowSet)==0 );
  46051. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46052. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46053. pMem->u.i = doubleToInt64(pMem->r);
  46054. /* Only mark the value as an integer if
  46055. **
  46056. ** (1) the round-trip conversion real->int->real is a no-op, and
  46057. ** (2) The integer is neither the largest nor the smallest
  46058. ** possible integer (ticket #3922)
  46059. **
  46060. ** The second and third terms in the following conditional enforces
  46061. ** the second condition under the assumption that addition overflow causes
  46062. ** values to wrap around. On x86 hardware, the third term is always
  46063. ** true and could be omitted. But we leave it in because other
  46064. ** architectures might behave differently.
  46065. */
  46066. if( pMem->r==(double)pMem->u.i
  46067. && pMem->u.i>SMALLEST_INT64
  46068. #if defined(__i486__) || defined(__x86_64__)
  46069. && ALWAYS(pMem->u.i<LARGEST_INT64)
  46070. #else
  46071. && pMem->u.i<LARGEST_INT64
  46072. #endif
  46073. ){
  46074. pMem->flags |= MEM_Int;
  46075. }
  46076. }
  46077. /*
  46078. ** Convert pMem to type integer. Invalidate any prior representations.
  46079. */
  46080. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  46081. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46082. assert( (pMem->flags & MEM_RowSet)==0 );
  46083. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46084. pMem->u.i = sqlite3VdbeIntValue(pMem);
  46085. MemSetTypeFlag(pMem, MEM_Int);
  46086. return SQLITE_OK;
  46087. }
  46088. /*
  46089. ** Convert pMem so that it is of type MEM_Real.
  46090. ** Invalidate any prior representations.
  46091. */
  46092. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  46093. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46094. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  46095. pMem->r = sqlite3VdbeRealValue(pMem);
  46096. MemSetTypeFlag(pMem, MEM_Real);
  46097. return SQLITE_OK;
  46098. }
  46099. /*
  46100. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  46101. ** Invalidate any prior representations.
  46102. **
  46103. ** Every effort is made to force the conversion, even if the input
  46104. ** is a string that does not look completely like a number. Convert
  46105. ** as much of the string as we can and ignore the rest.
  46106. */
  46107. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  46108. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  46109. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  46110. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46111. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  46112. MemSetTypeFlag(pMem, MEM_Int);
  46113. }else{
  46114. pMem->r = sqlite3VdbeRealValue(pMem);
  46115. MemSetTypeFlag(pMem, MEM_Real);
  46116. sqlite3VdbeIntegerAffinity(pMem);
  46117. }
  46118. }
  46119. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  46120. pMem->flags &= ~(MEM_Str|MEM_Blob);
  46121. return SQLITE_OK;
  46122. }
  46123. /*
  46124. ** Delete any previous value and set the value stored in *pMem to NULL.
  46125. */
  46126. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  46127. if( pMem->flags & MEM_Frame ){
  46128. VdbeFrame *pFrame = pMem->u.pFrame;
  46129. pFrame->pParent = pFrame->v->pDelFrame;
  46130. pFrame->v->pDelFrame = pFrame;
  46131. }
  46132. if( pMem->flags & MEM_RowSet ){
  46133. sqlite3RowSetClear(pMem->u.pRowSet);
  46134. }
  46135. MemSetTypeFlag(pMem, MEM_Null);
  46136. pMem->type = SQLITE_NULL;
  46137. }
  46138. /*
  46139. ** Delete any previous value and set the value to be a BLOB of length
  46140. ** n containing all zeros.
  46141. */
  46142. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  46143. sqlite3VdbeMemRelease(pMem);
  46144. pMem->flags = MEM_Blob|MEM_Zero;
  46145. pMem->type = SQLITE_BLOB;
  46146. pMem->n = 0;
  46147. if( n<0 ) n = 0;
  46148. pMem->u.nZero = n;
  46149. pMem->enc = SQLITE_UTF8;
  46150. #ifdef SQLITE_OMIT_INCRBLOB
  46151. sqlite3VdbeMemGrow(pMem, n, 0);
  46152. if( pMem->z ){
  46153. pMem->n = n;
  46154. memset(pMem->z, 0, n);
  46155. }
  46156. #endif
  46157. }
  46158. /*
  46159. ** Delete any previous value and set the value stored in *pMem to val,
  46160. ** manifest type INTEGER.
  46161. */
  46162. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  46163. sqlite3VdbeMemRelease(pMem);
  46164. pMem->u.i = val;
  46165. pMem->flags = MEM_Int;
  46166. pMem->type = SQLITE_INTEGER;
  46167. }
  46168. #ifndef SQLITE_OMIT_FLOATING_POINT
  46169. /*
  46170. ** Delete any previous value and set the value stored in *pMem to val,
  46171. ** manifest type REAL.
  46172. */
  46173. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  46174. if( sqlite3IsNaN(val) ){
  46175. sqlite3VdbeMemSetNull(pMem);
  46176. }else{
  46177. sqlite3VdbeMemRelease(pMem);
  46178. pMem->r = val;
  46179. pMem->flags = MEM_Real;
  46180. pMem->type = SQLITE_FLOAT;
  46181. }
  46182. }
  46183. #endif
  46184. /*
  46185. ** Delete any previous value and set the value of pMem to be an
  46186. ** empty boolean index.
  46187. */
  46188. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  46189. sqlite3 *db = pMem->db;
  46190. assert( db!=0 );
  46191. assert( (pMem->flags & MEM_RowSet)==0 );
  46192. sqlite3VdbeMemRelease(pMem);
  46193. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  46194. if( db->mallocFailed ){
  46195. pMem->flags = MEM_Null;
  46196. }else{
  46197. assert( pMem->zMalloc );
  46198. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  46199. sqlite3DbMallocSize(db, pMem->zMalloc));
  46200. assert( pMem->u.pRowSet!=0 );
  46201. pMem->flags = MEM_RowSet;
  46202. }
  46203. }
  46204. /*
  46205. ** Return true if the Mem object contains a TEXT or BLOB that is
  46206. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  46207. */
  46208. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  46209. assert( p->db!=0 );
  46210. if( p->flags & (MEM_Str|MEM_Blob) ){
  46211. int n = p->n;
  46212. if( p->flags & MEM_Zero ){
  46213. n += p->u.nZero;
  46214. }
  46215. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  46216. }
  46217. return 0;
  46218. }
  46219. #ifdef SQLITE_DEBUG
  46220. /*
  46221. ** This routine prepares a memory cell for modication by breaking
  46222. ** its link to a shallow copy and by marking any current shallow
  46223. ** copies of this cell as invalid.
  46224. **
  46225. ** This is used for testing and debugging only - to make sure shallow
  46226. ** copies are not misused.
  46227. */
  46228. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  46229. int i;
  46230. Mem *pX;
  46231. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  46232. if( pX->pScopyFrom==pMem ){
  46233. pX->flags |= MEM_Invalid;
  46234. pX->pScopyFrom = 0;
  46235. }
  46236. }
  46237. pMem->pScopyFrom = 0;
  46238. }
  46239. #endif /* SQLITE_DEBUG */
  46240. /*
  46241. ** Size of struct Mem not including the Mem.zMalloc member.
  46242. */
  46243. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  46244. /*
  46245. ** Make an shallow copy of pFrom into pTo. Prior contents of
  46246. ** pTo are freed. The pFrom->z field is not duplicated. If
  46247. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  46248. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  46249. */
  46250. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  46251. assert( (pFrom->flags & MEM_RowSet)==0 );
  46252. VdbeMemRelease(pTo);
  46253. memcpy(pTo, pFrom, MEMCELLSIZE);
  46254. pTo->xDel = 0;
  46255. if( (pFrom->flags&MEM_Static)==0 ){
  46256. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  46257. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  46258. pTo->flags |= srcType;
  46259. }
  46260. }
  46261. /*
  46262. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  46263. ** freed before the copy is made.
  46264. */
  46265. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  46266. int rc = SQLITE_OK;
  46267. assert( (pFrom->flags & MEM_RowSet)==0 );
  46268. VdbeMemRelease(pTo);
  46269. memcpy(pTo, pFrom, MEMCELLSIZE);
  46270. pTo->flags &= ~MEM_Dyn;
  46271. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  46272. if( 0==(pFrom->flags&MEM_Static) ){
  46273. pTo->flags |= MEM_Ephem;
  46274. rc = sqlite3VdbeMemMakeWriteable(pTo);
  46275. }
  46276. }
  46277. return rc;
  46278. }
  46279. /*
  46280. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  46281. ** freed. If pFrom contains ephemeral data, a copy is made.
  46282. **
  46283. ** pFrom contains an SQL NULL when this routine returns.
  46284. */
  46285. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  46286. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  46287. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  46288. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  46289. sqlite3VdbeMemRelease(pTo);
  46290. memcpy(pTo, pFrom, sizeof(Mem));
  46291. pFrom->flags = MEM_Null;
  46292. pFrom->xDel = 0;
  46293. pFrom->zMalloc = 0;
  46294. }
  46295. /*
  46296. ** Change the value of a Mem to be a string or a BLOB.
  46297. **
  46298. ** The memory management strategy depends on the value of the xDel
  46299. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  46300. ** string is copied into a (possibly existing) buffer managed by the
  46301. ** Mem structure. Otherwise, any existing buffer is freed and the
  46302. ** pointer copied.
  46303. **
  46304. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  46305. ** size limit) then no memory allocation occurs. If the string can be
  46306. ** stored without allocating memory, then it is. If a memory allocation
  46307. ** is required to store the string, then value of pMem is unchanged. In
  46308. ** either case, SQLITE_TOOBIG is returned.
  46309. */
  46310. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  46311. Mem *pMem, /* Memory cell to set to string value */
  46312. const char *z, /* String pointer */
  46313. int n, /* Bytes in string, or negative */
  46314. u8 enc, /* Encoding of z. 0 for BLOBs */
  46315. void (*xDel)(void*) /* Destructor function */
  46316. ){
  46317. int nByte = n; /* New value for pMem->n */
  46318. int iLimit; /* Maximum allowed string or blob size */
  46319. u16 flags = 0; /* New value for pMem->flags */
  46320. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  46321. assert( (pMem->flags & MEM_RowSet)==0 );
  46322. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  46323. if( !z ){
  46324. sqlite3VdbeMemSetNull(pMem);
  46325. return SQLITE_OK;
  46326. }
  46327. if( pMem->db ){
  46328. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  46329. }else{
  46330. iLimit = SQLITE_MAX_LENGTH;
  46331. }
  46332. flags = (enc==0?MEM_Blob:MEM_Str);
  46333. if( nByte<0 ){
  46334. assert( enc!=0 );
  46335. if( enc==SQLITE_UTF8 ){
  46336. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  46337. }else{
  46338. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  46339. }
  46340. flags |= MEM_Term;
  46341. }
  46342. /* The following block sets the new values of Mem.z and Mem.xDel. It
  46343. ** also sets a flag in local variable "flags" to indicate the memory
  46344. ** management (one of MEM_Dyn or MEM_Static).
  46345. */
  46346. if( xDel==SQLITE_TRANSIENT ){
  46347. int nAlloc = nByte;
  46348. if( flags&MEM_Term ){
  46349. nAlloc += (enc==SQLITE_UTF8?1:2);
  46350. }
  46351. if( nByte>iLimit ){
  46352. return SQLITE_TOOBIG;
  46353. }
  46354. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  46355. return SQLITE_NOMEM;
  46356. }
  46357. memcpy(pMem->z, z, nAlloc);
  46358. }else if( xDel==SQLITE_DYNAMIC ){
  46359. sqlite3VdbeMemRelease(pMem);
  46360. pMem->zMalloc = pMem->z = (char *)z;
  46361. pMem->xDel = 0;
  46362. }else{
  46363. sqlite3VdbeMemRelease(pMem);
  46364. pMem->z = (char *)z;
  46365. pMem->xDel = xDel;
  46366. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  46367. }
  46368. pMem->n = nByte;
  46369. pMem->flags = flags;
  46370. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  46371. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  46372. #ifndef SQLITE_OMIT_UTF16
  46373. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  46374. return SQLITE_NOMEM;
  46375. }
  46376. #endif
  46377. if( nByte>iLimit ){
  46378. return SQLITE_TOOBIG;
  46379. }
  46380. return SQLITE_OK;
  46381. }
  46382. /*
  46383. ** Compare the values contained by the two memory cells, returning
  46384. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  46385. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  46386. ** and reals) sorted numerically, followed by text ordered by the collating
  46387. ** sequence pColl and finally blob's ordered by memcmp().
  46388. **
  46389. ** Two NULL values are considered equal by this function.
  46390. */
  46391. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  46392. int rc;
  46393. int f1, f2;
  46394. int combined_flags;
  46395. f1 = pMem1->flags;
  46396. f2 = pMem2->flags;
  46397. combined_flags = f1|f2;
  46398. assert( (combined_flags & MEM_RowSet)==0 );
  46399. /* If one value is NULL, it is less than the other. If both values
  46400. ** are NULL, return 0.
  46401. */
  46402. if( combined_flags&MEM_Null ){
  46403. return (f2&MEM_Null) - (f1&MEM_Null);
  46404. }
  46405. /* If one value is a number and the other is not, the number is less.
  46406. ** If both are numbers, compare as reals if one is a real, or as integers
  46407. ** if both values are integers.
  46408. */
  46409. if( combined_flags&(MEM_Int|MEM_Real) ){
  46410. double r1, r2;
  46411. if( (f1 & f2 & MEM_Int)!=0 ){
  46412. if( pMem1->u.i < pMem2->u.i ) return -1;
  46413. if( pMem1->u.i > pMem2->u.i ) return 1;
  46414. return 0;
  46415. }
  46416. if( (f1&MEM_Real)!=0 ){
  46417. r1 = pMem1->r;
  46418. }else if( (f1&MEM_Int)!=0 ){
  46419. r1 = (double)pMem1->u.i;
  46420. }else{
  46421. return 1;
  46422. }
  46423. if( (f2&MEM_Real)!=0 ){
  46424. r2 = pMem2->r;
  46425. }else if( (f2&MEM_Int)!=0 ){
  46426. r2 = (double)pMem2->u.i;
  46427. }else{
  46428. return -1;
  46429. }
  46430. if( r1<r2 ) return -1;
  46431. if( r1>r2 ) return 1;
  46432. return 0;
  46433. }
  46434. /* If one value is a string and the other is a blob, the string is less.
  46435. ** If both are strings, compare using the collating functions.
  46436. */
  46437. if( combined_flags&MEM_Str ){
  46438. if( (f1 & MEM_Str)==0 ){
  46439. return 1;
  46440. }
  46441. if( (f2 & MEM_Str)==0 ){
  46442. return -1;
  46443. }
  46444. assert( pMem1->enc==pMem2->enc );
  46445. assert( pMem1->enc==SQLITE_UTF8 ||
  46446. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  46447. /* The collation sequence must be defined at this point, even if
  46448. ** the user deletes the collation sequence after the vdbe program is
  46449. ** compiled (this was not always the case).
  46450. */
  46451. assert( !pColl || pColl->xCmp );
  46452. if( pColl ){
  46453. if( pMem1->enc==pColl->enc ){
  46454. /* The strings are already in the correct encoding. Call the
  46455. ** comparison function directly */
  46456. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  46457. }else{
  46458. const void *v1, *v2;
  46459. int n1, n2;
  46460. Mem c1;
  46461. Mem c2;
  46462. memset(&c1, 0, sizeof(c1));
  46463. memset(&c2, 0, sizeof(c2));
  46464. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  46465. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  46466. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  46467. n1 = v1==0 ? 0 : c1.n;
  46468. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  46469. n2 = v2==0 ? 0 : c2.n;
  46470. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  46471. sqlite3VdbeMemRelease(&c1);
  46472. sqlite3VdbeMemRelease(&c2);
  46473. return rc;
  46474. }
  46475. }
  46476. /* If a NULL pointer was passed as the collate function, fall through
  46477. ** to the blob case and use memcmp(). */
  46478. }
  46479. /* Both values must be blobs. Compare using memcmp(). */
  46480. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  46481. if( rc==0 ){
  46482. rc = pMem1->n - pMem2->n;
  46483. }
  46484. return rc;
  46485. }
  46486. /*
  46487. ** Move data out of a btree key or data field and into a Mem structure.
  46488. ** The data or key is taken from the entry that pCur is currently pointing
  46489. ** to. offset and amt determine what portion of the data or key to retrieve.
  46490. ** key is true to get the key or false to get data. The result is written
  46491. ** into the pMem element.
  46492. **
  46493. ** The pMem structure is assumed to be uninitialized. Any prior content
  46494. ** is overwritten without being freed.
  46495. **
  46496. ** If this routine fails for any reason (malloc returns NULL or unable
  46497. ** to read from the disk) then the pMem is left in an inconsistent state.
  46498. */
  46499. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  46500. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  46501. int offset, /* Offset from the start of data to return bytes from. */
  46502. int amt, /* Number of bytes to return. */
  46503. int key, /* If true, retrieve from the btree key, not data. */
  46504. Mem *pMem /* OUT: Return data in this Mem structure. */
  46505. ){
  46506. char *zData; /* Data from the btree layer */
  46507. int available = 0; /* Number of bytes available on the local btree page */
  46508. int rc = SQLITE_OK; /* Return code */
  46509. assert( sqlite3BtreeCursorIsValid(pCur) );
  46510. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  46511. ** that both the BtShared and database handle mutexes are held. */
  46512. assert( (pMem->flags & MEM_RowSet)==0 );
  46513. if( key ){
  46514. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  46515. }else{
  46516. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  46517. }
  46518. assert( zData!=0 );
  46519. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  46520. sqlite3VdbeMemRelease(pMem);
  46521. pMem->z = &zData[offset];
  46522. pMem->flags = MEM_Blob|MEM_Ephem;
  46523. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  46524. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  46525. pMem->enc = 0;
  46526. pMem->type = SQLITE_BLOB;
  46527. if( key ){
  46528. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  46529. }else{
  46530. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  46531. }
  46532. pMem->z[amt] = 0;
  46533. pMem->z[amt+1] = 0;
  46534. if( rc!=SQLITE_OK ){
  46535. sqlite3VdbeMemRelease(pMem);
  46536. }
  46537. }
  46538. pMem->n = amt;
  46539. return rc;
  46540. }
  46541. /* This function is only available internally, it is not part of the
  46542. ** external API. It works in a similar way to sqlite3_value_text(),
  46543. ** except the data returned is in the encoding specified by the second
  46544. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  46545. ** SQLITE_UTF8.
  46546. **
  46547. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  46548. ** If that is the case, then the result must be aligned on an even byte
  46549. ** boundary.
  46550. */
  46551. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  46552. if( !pVal ) return 0;
  46553. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  46554. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  46555. assert( (pVal->flags & MEM_RowSet)==0 );
  46556. if( pVal->flags&MEM_Null ){
  46557. return 0;
  46558. }
  46559. assert( (MEM_Blob>>3) == MEM_Str );
  46560. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  46561. ExpandBlob(pVal);
  46562. if( pVal->flags&MEM_Str ){
  46563. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  46564. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  46565. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  46566. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  46567. return 0;
  46568. }
  46569. }
  46570. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  46571. }else{
  46572. assert( (pVal->flags&MEM_Blob)==0 );
  46573. sqlite3VdbeMemStringify(pVal, enc);
  46574. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  46575. }
  46576. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  46577. || pVal->db->mallocFailed );
  46578. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  46579. return pVal->z;
  46580. }else{
  46581. return 0;
  46582. }
  46583. }
  46584. /*
  46585. ** Create a new sqlite3_value object.
  46586. */
  46587. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  46588. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  46589. if( p ){
  46590. p->flags = MEM_Null;
  46591. p->type = SQLITE_NULL;
  46592. p->db = db;
  46593. }
  46594. return p;
  46595. }
  46596. /*
  46597. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  46598. ** valueNew(). See comments above valueNew() for details.
  46599. */
  46600. struct ValueNewStat4Ctx {
  46601. Parse *pParse;
  46602. Index *pIdx;
  46603. UnpackedRecord **ppRec;
  46604. int iVal;
  46605. };
  46606. /*
  46607. ** Allocate and return a pointer to a new sqlite3_value object. If
  46608. ** the second argument to this function is NULL, the object is allocated
  46609. ** by calling sqlite3ValueNew().
  46610. **
  46611. ** Otherwise, if the second argument is non-zero, then this function is
  46612. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  46613. ** already been allocated, allocate the UnpackedRecord structure that
  46614. ** that function will return to its caller here. Then return a pointer
  46615. ** an sqlite3_value within the UnpackedRecord.a[] array.
  46616. */
  46617. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  46618. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46619. if( p ){
  46620. UnpackedRecord *pRec = p->ppRec[0];
  46621. if( pRec==0 ){
  46622. Index *pIdx = p->pIdx; /* Index being probed */
  46623. int nByte; /* Bytes of space to allocate */
  46624. int i; /* Counter variable */
  46625. int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */
  46626. nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord);
  46627. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  46628. if( pRec ){
  46629. pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx);
  46630. if( pRec->pKeyInfo ){
  46631. assert( pRec->pKeyInfo->nField+1==nCol );
  46632. pRec->pKeyInfo->enc = ENC(db);
  46633. pRec->flags = UNPACKED_PREFIX_MATCH;
  46634. pRec->aMem = (Mem *)&pRec[1];
  46635. for(i=0; i<nCol; i++){
  46636. pRec->aMem[i].flags = MEM_Null;
  46637. pRec->aMem[i].type = SQLITE_NULL;
  46638. pRec->aMem[i].db = db;
  46639. }
  46640. }else{
  46641. sqlite3DbFree(db, pRec);
  46642. pRec = 0;
  46643. }
  46644. }
  46645. if( pRec==0 ) return 0;
  46646. p->ppRec[0] = pRec;
  46647. }
  46648. pRec->nField = p->iVal+1;
  46649. return &pRec->aMem[p->iVal];
  46650. }
  46651. #else
  46652. UNUSED_PARAMETER(p);
  46653. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  46654. return sqlite3ValueNew(db);
  46655. }
  46656. /*
  46657. ** Extract a value from the supplied expression in the manner described
  46658. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  46659. ** using valueNew().
  46660. **
  46661. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  46662. ** has been allocated, it is freed before returning. Or, if pCtx is not
  46663. ** NULL, it is assumed that the caller will free any allocated object
  46664. ** in all cases.
  46665. */
  46666. static int valueFromExpr(
  46667. sqlite3 *db, /* The database connection */
  46668. Expr *pExpr, /* The expression to evaluate */
  46669. u8 enc, /* Encoding to use */
  46670. u8 affinity, /* Affinity to use */
  46671. sqlite3_value **ppVal, /* Write the new value here */
  46672. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  46673. ){
  46674. int op;
  46675. char *zVal = 0;
  46676. sqlite3_value *pVal = 0;
  46677. int negInt = 1;
  46678. const char *zNeg = "";
  46679. int rc = SQLITE_OK;
  46680. if( !pExpr ){
  46681. *ppVal = 0;
  46682. return SQLITE_OK;
  46683. }
  46684. op = pExpr->op;
  46685. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4.
  46686. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  46687. ** when SQLITE_ENABLE_STAT4 is omitted.
  46688. */
  46689. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46690. if( op==TK_REGISTER ) op = pExpr->op2;
  46691. #else
  46692. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  46693. #endif
  46694. /* Handle negative integers in a single step. This is needed in the
  46695. ** case when the value is -9223372036854775808.
  46696. */
  46697. if( op==TK_UMINUS
  46698. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  46699. pExpr = pExpr->pLeft;
  46700. op = pExpr->op;
  46701. negInt = -1;
  46702. zNeg = "-";
  46703. }
  46704. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  46705. pVal = valueNew(db, pCtx);
  46706. if( pVal==0 ) goto no_mem;
  46707. if( ExprHasProperty(pExpr, EP_IntValue) ){
  46708. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  46709. }else{
  46710. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  46711. if( zVal==0 ) goto no_mem;
  46712. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  46713. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  46714. }
  46715. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  46716. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  46717. }else{
  46718. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  46719. }
  46720. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  46721. if( enc!=SQLITE_UTF8 ){
  46722. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  46723. }
  46724. }else if( op==TK_UMINUS ) {
  46725. /* This branch happens for multiple negative signs. Ex: -(-5) */
  46726. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  46727. && pVal!=0
  46728. ){
  46729. sqlite3VdbeMemNumerify(pVal);
  46730. if( pVal->u.i==SMALLEST_INT64 ){
  46731. pVal->flags &= MEM_Int;
  46732. pVal->flags |= MEM_Real;
  46733. pVal->r = (double)LARGEST_INT64;
  46734. }else{
  46735. pVal->u.i = -pVal->u.i;
  46736. }
  46737. pVal->r = -pVal->r;
  46738. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  46739. }
  46740. }else if( op==TK_NULL ){
  46741. pVal = valueNew(db, pCtx);
  46742. if( pVal==0 ) goto no_mem;
  46743. }
  46744. #ifndef SQLITE_OMIT_BLOB_LITERAL
  46745. else if( op==TK_BLOB ){
  46746. int nVal;
  46747. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  46748. assert( pExpr->u.zToken[1]=='\'' );
  46749. pVal = valueNew(db, pCtx);
  46750. if( !pVal ) goto no_mem;
  46751. zVal = &pExpr->u.zToken[2];
  46752. nVal = sqlite3Strlen30(zVal)-1;
  46753. assert( zVal[nVal]=='\'' );
  46754. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  46755. 0, SQLITE_DYNAMIC);
  46756. }
  46757. #endif
  46758. if( pVal ){
  46759. sqlite3VdbeMemStoreType(pVal);
  46760. }
  46761. *ppVal = pVal;
  46762. return rc;
  46763. no_mem:
  46764. db->mallocFailed = 1;
  46765. sqlite3DbFree(db, zVal);
  46766. assert( *ppVal==0 );
  46767. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46768. if( pCtx==0 ) sqlite3ValueFree(pVal);
  46769. #else
  46770. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  46771. #endif
  46772. return SQLITE_NOMEM;
  46773. }
  46774. /*
  46775. ** Create a new sqlite3_value object, containing the value of pExpr.
  46776. **
  46777. ** This only works for very simple expressions that consist of one constant
  46778. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  46779. ** be converted directly into a value, then the value is allocated and
  46780. ** a pointer written to *ppVal. The caller is responsible for deallocating
  46781. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  46782. ** cannot be converted to a value, then *ppVal is set to NULL.
  46783. */
  46784. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  46785. sqlite3 *db, /* The database connection */
  46786. Expr *pExpr, /* The expression to evaluate */
  46787. u8 enc, /* Encoding to use */
  46788. u8 affinity, /* Affinity to use */
  46789. sqlite3_value **ppVal /* Write the new value here */
  46790. ){
  46791. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  46792. }
  46793. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  46794. /*
  46795. ** The implementation of the sqlite_record() function. This function accepts
  46796. ** a single argument of any type. The return value is a formatted database
  46797. ** record (a blob) containing the argument value.
  46798. **
  46799. ** This is used to convert the value stored in the 'sample' column of the
  46800. ** sqlite_stat3 table to the record format SQLite uses internally.
  46801. */
  46802. static void recordFunc(
  46803. sqlite3_context *context,
  46804. int argc,
  46805. sqlite3_value **argv
  46806. ){
  46807. const int file_format = 1;
  46808. int iSerial; /* Serial type */
  46809. int nSerial; /* Bytes of space for iSerial as varint */
  46810. int nVal; /* Bytes of space required for argv[0] */
  46811. int nRet;
  46812. sqlite3 *db;
  46813. u8 *aRet;
  46814. UNUSED_PARAMETER( argc );
  46815. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  46816. nSerial = sqlite3VarintLen(iSerial);
  46817. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  46818. db = sqlite3_context_db_handle(context);
  46819. nRet = 1 + nSerial + nVal;
  46820. aRet = sqlite3DbMallocRaw(db, nRet);
  46821. if( aRet==0 ){
  46822. sqlite3_result_error_nomem(context);
  46823. }else{
  46824. aRet[0] = nSerial+1;
  46825. sqlite3PutVarint(&aRet[1], iSerial);
  46826. sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
  46827. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  46828. sqlite3DbFree(db, aRet);
  46829. }
  46830. }
  46831. /*
  46832. ** Register built-in functions used to help read ANALYZE data.
  46833. */
  46834. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  46835. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  46836. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  46837. };
  46838. int i;
  46839. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  46840. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  46841. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  46842. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  46843. }
  46844. }
  46845. /*
  46846. ** This function is used to allocate and populate UnpackedRecord
  46847. ** structures intended to be compared against sample index keys stored
  46848. ** in the sqlite_stat4 table.
  46849. **
  46850. ** A single call to this function attempts to populates field iVal (leftmost
  46851. ** is 0 etc.) of the unpacked record with a value extracted from expression
  46852. ** pExpr. Extraction of values is possible if:
  46853. **
  46854. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  46855. **
  46856. ** * The expression is a bound variable, and this is a reprepare, or
  46857. **
  46858. ** * The sqlite3ValueFromExpr() function is able to extract a value
  46859. ** from the expression (i.e. the expression is a literal value).
  46860. **
  46861. ** If a value can be extracted, the affinity passed as the 5th argument
  46862. ** is applied to it before it is copied into the UnpackedRecord. Output
  46863. ** parameter *pbOk is set to true if a value is extracted, or false
  46864. ** otherwise.
  46865. **
  46866. ** When this function is called, *ppRec must either point to an object
  46867. ** allocated by an earlier call to this function, or must be NULL. If it
  46868. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  46869. ** is allocated (and *ppRec set to point to it) before returning.
  46870. **
  46871. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  46872. ** error if a value cannot be extracted from pExpr. If an error does
  46873. ** occur, an SQLite error code is returned.
  46874. */
  46875. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  46876. Parse *pParse, /* Parse context */
  46877. Index *pIdx, /* Index being probed */
  46878. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  46879. Expr *pExpr, /* The expression to extract a value from */
  46880. u8 affinity, /* Affinity to use */
  46881. int iVal, /* Array element to populate */
  46882. int *pbOk /* OUT: True if value was extracted */
  46883. ){
  46884. int rc = SQLITE_OK;
  46885. sqlite3_value *pVal = 0;
  46886. sqlite3 *db = pParse->db;
  46887. struct ValueNewStat4Ctx alloc;
  46888. alloc.pParse = pParse;
  46889. alloc.pIdx = pIdx;
  46890. alloc.ppRec = ppRec;
  46891. alloc.iVal = iVal;
  46892. /* Skip over any TK_COLLATE nodes */
  46893. pExpr = sqlite3ExprSkipCollate(pExpr);
  46894. if( !pExpr ){
  46895. pVal = valueNew(db, &alloc);
  46896. if( pVal ){
  46897. sqlite3VdbeMemSetNull((Mem*)pVal);
  46898. *pbOk = 1;
  46899. }
  46900. }else if( pExpr->op==TK_VARIABLE
  46901. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  46902. ){
  46903. Vdbe *v;
  46904. int iBindVar = pExpr->iColumn;
  46905. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  46906. if( (v = pParse->pReprepare)!=0 ){
  46907. pVal = valueNew(db, &alloc);
  46908. if( pVal ){
  46909. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  46910. if( rc==SQLITE_OK ){
  46911. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  46912. }
  46913. pVal->db = pParse->db;
  46914. *pbOk = 1;
  46915. sqlite3VdbeMemStoreType((Mem*)pVal);
  46916. }
  46917. }else{
  46918. *pbOk = 0;
  46919. }
  46920. }else{
  46921. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
  46922. *pbOk = (pVal!=0);
  46923. }
  46924. assert( pVal==0 || pVal->db==db );
  46925. return rc;
  46926. }
  46927. /*
  46928. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  46929. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  46930. ** the object.
  46931. */
  46932. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  46933. if( pRec ){
  46934. int i;
  46935. int nCol = pRec->pKeyInfo->nField+1;
  46936. Mem *aMem = pRec->aMem;
  46937. sqlite3 *db = aMem[0].db;
  46938. for(i=0; i<nCol; i++){
  46939. sqlite3DbFree(db, aMem[i].zMalloc);
  46940. }
  46941. sqlite3DbFree(db, pRec->pKeyInfo);
  46942. sqlite3DbFree(db, pRec);
  46943. }
  46944. }
  46945. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  46946. /*
  46947. ** Change the string value of an sqlite3_value object
  46948. */
  46949. SQLITE_PRIVATE void sqlite3ValueSetStr(
  46950. sqlite3_value *v, /* Value to be set */
  46951. int n, /* Length of string z */
  46952. const void *z, /* Text of the new string */
  46953. u8 enc, /* Encoding to use */
  46954. void (*xDel)(void*) /* Destructor for the string */
  46955. ){
  46956. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  46957. }
  46958. /*
  46959. ** Free an sqlite3_value object
  46960. */
  46961. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  46962. if( !v ) return;
  46963. sqlite3VdbeMemRelease((Mem *)v);
  46964. sqlite3DbFree(((Mem*)v)->db, v);
  46965. }
  46966. /*
  46967. ** Return the number of bytes in the sqlite3_value object assuming
  46968. ** that it uses the encoding "enc"
  46969. */
  46970. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  46971. Mem *p = (Mem*)pVal;
  46972. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  46973. if( p->flags & MEM_Zero ){
  46974. return p->n + p->u.nZero;
  46975. }else{
  46976. return p->n;
  46977. }
  46978. }
  46979. return 0;
  46980. }
  46981. /************** End of vdbemem.c *********************************************/
  46982. /************** Begin file vdbeaux.c *****************************************/
  46983. /*
  46984. ** 2003 September 6
  46985. **
  46986. ** The author disclaims copyright to this source code. In place of
  46987. ** a legal notice, here is a blessing:
  46988. **
  46989. ** May you do good and not evil.
  46990. ** May you find forgiveness for yourself and forgive others.
  46991. ** May you share freely, never taking more than you give.
  46992. **
  46993. *************************************************************************
  46994. ** This file contains code used for creating, destroying, and populating
  46995. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  46996. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  46997. ** But that file was getting too big so this subroutines were split out.
  46998. */
  46999. /*
  47000. ** Create a new virtual database engine.
  47001. */
  47002. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  47003. Vdbe *p;
  47004. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  47005. if( p==0 ) return 0;
  47006. p->db = db;
  47007. if( db->pVdbe ){
  47008. db->pVdbe->pPrev = p;
  47009. }
  47010. p->pNext = db->pVdbe;
  47011. p->pPrev = 0;
  47012. db->pVdbe = p;
  47013. p->magic = VDBE_MAGIC_INIT;
  47014. return p;
  47015. }
  47016. /*
  47017. ** Remember the SQL string for a prepared statement.
  47018. */
  47019. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  47020. assert( isPrepareV2==1 || isPrepareV2==0 );
  47021. if( p==0 ) return;
  47022. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  47023. if( !isPrepareV2 ) return;
  47024. #endif
  47025. assert( p->zSql==0 );
  47026. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  47027. p->isPrepareV2 = (u8)isPrepareV2;
  47028. }
  47029. /*
  47030. ** Return the SQL associated with a prepared statement
  47031. */
  47032. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  47033. Vdbe *p = (Vdbe *)pStmt;
  47034. return (p && p->isPrepareV2) ? p->zSql : 0;
  47035. }
  47036. /*
  47037. ** Swap all content between two VDBE structures.
  47038. */
  47039. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  47040. Vdbe tmp, *pTmp;
  47041. char *zTmp;
  47042. tmp = *pA;
  47043. *pA = *pB;
  47044. *pB = tmp;
  47045. pTmp = pA->pNext;
  47046. pA->pNext = pB->pNext;
  47047. pB->pNext = pTmp;
  47048. pTmp = pA->pPrev;
  47049. pA->pPrev = pB->pPrev;
  47050. pB->pPrev = pTmp;
  47051. zTmp = pA->zSql;
  47052. pA->zSql = pB->zSql;
  47053. pB->zSql = zTmp;
  47054. pB->isPrepareV2 = pA->isPrepareV2;
  47055. }
  47056. #ifdef SQLITE_DEBUG
  47057. /*
  47058. ** Turn tracing on or off
  47059. */
  47060. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  47061. p->trace = trace;
  47062. }
  47063. #endif
  47064. /*
  47065. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  47066. ** it was.
  47067. **
  47068. ** If an out-of-memory error occurs while resizing the array, return
  47069. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  47070. ** unchanged (this is so that any opcodes already allocated can be
  47071. ** correctly deallocated along with the rest of the Vdbe).
  47072. */
  47073. static int growOpArray(Vdbe *p){
  47074. VdbeOp *pNew;
  47075. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  47076. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  47077. if( pNew ){
  47078. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  47079. p->aOp = pNew;
  47080. }
  47081. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  47082. }
  47083. /*
  47084. ** Add a new instruction to the list of instructions current in the
  47085. ** VDBE. Return the address of the new instruction.
  47086. **
  47087. ** Parameters:
  47088. **
  47089. ** p Pointer to the VDBE
  47090. **
  47091. ** op The opcode for this instruction
  47092. **
  47093. ** p1, p2, p3 Operands
  47094. **
  47095. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  47096. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  47097. ** operand.
  47098. */
  47099. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  47100. int i;
  47101. VdbeOp *pOp;
  47102. i = p->nOp;
  47103. assert( p->magic==VDBE_MAGIC_INIT );
  47104. assert( op>0 && op<0xff );
  47105. if( p->nOpAlloc<=i ){
  47106. if( growOpArray(p) ){
  47107. return 1;
  47108. }
  47109. }
  47110. p->nOp++;
  47111. pOp = &p->aOp[i];
  47112. pOp->opcode = (u8)op;
  47113. pOp->p5 = 0;
  47114. pOp->p1 = p1;
  47115. pOp->p2 = p2;
  47116. pOp->p3 = p3;
  47117. pOp->p4.p = 0;
  47118. pOp->p4type = P4_NOTUSED;
  47119. #ifdef SQLITE_DEBUG
  47120. pOp->zComment = 0;
  47121. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  47122. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  47123. }
  47124. #endif
  47125. #ifdef VDBE_PROFILE
  47126. pOp->cycles = 0;
  47127. pOp->cnt = 0;
  47128. #endif
  47129. return i;
  47130. }
  47131. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  47132. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  47133. }
  47134. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  47135. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  47136. }
  47137. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  47138. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  47139. }
  47140. /*
  47141. ** Add an opcode that includes the p4 value as a pointer.
  47142. */
  47143. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  47144. Vdbe *p, /* Add the opcode to this VM */
  47145. int op, /* The new opcode */
  47146. int p1, /* The P1 operand */
  47147. int p2, /* The P2 operand */
  47148. int p3, /* The P3 operand */
  47149. const char *zP4, /* The P4 operand */
  47150. int p4type /* P4 operand type */
  47151. ){
  47152. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  47153. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  47154. return addr;
  47155. }
  47156. /*
  47157. ** Add an OP_ParseSchema opcode. This routine is broken out from
  47158. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  47159. ** as having been used.
  47160. **
  47161. ** The zWhere string must have been obtained from sqlite3_malloc().
  47162. ** This routine will take ownership of the allocated memory.
  47163. */
  47164. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  47165. int j;
  47166. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  47167. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  47168. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  47169. }
  47170. /*
  47171. ** Add an opcode that includes the p4 value as an integer.
  47172. */
  47173. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  47174. Vdbe *p, /* Add the opcode to this VM */
  47175. int op, /* The new opcode */
  47176. int p1, /* The P1 operand */
  47177. int p2, /* The P2 operand */
  47178. int p3, /* The P3 operand */
  47179. int p4 /* The P4 operand as an integer */
  47180. ){
  47181. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  47182. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  47183. return addr;
  47184. }
  47185. /*
  47186. ** Create a new symbolic label for an instruction that has yet to be
  47187. ** coded. The symbolic label is really just a negative number. The
  47188. ** label can be used as the P2 value of an operation. Later, when
  47189. ** the label is resolved to a specific address, the VDBE will scan
  47190. ** through its operation list and change all values of P2 which match
  47191. ** the label into the resolved address.
  47192. **
  47193. ** The VDBE knows that a P2 value is a label because labels are
  47194. ** always negative and P2 values are suppose to be non-negative.
  47195. ** Hence, a negative P2 value is a label that has yet to be resolved.
  47196. **
  47197. ** Zero is returned if a malloc() fails.
  47198. */
  47199. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  47200. int i = p->nLabel++;
  47201. assert( p->magic==VDBE_MAGIC_INIT );
  47202. if( (i & (i-1))==0 ){
  47203. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  47204. (i*2+1)*sizeof(p->aLabel[0]));
  47205. }
  47206. if( p->aLabel ){
  47207. p->aLabel[i] = -1;
  47208. }
  47209. return -1-i;
  47210. }
  47211. /*
  47212. ** Resolve label "x" to be the address of the next instruction to
  47213. ** be inserted. The parameter "x" must have been obtained from
  47214. ** a prior call to sqlite3VdbeMakeLabel().
  47215. */
  47216. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  47217. int j = -1-x;
  47218. assert( p->magic==VDBE_MAGIC_INIT );
  47219. assert( j<p->nLabel );
  47220. if( j>=0 && p->aLabel ){
  47221. p->aLabel[j] = p->nOp;
  47222. }
  47223. }
  47224. /*
  47225. ** Mark the VDBE as one that can only be run one time.
  47226. */
  47227. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  47228. p->runOnlyOnce = 1;
  47229. }
  47230. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  47231. /*
  47232. ** The following type and function are used to iterate through all opcodes
  47233. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  47234. ** invoke directly or indirectly. It should be used as follows:
  47235. **
  47236. ** Op *pOp;
  47237. ** VdbeOpIter sIter;
  47238. **
  47239. ** memset(&sIter, 0, sizeof(sIter));
  47240. ** sIter.v = v; // v is of type Vdbe*
  47241. ** while( (pOp = opIterNext(&sIter)) ){
  47242. ** // Do something with pOp
  47243. ** }
  47244. ** sqlite3DbFree(v->db, sIter.apSub);
  47245. **
  47246. */
  47247. typedef struct VdbeOpIter VdbeOpIter;
  47248. struct VdbeOpIter {
  47249. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  47250. SubProgram **apSub; /* Array of subprograms */
  47251. int nSub; /* Number of entries in apSub */
  47252. int iAddr; /* Address of next instruction to return */
  47253. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  47254. };
  47255. static Op *opIterNext(VdbeOpIter *p){
  47256. Vdbe *v = p->v;
  47257. Op *pRet = 0;
  47258. Op *aOp;
  47259. int nOp;
  47260. if( p->iSub<=p->nSub ){
  47261. if( p->iSub==0 ){
  47262. aOp = v->aOp;
  47263. nOp = v->nOp;
  47264. }else{
  47265. aOp = p->apSub[p->iSub-1]->aOp;
  47266. nOp = p->apSub[p->iSub-1]->nOp;
  47267. }
  47268. assert( p->iAddr<nOp );
  47269. pRet = &aOp[p->iAddr];
  47270. p->iAddr++;
  47271. if( p->iAddr==nOp ){
  47272. p->iSub++;
  47273. p->iAddr = 0;
  47274. }
  47275. if( pRet->p4type==P4_SUBPROGRAM ){
  47276. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  47277. int j;
  47278. for(j=0; j<p->nSub; j++){
  47279. if( p->apSub[j]==pRet->p4.pProgram ) break;
  47280. }
  47281. if( j==p->nSub ){
  47282. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  47283. if( !p->apSub ){
  47284. pRet = 0;
  47285. }else{
  47286. p->apSub[p->nSub++] = pRet->p4.pProgram;
  47287. }
  47288. }
  47289. }
  47290. }
  47291. return pRet;
  47292. }
  47293. /*
  47294. ** Check if the program stored in the VM associated with pParse may
  47295. ** throw an ABORT exception (causing the statement, but not entire transaction
  47296. ** to be rolled back). This condition is true if the main program or any
  47297. ** sub-programs contains any of the following:
  47298. **
  47299. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  47300. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  47301. ** * OP_Destroy
  47302. ** * OP_VUpdate
  47303. ** * OP_VRename
  47304. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  47305. **
  47306. ** Then check that the value of Parse.mayAbort is true if an
  47307. ** ABORT may be thrown, or false otherwise. Return true if it does
  47308. ** match, or false otherwise. This function is intended to be used as
  47309. ** part of an assert statement in the compiler. Similar to:
  47310. **
  47311. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  47312. */
  47313. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  47314. int hasAbort = 0;
  47315. Op *pOp;
  47316. VdbeOpIter sIter;
  47317. memset(&sIter, 0, sizeof(sIter));
  47318. sIter.v = v;
  47319. while( (pOp = opIterNext(&sIter))!=0 ){
  47320. int opcode = pOp->opcode;
  47321. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  47322. #ifndef SQLITE_OMIT_FOREIGN_KEY
  47323. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  47324. #endif
  47325. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  47326. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  47327. ){
  47328. hasAbort = 1;
  47329. break;
  47330. }
  47331. }
  47332. sqlite3DbFree(v->db, sIter.apSub);
  47333. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  47334. ** If malloc failed, then the while() loop above may not have iterated
  47335. ** through all opcodes and hasAbort may be set incorrectly. Return
  47336. ** true for this case to prevent the assert() in the callers frame
  47337. ** from failing. */
  47338. return ( v->db->mallocFailed || hasAbort==mayAbort );
  47339. }
  47340. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  47341. /*
  47342. ** Loop through the program looking for P2 values that are negative
  47343. ** on jump instructions. Each such value is a label. Resolve the
  47344. ** label by setting the P2 value to its correct non-zero value.
  47345. **
  47346. ** This routine is called once after all opcodes have been inserted.
  47347. **
  47348. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  47349. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  47350. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  47351. **
  47352. ** The Op.opflags field is set on all opcodes.
  47353. */
  47354. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  47355. int i;
  47356. int nMaxArgs = *pMaxFuncArgs;
  47357. Op *pOp;
  47358. int *aLabel = p->aLabel;
  47359. p->readOnly = 1;
  47360. p->bIsReader = 0;
  47361. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  47362. u8 opcode = pOp->opcode;
  47363. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  47364. ** cases from this switch! */
  47365. switch( opcode ){
  47366. case OP_Function:
  47367. case OP_AggStep: {
  47368. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  47369. break;
  47370. }
  47371. case OP_Transaction: {
  47372. if( pOp->p2!=0 ) p->readOnly = 0;
  47373. /* fall thru */
  47374. }
  47375. case OP_AutoCommit:
  47376. case OP_Savepoint: {
  47377. p->bIsReader = 1;
  47378. break;
  47379. }
  47380. #ifndef SQLITE_OMIT_WAL
  47381. case OP_Checkpoint:
  47382. #endif
  47383. case OP_Vacuum:
  47384. case OP_JournalMode: {
  47385. p->readOnly = 0;
  47386. p->bIsReader = 1;
  47387. break;
  47388. }
  47389. #ifndef SQLITE_OMIT_VIRTUALTABLE
  47390. case OP_VUpdate: {
  47391. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  47392. break;
  47393. }
  47394. case OP_VFilter: {
  47395. int n;
  47396. assert( p->nOp - i >= 3 );
  47397. assert( pOp[-1].opcode==OP_Integer );
  47398. n = pOp[-1].p1;
  47399. if( n>nMaxArgs ) nMaxArgs = n;
  47400. break;
  47401. }
  47402. #endif
  47403. case OP_Next:
  47404. case OP_SorterNext: {
  47405. pOp->p4.xAdvance = sqlite3BtreeNext;
  47406. pOp->p4type = P4_ADVANCE;
  47407. break;
  47408. }
  47409. case OP_Prev: {
  47410. pOp->p4.xAdvance = sqlite3BtreePrevious;
  47411. pOp->p4type = P4_ADVANCE;
  47412. break;
  47413. }
  47414. }
  47415. pOp->opflags = sqlite3OpcodeProperty[opcode];
  47416. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  47417. assert( -1-pOp->p2<p->nLabel );
  47418. pOp->p2 = aLabel[-1-pOp->p2];
  47419. }
  47420. }
  47421. sqlite3DbFree(p->db, p->aLabel);
  47422. p->aLabel = 0;
  47423. *pMaxFuncArgs = nMaxArgs;
  47424. assert( p->bIsReader!=0 || p->btreeMask==0 );
  47425. }
  47426. /*
  47427. ** Return the address of the next instruction to be inserted.
  47428. */
  47429. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  47430. assert( p->magic==VDBE_MAGIC_INIT );
  47431. return p->nOp;
  47432. }
  47433. /*
  47434. ** This function returns a pointer to the array of opcodes associated with
  47435. ** the Vdbe passed as the first argument. It is the callers responsibility
  47436. ** to arrange for the returned array to be eventually freed using the
  47437. ** vdbeFreeOpArray() function.
  47438. **
  47439. ** Before returning, *pnOp is set to the number of entries in the returned
  47440. ** array. Also, *pnMaxArg is set to the larger of its current value and
  47441. ** the number of entries in the Vdbe.apArg[] array required to execute the
  47442. ** returned program.
  47443. */
  47444. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  47445. VdbeOp *aOp = p->aOp;
  47446. assert( aOp && !p->db->mallocFailed );
  47447. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  47448. assert( p->btreeMask==0 );
  47449. resolveP2Values(p, pnMaxArg);
  47450. *pnOp = p->nOp;
  47451. p->aOp = 0;
  47452. return aOp;
  47453. }
  47454. /*
  47455. ** Add a whole list of operations to the operation stack. Return the
  47456. ** address of the first operation added.
  47457. */
  47458. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  47459. int addr;
  47460. assert( p->magic==VDBE_MAGIC_INIT );
  47461. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  47462. return 0;
  47463. }
  47464. addr = p->nOp;
  47465. if( ALWAYS(nOp>0) ){
  47466. int i;
  47467. VdbeOpList const *pIn = aOp;
  47468. for(i=0; i<nOp; i++, pIn++){
  47469. int p2 = pIn->p2;
  47470. VdbeOp *pOut = &p->aOp[i+addr];
  47471. pOut->opcode = pIn->opcode;
  47472. pOut->p1 = pIn->p1;
  47473. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  47474. pOut->p2 = addr + ADDR(p2);
  47475. }else{
  47476. pOut->p2 = p2;
  47477. }
  47478. pOut->p3 = pIn->p3;
  47479. pOut->p4type = P4_NOTUSED;
  47480. pOut->p4.p = 0;
  47481. pOut->p5 = 0;
  47482. #ifdef SQLITE_DEBUG
  47483. pOut->zComment = 0;
  47484. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  47485. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  47486. }
  47487. #endif
  47488. }
  47489. p->nOp += nOp;
  47490. }
  47491. return addr;
  47492. }
  47493. /*
  47494. ** Change the value of the P1 operand for a specific instruction.
  47495. ** This routine is useful when a large program is loaded from a
  47496. ** static array using sqlite3VdbeAddOpList but we want to make a
  47497. ** few minor changes to the program.
  47498. */
  47499. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  47500. assert( p!=0 );
  47501. if( ((u32)p->nOp)>addr ){
  47502. p->aOp[addr].p1 = val;
  47503. }
  47504. }
  47505. /*
  47506. ** Change the value of the P2 operand for a specific instruction.
  47507. ** This routine is useful for setting a jump destination.
  47508. */
  47509. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  47510. assert( p!=0 );
  47511. if( ((u32)p->nOp)>addr ){
  47512. p->aOp[addr].p2 = val;
  47513. }
  47514. }
  47515. /*
  47516. ** Change the value of the P3 operand for a specific instruction.
  47517. */
  47518. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  47519. assert( p!=0 );
  47520. if( ((u32)p->nOp)>addr ){
  47521. p->aOp[addr].p3 = val;
  47522. }
  47523. }
  47524. /*
  47525. ** Change the value of the P5 operand for the most recently
  47526. ** added operation.
  47527. */
  47528. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  47529. assert( p!=0 );
  47530. if( p->aOp ){
  47531. assert( p->nOp>0 );
  47532. p->aOp[p->nOp-1].p5 = val;
  47533. }
  47534. }
  47535. /*
  47536. ** Change the P2 operand of instruction addr so that it points to
  47537. ** the address of the next instruction to be coded.
  47538. */
  47539. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  47540. if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  47541. }
  47542. /*
  47543. ** If the input FuncDef structure is ephemeral, then free it. If
  47544. ** the FuncDef is not ephermal, then do nothing.
  47545. */
  47546. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  47547. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  47548. sqlite3DbFree(db, pDef);
  47549. }
  47550. }
  47551. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  47552. /*
  47553. ** Delete a P4 value if necessary.
  47554. */
  47555. static void freeP4(sqlite3 *db, int p4type, void *p4){
  47556. if( p4 ){
  47557. assert( db );
  47558. switch( p4type ){
  47559. case P4_REAL:
  47560. case P4_INT64:
  47561. case P4_DYNAMIC:
  47562. case P4_KEYINFO:
  47563. case P4_INTARRAY:
  47564. case P4_KEYINFO_HANDOFF: {
  47565. sqlite3DbFree(db, p4);
  47566. break;
  47567. }
  47568. case P4_MPRINTF: {
  47569. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  47570. break;
  47571. }
  47572. case P4_FUNCDEF: {
  47573. freeEphemeralFunction(db, (FuncDef*)p4);
  47574. break;
  47575. }
  47576. case P4_MEM: {
  47577. if( db->pnBytesFreed==0 ){
  47578. sqlite3ValueFree((sqlite3_value*)p4);
  47579. }else{
  47580. Mem *p = (Mem*)p4;
  47581. sqlite3DbFree(db, p->zMalloc);
  47582. sqlite3DbFree(db, p);
  47583. }
  47584. break;
  47585. }
  47586. case P4_VTAB : {
  47587. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  47588. break;
  47589. }
  47590. }
  47591. }
  47592. }
  47593. /*
  47594. ** Free the space allocated for aOp and any p4 values allocated for the
  47595. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  47596. ** nOp entries.
  47597. */
  47598. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  47599. if( aOp ){
  47600. Op *pOp;
  47601. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  47602. freeP4(db, pOp->p4type, pOp->p4.p);
  47603. #ifdef SQLITE_DEBUG
  47604. sqlite3DbFree(db, pOp->zComment);
  47605. #endif
  47606. }
  47607. }
  47608. sqlite3DbFree(db, aOp);
  47609. }
  47610. /*
  47611. ** Link the SubProgram object passed as the second argument into the linked
  47612. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  47613. ** objects when the VM is no longer required.
  47614. */
  47615. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  47616. p->pNext = pVdbe->pProgram;
  47617. pVdbe->pProgram = p;
  47618. }
  47619. /*
  47620. ** Change the opcode at addr into OP_Noop
  47621. */
  47622. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  47623. if( p->aOp ){
  47624. VdbeOp *pOp = &p->aOp[addr];
  47625. sqlite3 *db = p->db;
  47626. freeP4(db, pOp->p4type, pOp->p4.p);
  47627. memset(pOp, 0, sizeof(pOp[0]));
  47628. pOp->opcode = OP_Noop;
  47629. }
  47630. }
  47631. /*
  47632. ** Change the value of the P4 operand for a specific instruction.
  47633. ** This routine is useful when a large program is loaded from a
  47634. ** static array using sqlite3VdbeAddOpList but we want to make a
  47635. ** few minor changes to the program.
  47636. **
  47637. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  47638. ** the string is made into memory obtained from sqlite3_malloc().
  47639. ** A value of n==0 means copy bytes of zP4 up to and including the
  47640. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  47641. **
  47642. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  47643. ** A copy is made of the KeyInfo structure into memory obtained from
  47644. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  47645. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  47646. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  47647. ** caller should not free the allocation, it will be freed when the Vdbe is
  47648. ** finalized.
  47649. **
  47650. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  47651. ** to a string or structure that is guaranteed to exist for the lifetime of
  47652. ** the Vdbe. In these cases we can just copy the pointer.
  47653. **
  47654. ** If addr<0 then change P4 on the most recently inserted instruction.
  47655. */
  47656. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  47657. Op *pOp;
  47658. sqlite3 *db;
  47659. assert( p!=0 );
  47660. db = p->db;
  47661. assert( p->magic==VDBE_MAGIC_INIT );
  47662. if( p->aOp==0 || db->mallocFailed ){
  47663. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  47664. freeP4(db, n, (void*)*(char**)&zP4);
  47665. }
  47666. return;
  47667. }
  47668. assert( p->nOp>0 );
  47669. assert( addr<p->nOp );
  47670. if( addr<0 ){
  47671. addr = p->nOp - 1;
  47672. }
  47673. pOp = &p->aOp[addr];
  47674. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  47675. freeP4(db, pOp->p4type, pOp->p4.p);
  47676. pOp->p4.p = 0;
  47677. if( n==P4_INT32 ){
  47678. /* Note: this cast is safe, because the origin data point was an int
  47679. ** that was cast to a (const char *). */
  47680. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  47681. pOp->p4type = P4_INT32;
  47682. }else if( zP4==0 ){
  47683. pOp->p4.p = 0;
  47684. pOp->p4type = P4_NOTUSED;
  47685. }else if( n==P4_KEYINFO ){
  47686. KeyInfo *pOrig, *pNew;
  47687. pOrig = (KeyInfo*)zP4;
  47688. pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
  47689. if( pNew ){
  47690. memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
  47691. memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
  47692. pOp->p4type = P4_KEYINFO;
  47693. }else{
  47694. p->db->mallocFailed = 1;
  47695. pOp->p4type = P4_NOTUSED;
  47696. }
  47697. }else if( n==P4_KEYINFO_HANDOFF ){
  47698. pOp->p4.p = (void*)zP4;
  47699. pOp->p4type = P4_KEYINFO;
  47700. }else if( n==P4_VTAB ){
  47701. pOp->p4.p = (void*)zP4;
  47702. pOp->p4type = P4_VTAB;
  47703. sqlite3VtabLock((VTable *)zP4);
  47704. assert( ((VTable *)zP4)->db==p->db );
  47705. }else if( n<0 ){
  47706. pOp->p4.p = (void*)zP4;
  47707. pOp->p4type = (signed char)n;
  47708. }else{
  47709. if( n==0 ) n = sqlite3Strlen30(zP4);
  47710. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  47711. pOp->p4type = P4_DYNAMIC;
  47712. }
  47713. }
  47714. #ifndef NDEBUG
  47715. /*
  47716. ** Change the comment on the most recently coded instruction. Or
  47717. ** insert a No-op and add the comment to that new instruction. This
  47718. ** makes the code easier to read during debugging. None of this happens
  47719. ** in a production build.
  47720. */
  47721. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  47722. assert( p->nOp>0 || p->aOp==0 );
  47723. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  47724. if( p->nOp ){
  47725. assert( p->aOp );
  47726. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  47727. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  47728. }
  47729. }
  47730. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  47731. va_list ap;
  47732. if( p ){
  47733. va_start(ap, zFormat);
  47734. vdbeVComment(p, zFormat, ap);
  47735. va_end(ap);
  47736. }
  47737. }
  47738. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  47739. va_list ap;
  47740. if( p ){
  47741. sqlite3VdbeAddOp0(p, OP_Noop);
  47742. va_start(ap, zFormat);
  47743. vdbeVComment(p, zFormat, ap);
  47744. va_end(ap);
  47745. }
  47746. }
  47747. #endif /* NDEBUG */
  47748. /*
  47749. ** Return the opcode for a given address. If the address is -1, then
  47750. ** return the most recently inserted opcode.
  47751. **
  47752. ** If a memory allocation error has occurred prior to the calling of this
  47753. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  47754. ** is readable but not writable, though it is cast to a writable value.
  47755. ** The return of a dummy opcode allows the call to continue functioning
  47756. ** after a OOM fault without having to check to see if the return from
  47757. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  47758. ** dummy will never be written to. This is verified by code inspection and
  47759. ** by running with Valgrind.
  47760. **
  47761. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  47762. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  47763. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  47764. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  47765. ** having to double-check to make sure that the result is non-negative. But
  47766. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  47767. ** check the value of p->nOp-1 before continuing.
  47768. */
  47769. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  47770. /* C89 specifies that the constant "dummy" will be initialized to all
  47771. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  47772. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  47773. assert( p->magic==VDBE_MAGIC_INIT );
  47774. if( addr<0 ){
  47775. #ifdef SQLITE_OMIT_TRACE
  47776. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  47777. #endif
  47778. addr = p->nOp - 1;
  47779. }
  47780. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  47781. if( p->db->mallocFailed ){
  47782. return (VdbeOp*)&dummy;
  47783. }else{
  47784. return &p->aOp[addr];
  47785. }
  47786. }
  47787. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  47788. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  47789. /*
  47790. ** Compute a string that describes the P4 parameter for an opcode.
  47791. ** Use zTemp for any required temporary buffer space.
  47792. */
  47793. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  47794. char *zP4 = zTemp;
  47795. assert( nTemp>=20 );
  47796. switch( pOp->p4type ){
  47797. case P4_KEYINFO_STATIC:
  47798. case P4_KEYINFO: {
  47799. int i, j;
  47800. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  47801. assert( pKeyInfo->aSortOrder!=0 );
  47802. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  47803. i = sqlite3Strlen30(zTemp);
  47804. for(j=0; j<pKeyInfo->nField; j++){
  47805. CollSeq *pColl = pKeyInfo->aColl[j];
  47806. const char *zColl = pColl ? pColl->zName : "nil";
  47807. int n = sqlite3Strlen30(zColl);
  47808. if( i+n>nTemp-6 ){
  47809. memcpy(&zTemp[i],",...",4);
  47810. break;
  47811. }
  47812. zTemp[i++] = ',';
  47813. if( pKeyInfo->aSortOrder[j] ){
  47814. zTemp[i++] = '-';
  47815. }
  47816. memcpy(&zTemp[i], zColl, n+1);
  47817. i += n;
  47818. }
  47819. zTemp[i++] = ')';
  47820. zTemp[i] = 0;
  47821. assert( i<nTemp );
  47822. break;
  47823. }
  47824. case P4_COLLSEQ: {
  47825. CollSeq *pColl = pOp->p4.pColl;
  47826. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  47827. break;
  47828. }
  47829. case P4_FUNCDEF: {
  47830. FuncDef *pDef = pOp->p4.pFunc;
  47831. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  47832. break;
  47833. }
  47834. case P4_INT64: {
  47835. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  47836. break;
  47837. }
  47838. case P4_INT32: {
  47839. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  47840. break;
  47841. }
  47842. case P4_REAL: {
  47843. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  47844. break;
  47845. }
  47846. case P4_MEM: {
  47847. Mem *pMem = pOp->p4.pMem;
  47848. if( pMem->flags & MEM_Str ){
  47849. zP4 = pMem->z;
  47850. }else if( pMem->flags & MEM_Int ){
  47851. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  47852. }else if( pMem->flags & MEM_Real ){
  47853. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  47854. }else if( pMem->flags & MEM_Null ){
  47855. sqlite3_snprintf(nTemp, zTemp, "NULL");
  47856. }else{
  47857. assert( pMem->flags & MEM_Blob );
  47858. zP4 = "(blob)";
  47859. }
  47860. break;
  47861. }
  47862. #ifndef SQLITE_OMIT_VIRTUALTABLE
  47863. case P4_VTAB: {
  47864. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  47865. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  47866. break;
  47867. }
  47868. #endif
  47869. case P4_INTARRAY: {
  47870. sqlite3_snprintf(nTemp, zTemp, "intarray");
  47871. break;
  47872. }
  47873. case P4_SUBPROGRAM: {
  47874. sqlite3_snprintf(nTemp, zTemp, "program");
  47875. break;
  47876. }
  47877. case P4_ADVANCE: {
  47878. zTemp[0] = 0;
  47879. break;
  47880. }
  47881. default: {
  47882. zP4 = pOp->p4.z;
  47883. if( zP4==0 ){
  47884. zP4 = zTemp;
  47885. zTemp[0] = 0;
  47886. }
  47887. }
  47888. }
  47889. assert( zP4!=0 );
  47890. return zP4;
  47891. }
  47892. #endif
  47893. /*
  47894. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  47895. **
  47896. ** The prepared statements need to know in advance the complete set of
  47897. ** attached databases that will be use. A mask of these databases
  47898. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  47899. ** p->btreeMask of databases that will require a lock.
  47900. */
  47901. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  47902. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  47903. assert( i<(int)sizeof(p->btreeMask)*8 );
  47904. p->btreeMask |= ((yDbMask)1)<<i;
  47905. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  47906. p->lockMask |= ((yDbMask)1)<<i;
  47907. }
  47908. }
  47909. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  47910. /*
  47911. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  47912. ** this routine obtains the mutex associated with each BtShared structure
  47913. ** that may be accessed by the VM passed as an argument. In doing so it also
  47914. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  47915. ** that the correct busy-handler callback is invoked if required.
  47916. **
  47917. ** If SQLite is not threadsafe but does support shared-cache mode, then
  47918. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  47919. ** of all of BtShared structures accessible via the database handle
  47920. ** associated with the VM.
  47921. **
  47922. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  47923. ** function is a no-op.
  47924. **
  47925. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  47926. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  47927. ** corresponding to btrees that use shared cache. Then the runtime of
  47928. ** this routine is N*N. But as N is rarely more than 1, this should not
  47929. ** be a problem.
  47930. */
  47931. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  47932. int i;
  47933. yDbMask mask;
  47934. sqlite3 *db;
  47935. Db *aDb;
  47936. int nDb;
  47937. if( p->lockMask==0 ) return; /* The common case */
  47938. db = p->db;
  47939. aDb = db->aDb;
  47940. nDb = db->nDb;
  47941. for(i=0, mask=1; i<nDb; i++, mask += mask){
  47942. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  47943. sqlite3BtreeEnter(aDb[i].pBt);
  47944. }
  47945. }
  47946. }
  47947. #endif
  47948. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  47949. /*
  47950. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  47951. */
  47952. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  47953. int i;
  47954. yDbMask mask;
  47955. sqlite3 *db;
  47956. Db *aDb;
  47957. int nDb;
  47958. if( p->lockMask==0 ) return; /* The common case */
  47959. db = p->db;
  47960. aDb = db->aDb;
  47961. nDb = db->nDb;
  47962. for(i=0, mask=1; i<nDb; i++, mask += mask){
  47963. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  47964. sqlite3BtreeLeave(aDb[i].pBt);
  47965. }
  47966. }
  47967. }
  47968. #endif
  47969. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  47970. /*
  47971. ** Print a single opcode. This routine is used for debugging only.
  47972. */
  47973. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  47974. char *zP4;
  47975. char zPtr[50];
  47976. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  47977. if( pOut==0 ) pOut = stdout;
  47978. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  47979. fprintf(pOut, zFormat1, pc,
  47980. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  47981. #ifdef SQLITE_DEBUG
  47982. pOp->zComment ? pOp->zComment : ""
  47983. #else
  47984. ""
  47985. #endif
  47986. );
  47987. fflush(pOut);
  47988. }
  47989. #endif
  47990. /*
  47991. ** Release an array of N Mem elements
  47992. */
  47993. static void releaseMemArray(Mem *p, int N){
  47994. if( p && N ){
  47995. Mem *pEnd;
  47996. sqlite3 *db = p->db;
  47997. u8 malloc_failed = db->mallocFailed;
  47998. if( db->pnBytesFreed ){
  47999. for(pEnd=&p[N]; p<pEnd; p++){
  48000. sqlite3DbFree(db, p->zMalloc);
  48001. }
  48002. return;
  48003. }
  48004. for(pEnd=&p[N]; p<pEnd; p++){
  48005. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  48006. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  48007. ** that takes advantage of the fact that the memory cell value is
  48008. ** being set to NULL after releasing any dynamic resources.
  48009. **
  48010. ** The justification for duplicating code is that according to
  48011. ** callgrind, this causes a certain test case to hit the CPU 4.7
  48012. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  48013. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  48014. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  48015. ** with no indexes using a single prepared INSERT statement, bind()
  48016. ** and reset(). Inserts are grouped into a transaction.
  48017. */
  48018. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  48019. sqlite3VdbeMemRelease(p);
  48020. }else if( p->zMalloc ){
  48021. sqlite3DbFree(db, p->zMalloc);
  48022. p->zMalloc = 0;
  48023. }
  48024. p->flags = MEM_Invalid;
  48025. }
  48026. db->mallocFailed = malloc_failed;
  48027. }
  48028. }
  48029. /*
  48030. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  48031. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  48032. */
  48033. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  48034. int i;
  48035. Mem *aMem = VdbeFrameMem(p);
  48036. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  48037. for(i=0; i<p->nChildCsr; i++){
  48038. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  48039. }
  48040. releaseMemArray(aMem, p->nChildMem);
  48041. sqlite3DbFree(p->v->db, p);
  48042. }
  48043. #ifndef SQLITE_OMIT_EXPLAIN
  48044. /*
  48045. ** Give a listing of the program in the virtual machine.
  48046. **
  48047. ** The interface is the same as sqlite3VdbeExec(). But instead of
  48048. ** running the code, it invokes the callback once for each instruction.
  48049. ** This feature is used to implement "EXPLAIN".
  48050. **
  48051. ** When p->explain==1, each instruction is listed. When
  48052. ** p->explain==2, only OP_Explain instructions are listed and these
  48053. ** are shown in a different format. p->explain==2 is used to implement
  48054. ** EXPLAIN QUERY PLAN.
  48055. **
  48056. ** When p->explain==1, first the main program is listed, then each of
  48057. ** the trigger subprograms are listed one by one.
  48058. */
  48059. SQLITE_PRIVATE int sqlite3VdbeList(
  48060. Vdbe *p /* The VDBE */
  48061. ){
  48062. int nRow; /* Stop when row count reaches this */
  48063. int nSub = 0; /* Number of sub-vdbes seen so far */
  48064. SubProgram **apSub = 0; /* Array of sub-vdbes */
  48065. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  48066. sqlite3 *db = p->db; /* The database connection */
  48067. int i; /* Loop counter */
  48068. int rc = SQLITE_OK; /* Return code */
  48069. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  48070. assert( p->explain );
  48071. assert( p->magic==VDBE_MAGIC_RUN );
  48072. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  48073. /* Even though this opcode does not use dynamic strings for
  48074. ** the result, result columns may become dynamic if the user calls
  48075. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  48076. */
  48077. releaseMemArray(pMem, 8);
  48078. p->pResultSet = 0;
  48079. if( p->rc==SQLITE_NOMEM ){
  48080. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  48081. ** sqlite3_column_text16() failed. */
  48082. db->mallocFailed = 1;
  48083. return SQLITE_ERROR;
  48084. }
  48085. /* When the number of output rows reaches nRow, that means the
  48086. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  48087. ** nRow is the sum of the number of rows in the main program, plus
  48088. ** the sum of the number of rows in all trigger subprograms encountered
  48089. ** so far. The nRow value will increase as new trigger subprograms are
  48090. ** encountered, but p->pc will eventually catch up to nRow.
  48091. */
  48092. nRow = p->nOp;
  48093. if( p->explain==1 ){
  48094. /* The first 8 memory cells are used for the result set. So we will
  48095. ** commandeer the 9th cell to use as storage for an array of pointers
  48096. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  48097. ** cells. */
  48098. assert( p->nMem>9 );
  48099. pSub = &p->aMem[9];
  48100. if( pSub->flags&MEM_Blob ){
  48101. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  48102. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  48103. nSub = pSub->n/sizeof(Vdbe*);
  48104. apSub = (SubProgram **)pSub->z;
  48105. }
  48106. for(i=0; i<nSub; i++){
  48107. nRow += apSub[i]->nOp;
  48108. }
  48109. }
  48110. do{
  48111. i = p->pc++;
  48112. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  48113. if( i>=nRow ){
  48114. p->rc = SQLITE_OK;
  48115. rc = SQLITE_DONE;
  48116. }else if( db->u1.isInterrupted ){
  48117. p->rc = SQLITE_INTERRUPT;
  48118. rc = SQLITE_ERROR;
  48119. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  48120. }else{
  48121. char *z;
  48122. Op *pOp;
  48123. if( i<p->nOp ){
  48124. /* The output line number is small enough that we are still in the
  48125. ** main program. */
  48126. pOp = &p->aOp[i];
  48127. }else{
  48128. /* We are currently listing subprograms. Figure out which one and
  48129. ** pick up the appropriate opcode. */
  48130. int j;
  48131. i -= p->nOp;
  48132. for(j=0; i>=apSub[j]->nOp; j++){
  48133. i -= apSub[j]->nOp;
  48134. }
  48135. pOp = &apSub[j]->aOp[i];
  48136. }
  48137. if( p->explain==1 ){
  48138. pMem->flags = MEM_Int;
  48139. pMem->type = SQLITE_INTEGER;
  48140. pMem->u.i = i; /* Program counter */
  48141. pMem++;
  48142. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  48143. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  48144. assert( pMem->z!=0 );
  48145. pMem->n = sqlite3Strlen30(pMem->z);
  48146. pMem->type = SQLITE_TEXT;
  48147. pMem->enc = SQLITE_UTF8;
  48148. pMem++;
  48149. /* When an OP_Program opcode is encounter (the only opcode that has
  48150. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  48151. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  48152. ** has not already been seen.
  48153. */
  48154. if( pOp->p4type==P4_SUBPROGRAM ){
  48155. int nByte = (nSub+1)*sizeof(SubProgram*);
  48156. int j;
  48157. for(j=0; j<nSub; j++){
  48158. if( apSub[j]==pOp->p4.pProgram ) break;
  48159. }
  48160. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  48161. apSub = (SubProgram **)pSub->z;
  48162. apSub[nSub++] = pOp->p4.pProgram;
  48163. pSub->flags |= MEM_Blob;
  48164. pSub->n = nSub*sizeof(SubProgram*);
  48165. }
  48166. }
  48167. }
  48168. pMem->flags = MEM_Int;
  48169. pMem->u.i = pOp->p1; /* P1 */
  48170. pMem->type = SQLITE_INTEGER;
  48171. pMem++;
  48172. pMem->flags = MEM_Int;
  48173. pMem->u.i = pOp->p2; /* P2 */
  48174. pMem->type = SQLITE_INTEGER;
  48175. pMem++;
  48176. pMem->flags = MEM_Int;
  48177. pMem->u.i = pOp->p3; /* P3 */
  48178. pMem->type = SQLITE_INTEGER;
  48179. pMem++;
  48180. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  48181. assert( p->db->mallocFailed );
  48182. return SQLITE_ERROR;
  48183. }
  48184. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  48185. z = displayP4(pOp, pMem->z, 32);
  48186. if( z!=pMem->z ){
  48187. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  48188. }else{
  48189. assert( pMem->z!=0 );
  48190. pMem->n = sqlite3Strlen30(pMem->z);
  48191. pMem->enc = SQLITE_UTF8;
  48192. }
  48193. pMem->type = SQLITE_TEXT;
  48194. pMem++;
  48195. if( p->explain==1 ){
  48196. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  48197. assert( p->db->mallocFailed );
  48198. return SQLITE_ERROR;
  48199. }
  48200. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  48201. pMem->n = 2;
  48202. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  48203. pMem->type = SQLITE_TEXT;
  48204. pMem->enc = SQLITE_UTF8;
  48205. pMem++;
  48206. #ifdef SQLITE_DEBUG
  48207. if( pOp->zComment ){
  48208. pMem->flags = MEM_Str|MEM_Term;
  48209. pMem->z = pOp->zComment;
  48210. pMem->n = sqlite3Strlen30(pMem->z);
  48211. pMem->enc = SQLITE_UTF8;
  48212. pMem->type = SQLITE_TEXT;
  48213. }else
  48214. #endif
  48215. {
  48216. pMem->flags = MEM_Null; /* Comment */
  48217. pMem->type = SQLITE_NULL;
  48218. }
  48219. }
  48220. p->nResColumn = 8 - 4*(p->explain-1);
  48221. p->pResultSet = &p->aMem[1];
  48222. p->rc = SQLITE_OK;
  48223. rc = SQLITE_ROW;
  48224. }
  48225. return rc;
  48226. }
  48227. #endif /* SQLITE_OMIT_EXPLAIN */
  48228. #ifdef SQLITE_DEBUG
  48229. /*
  48230. ** Print the SQL that was used to generate a VDBE program.
  48231. */
  48232. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  48233. int nOp = p->nOp;
  48234. VdbeOp *pOp;
  48235. if( nOp<1 ) return;
  48236. pOp = &p->aOp[0];
  48237. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  48238. const char *z = pOp->p4.z;
  48239. while( sqlite3Isspace(*z) ) z++;
  48240. printf("SQL: [%s]\n", z);
  48241. }
  48242. }
  48243. #endif
  48244. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  48245. /*
  48246. ** Print an IOTRACE message showing SQL content.
  48247. */
  48248. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  48249. int nOp = p->nOp;
  48250. VdbeOp *pOp;
  48251. if( sqlite3IoTrace==0 ) return;
  48252. if( nOp<1 ) return;
  48253. pOp = &p->aOp[0];
  48254. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  48255. int i, j;
  48256. char z[1000];
  48257. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  48258. for(i=0; sqlite3Isspace(z[i]); i++){}
  48259. for(j=0; z[i]; i++){
  48260. if( sqlite3Isspace(z[i]) ){
  48261. if( z[i-1]!=' ' ){
  48262. z[j++] = ' ';
  48263. }
  48264. }else{
  48265. z[j++] = z[i];
  48266. }
  48267. }
  48268. z[j] = 0;
  48269. sqlite3IoTrace("SQL %s\n", z);
  48270. }
  48271. }
  48272. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  48273. /*
  48274. ** Allocate space from a fixed size buffer and return a pointer to
  48275. ** that space. If insufficient space is available, return NULL.
  48276. **
  48277. ** The pBuf parameter is the initial value of a pointer which will
  48278. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  48279. ** NULL, it means that memory space has already been allocated and that
  48280. ** this routine should not allocate any new memory. When pBuf is not
  48281. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  48282. ** is NULL.
  48283. **
  48284. ** nByte is the number of bytes of space needed.
  48285. **
  48286. ** *ppFrom points to available space and pEnd points to the end of the
  48287. ** available space. When space is allocated, *ppFrom is advanced past
  48288. ** the end of the allocated space.
  48289. **
  48290. ** *pnByte is a counter of the number of bytes of space that have failed
  48291. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  48292. ** request, then increment *pnByte by the amount of the request.
  48293. */
  48294. static void *allocSpace(
  48295. void *pBuf, /* Where return pointer will be stored */
  48296. int nByte, /* Number of bytes to allocate */
  48297. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  48298. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  48299. int *pnByte /* If allocation cannot be made, increment *pnByte */
  48300. ){
  48301. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  48302. if( pBuf ) return pBuf;
  48303. nByte = ROUND8(nByte);
  48304. if( &(*ppFrom)[nByte] <= pEnd ){
  48305. pBuf = (void*)*ppFrom;
  48306. *ppFrom += nByte;
  48307. }else{
  48308. *pnByte += nByte;
  48309. }
  48310. return pBuf;
  48311. }
  48312. /*
  48313. ** Rewind the VDBE back to the beginning in preparation for
  48314. ** running it.
  48315. */
  48316. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  48317. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  48318. int i;
  48319. #endif
  48320. assert( p!=0 );
  48321. assert( p->magic==VDBE_MAGIC_INIT );
  48322. /* There should be at least one opcode.
  48323. */
  48324. assert( p->nOp>0 );
  48325. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  48326. p->magic = VDBE_MAGIC_RUN;
  48327. #ifdef SQLITE_DEBUG
  48328. for(i=1; i<p->nMem; i++){
  48329. assert( p->aMem[i].db==p->db );
  48330. }
  48331. #endif
  48332. p->pc = -1;
  48333. p->rc = SQLITE_OK;
  48334. p->errorAction = OE_Abort;
  48335. p->magic = VDBE_MAGIC_RUN;
  48336. p->nChange = 0;
  48337. p->cacheCtr = 1;
  48338. p->minWriteFileFormat = 255;
  48339. p->iStatement = 0;
  48340. p->nFkConstraint = 0;
  48341. #ifdef VDBE_PROFILE
  48342. for(i=0; i<p->nOp; i++){
  48343. p->aOp[i].cnt = 0;
  48344. p->aOp[i].cycles = 0;
  48345. }
  48346. #endif
  48347. }
  48348. /*
  48349. ** Prepare a virtual machine for execution for the first time after
  48350. ** creating the virtual machine. This involves things such
  48351. ** as allocating stack space and initializing the program counter.
  48352. ** After the VDBE has be prepped, it can be executed by one or more
  48353. ** calls to sqlite3VdbeExec().
  48354. **
  48355. ** This function may be called exact once on a each virtual machine.
  48356. ** After this routine is called the VM has been "packaged" and is ready
  48357. ** to run. After this routine is called, futher calls to
  48358. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  48359. ** the Vdbe from the Parse object that helped generate it so that the
  48360. ** the Vdbe becomes an independent entity and the Parse object can be
  48361. ** destroyed.
  48362. **
  48363. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  48364. ** to its initial state after it has been run.
  48365. */
  48366. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  48367. Vdbe *p, /* The VDBE */
  48368. Parse *pParse /* Parsing context */
  48369. ){
  48370. sqlite3 *db; /* The database connection */
  48371. int nVar; /* Number of parameters */
  48372. int nMem; /* Number of VM memory registers */
  48373. int nCursor; /* Number of cursors required */
  48374. int nArg; /* Number of arguments in subprograms */
  48375. int nOnce; /* Number of OP_Once instructions */
  48376. int n; /* Loop counter */
  48377. u8 *zCsr; /* Memory available for allocation */
  48378. u8 *zEnd; /* First byte past allocated memory */
  48379. int nByte; /* How much extra memory is needed */
  48380. assert( p!=0 );
  48381. assert( p->nOp>0 );
  48382. assert( pParse!=0 );
  48383. assert( p->magic==VDBE_MAGIC_INIT );
  48384. db = p->db;
  48385. assert( db->mallocFailed==0 );
  48386. nVar = pParse->nVar;
  48387. nMem = pParse->nMem;
  48388. nCursor = pParse->nTab;
  48389. nArg = pParse->nMaxArg;
  48390. nOnce = pParse->nOnce;
  48391. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  48392. /* For each cursor required, also allocate a memory cell. Memory
  48393. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  48394. ** the vdbe program. Instead they are used to allocate space for
  48395. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  48396. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  48397. ** stores the blob of memory associated with cursor 1, etc.
  48398. **
  48399. ** See also: allocateCursor().
  48400. */
  48401. nMem += nCursor;
  48402. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  48403. ** an array to marshal SQL function arguments in.
  48404. */
  48405. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  48406. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  48407. resolveP2Values(p, &nArg);
  48408. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  48409. if( pParse->explain && nMem<10 ){
  48410. nMem = 10;
  48411. }
  48412. memset(zCsr, 0, zEnd-zCsr);
  48413. zCsr += (zCsr - (u8*)0)&7;
  48414. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  48415. p->expired = 0;
  48416. /* Memory for registers, parameters, cursor, etc, is allocated in two
  48417. ** passes. On the first pass, we try to reuse unused space at the
  48418. ** end of the opcode array. If we are unable to satisfy all memory
  48419. ** requirements by reusing the opcode array tail, then the second
  48420. ** pass will fill in the rest using a fresh allocation.
  48421. **
  48422. ** This two-pass approach that reuses as much memory as possible from
  48423. ** the leftover space at the end of the opcode array can significantly
  48424. ** reduce the amount of memory held by a prepared statement.
  48425. */
  48426. do {
  48427. nByte = 0;
  48428. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  48429. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  48430. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  48431. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  48432. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  48433. &zCsr, zEnd, &nByte);
  48434. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  48435. if( nByte ){
  48436. p->pFree = sqlite3DbMallocZero(db, nByte);
  48437. }
  48438. zCsr = p->pFree;
  48439. zEnd = &zCsr[nByte];
  48440. }while( nByte && !db->mallocFailed );
  48441. p->nCursor = nCursor;
  48442. p->nOnceFlag = nOnce;
  48443. if( p->aVar ){
  48444. p->nVar = (ynVar)nVar;
  48445. for(n=0; n<nVar; n++){
  48446. p->aVar[n].flags = MEM_Null;
  48447. p->aVar[n].db = db;
  48448. }
  48449. }
  48450. if( p->azVar ){
  48451. p->nzVar = pParse->nzVar;
  48452. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  48453. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  48454. }
  48455. if( p->aMem ){
  48456. p->aMem--; /* aMem[] goes from 1..nMem */
  48457. p->nMem = nMem; /* not from 0..nMem-1 */
  48458. for(n=1; n<=nMem; n++){
  48459. p->aMem[n].flags = MEM_Invalid;
  48460. p->aMem[n].db = db;
  48461. }
  48462. }
  48463. p->explain = pParse->explain;
  48464. sqlite3VdbeRewind(p);
  48465. }
  48466. /*
  48467. ** Close a VDBE cursor and release all the resources that cursor
  48468. ** happens to hold.
  48469. */
  48470. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  48471. if( pCx==0 ){
  48472. return;
  48473. }
  48474. sqlite3VdbeSorterClose(p->db, pCx);
  48475. if( pCx->pBt ){
  48476. sqlite3BtreeClose(pCx->pBt);
  48477. /* The pCx->pCursor will be close automatically, if it exists, by
  48478. ** the call above. */
  48479. }else if( pCx->pCursor ){
  48480. sqlite3BtreeCloseCursor(pCx->pCursor);
  48481. }
  48482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  48483. if( pCx->pVtabCursor ){
  48484. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  48485. const sqlite3_module *pModule = pCx->pModule;
  48486. p->inVtabMethod = 1;
  48487. pModule->xClose(pVtabCursor);
  48488. p->inVtabMethod = 0;
  48489. }
  48490. #endif
  48491. }
  48492. /*
  48493. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  48494. ** is used, for example, when a trigger sub-program is halted to restore
  48495. ** control to the main program.
  48496. */
  48497. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  48498. Vdbe *v = pFrame->v;
  48499. v->aOnceFlag = pFrame->aOnceFlag;
  48500. v->nOnceFlag = pFrame->nOnceFlag;
  48501. v->aOp = pFrame->aOp;
  48502. v->nOp = pFrame->nOp;
  48503. v->aMem = pFrame->aMem;
  48504. v->nMem = pFrame->nMem;
  48505. v->apCsr = pFrame->apCsr;
  48506. v->nCursor = pFrame->nCursor;
  48507. v->db->lastRowid = pFrame->lastRowid;
  48508. v->nChange = pFrame->nChange;
  48509. return pFrame->pc;
  48510. }
  48511. /*
  48512. ** Close all cursors.
  48513. **
  48514. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  48515. ** cell array. This is necessary as the memory cell array may contain
  48516. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  48517. ** open cursors.
  48518. */
  48519. static void closeAllCursors(Vdbe *p){
  48520. if( p->pFrame ){
  48521. VdbeFrame *pFrame;
  48522. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  48523. sqlite3VdbeFrameRestore(pFrame);
  48524. }
  48525. p->pFrame = 0;
  48526. p->nFrame = 0;
  48527. if( p->apCsr ){
  48528. int i;
  48529. for(i=0; i<p->nCursor; i++){
  48530. VdbeCursor *pC = p->apCsr[i];
  48531. if( pC ){
  48532. sqlite3VdbeFreeCursor(p, pC);
  48533. p->apCsr[i] = 0;
  48534. }
  48535. }
  48536. }
  48537. if( p->aMem ){
  48538. releaseMemArray(&p->aMem[1], p->nMem);
  48539. }
  48540. while( p->pDelFrame ){
  48541. VdbeFrame *pDel = p->pDelFrame;
  48542. p->pDelFrame = pDel->pParent;
  48543. sqlite3VdbeFrameDelete(pDel);
  48544. }
  48545. /* Delete any auxdata allocations made by the VM */
  48546. sqlite3VdbeDeleteAuxData(p, -1, 0);
  48547. assert( p->pAuxData==0 );
  48548. }
  48549. /*
  48550. ** Clean up the VM after execution.
  48551. **
  48552. ** This routine will automatically close any cursors, lists, and/or
  48553. ** sorters that were left open. It also deletes the values of
  48554. ** variables in the aVar[] array.
  48555. */
  48556. static void Cleanup(Vdbe *p){
  48557. sqlite3 *db = p->db;
  48558. #ifdef SQLITE_DEBUG
  48559. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  48560. ** Vdbe.aMem[] arrays have already been cleaned up. */
  48561. int i;
  48562. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  48563. if( p->aMem ){
  48564. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  48565. }
  48566. #endif
  48567. sqlite3DbFree(db, p->zErrMsg);
  48568. p->zErrMsg = 0;
  48569. p->pResultSet = 0;
  48570. }
  48571. /*
  48572. ** Set the number of result columns that will be returned by this SQL
  48573. ** statement. This is now set at compile time, rather than during
  48574. ** execution of the vdbe program so that sqlite3_column_count() can
  48575. ** be called on an SQL statement before sqlite3_step().
  48576. */
  48577. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  48578. Mem *pColName;
  48579. int n;
  48580. sqlite3 *db = p->db;
  48581. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  48582. sqlite3DbFree(db, p->aColName);
  48583. n = nResColumn*COLNAME_N;
  48584. p->nResColumn = (u16)nResColumn;
  48585. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  48586. if( p->aColName==0 ) return;
  48587. while( n-- > 0 ){
  48588. pColName->flags = MEM_Null;
  48589. pColName->db = p->db;
  48590. pColName++;
  48591. }
  48592. }
  48593. /*
  48594. ** Set the name of the idx'th column to be returned by the SQL statement.
  48595. ** zName must be a pointer to a nul terminated string.
  48596. **
  48597. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  48598. **
  48599. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  48600. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  48601. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  48602. */
  48603. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  48604. Vdbe *p, /* Vdbe being configured */
  48605. int idx, /* Index of column zName applies to */
  48606. int var, /* One of the COLNAME_* constants */
  48607. const char *zName, /* Pointer to buffer containing name */
  48608. void (*xDel)(void*) /* Memory management strategy for zName */
  48609. ){
  48610. int rc;
  48611. Mem *pColName;
  48612. assert( idx<p->nResColumn );
  48613. assert( var<COLNAME_N );
  48614. if( p->db->mallocFailed ){
  48615. assert( !zName || xDel!=SQLITE_DYNAMIC );
  48616. return SQLITE_NOMEM;
  48617. }
  48618. assert( p->aColName!=0 );
  48619. pColName = &(p->aColName[idx+var*p->nResColumn]);
  48620. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  48621. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  48622. return rc;
  48623. }
  48624. /*
  48625. ** A read or write transaction may or may not be active on database handle
  48626. ** db. If a transaction is active, commit it. If there is a
  48627. ** write-transaction spanning more than one database file, this routine
  48628. ** takes care of the master journal trickery.
  48629. */
  48630. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  48631. int i;
  48632. int nTrans = 0; /* Number of databases with an active write-transaction */
  48633. int rc = SQLITE_OK;
  48634. int needXcommit = 0;
  48635. #ifdef SQLITE_OMIT_VIRTUALTABLE
  48636. /* With this option, sqlite3VtabSync() is defined to be simply
  48637. ** SQLITE_OK so p is not used.
  48638. */
  48639. UNUSED_PARAMETER(p);
  48640. #endif
  48641. /* Before doing anything else, call the xSync() callback for any
  48642. ** virtual module tables written in this transaction. This has to
  48643. ** be done before determining whether a master journal file is
  48644. ** required, as an xSync() callback may add an attached database
  48645. ** to the transaction.
  48646. */
  48647. rc = sqlite3VtabSync(db, p);
  48648. /* This loop determines (a) if the commit hook should be invoked and
  48649. ** (b) how many database files have open write transactions, not
  48650. ** including the temp database. (b) is important because if more than
  48651. ** one database file has an open write transaction, a master journal
  48652. ** file is required for an atomic commit.
  48653. */
  48654. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48655. Btree *pBt = db->aDb[i].pBt;
  48656. if( sqlite3BtreeIsInTrans(pBt) ){
  48657. needXcommit = 1;
  48658. if( i!=1 ) nTrans++;
  48659. sqlite3BtreeEnter(pBt);
  48660. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  48661. sqlite3BtreeLeave(pBt);
  48662. }
  48663. }
  48664. if( rc!=SQLITE_OK ){
  48665. return rc;
  48666. }
  48667. /* If there are any write-transactions at all, invoke the commit hook */
  48668. if( needXcommit && db->xCommitCallback ){
  48669. rc = db->xCommitCallback(db->pCommitArg);
  48670. if( rc ){
  48671. return SQLITE_CONSTRAINT_COMMITHOOK;
  48672. }
  48673. }
  48674. /* The simple case - no more than one database file (not counting the
  48675. ** TEMP database) has a transaction active. There is no need for the
  48676. ** master-journal.
  48677. **
  48678. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  48679. ** string, it means the main database is :memory: or a temp file. In
  48680. ** that case we do not support atomic multi-file commits, so use the
  48681. ** simple case then too.
  48682. */
  48683. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  48684. || nTrans<=1
  48685. ){
  48686. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48687. Btree *pBt = db->aDb[i].pBt;
  48688. if( pBt ){
  48689. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  48690. }
  48691. }
  48692. /* Do the commit only if all databases successfully complete phase 1.
  48693. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  48694. ** IO error while deleting or truncating a journal file. It is unlikely,
  48695. ** but could happen. In this case abandon processing and return the error.
  48696. */
  48697. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48698. Btree *pBt = db->aDb[i].pBt;
  48699. if( pBt ){
  48700. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  48701. }
  48702. }
  48703. if( rc==SQLITE_OK ){
  48704. sqlite3VtabCommit(db);
  48705. }
  48706. }
  48707. /* The complex case - There is a multi-file write-transaction active.
  48708. ** This requires a master journal file to ensure the transaction is
  48709. ** committed atomicly.
  48710. */
  48711. #ifndef SQLITE_OMIT_DISKIO
  48712. else{
  48713. sqlite3_vfs *pVfs = db->pVfs;
  48714. int needSync = 0;
  48715. char *zMaster = 0; /* File-name for the master journal */
  48716. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  48717. sqlite3_file *pMaster = 0;
  48718. i64 offset = 0;
  48719. int res;
  48720. int retryCount = 0;
  48721. int nMainFile;
  48722. /* Select a master journal file name */
  48723. nMainFile = sqlite3Strlen30(zMainFile);
  48724. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  48725. if( zMaster==0 ) return SQLITE_NOMEM;
  48726. do {
  48727. u32 iRandom;
  48728. if( retryCount ){
  48729. if( retryCount>100 ){
  48730. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  48731. sqlite3OsDelete(pVfs, zMaster, 0);
  48732. break;
  48733. }else if( retryCount==1 ){
  48734. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  48735. }
  48736. }
  48737. retryCount++;
  48738. sqlite3_randomness(sizeof(iRandom), &iRandom);
  48739. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  48740. (iRandom>>8)&0xffffff, iRandom&0xff);
  48741. /* The antipenultimate character of the master journal name must
  48742. ** be "9" to avoid name collisions when using 8+3 filenames. */
  48743. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  48744. sqlite3FileSuffix3(zMainFile, zMaster);
  48745. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  48746. }while( rc==SQLITE_OK && res );
  48747. if( rc==SQLITE_OK ){
  48748. /* Open the master journal. */
  48749. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  48750. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  48751. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  48752. );
  48753. }
  48754. if( rc!=SQLITE_OK ){
  48755. sqlite3DbFree(db, zMaster);
  48756. return rc;
  48757. }
  48758. /* Write the name of each database file in the transaction into the new
  48759. ** master journal file. If an error occurs at this point close
  48760. ** and delete the master journal file. All the individual journal files
  48761. ** still have 'null' as the master journal pointer, so they will roll
  48762. ** back independently if a failure occurs.
  48763. */
  48764. for(i=0; i<db->nDb; i++){
  48765. Btree *pBt = db->aDb[i].pBt;
  48766. if( sqlite3BtreeIsInTrans(pBt) ){
  48767. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  48768. if( zFile==0 ){
  48769. continue; /* Ignore TEMP and :memory: databases */
  48770. }
  48771. assert( zFile[0]!=0 );
  48772. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  48773. needSync = 1;
  48774. }
  48775. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  48776. offset += sqlite3Strlen30(zFile)+1;
  48777. if( rc!=SQLITE_OK ){
  48778. sqlite3OsCloseFree(pMaster);
  48779. sqlite3OsDelete(pVfs, zMaster, 0);
  48780. sqlite3DbFree(db, zMaster);
  48781. return rc;
  48782. }
  48783. }
  48784. }
  48785. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  48786. ** flag is set this is not required.
  48787. */
  48788. if( needSync
  48789. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  48790. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  48791. ){
  48792. sqlite3OsCloseFree(pMaster);
  48793. sqlite3OsDelete(pVfs, zMaster, 0);
  48794. sqlite3DbFree(db, zMaster);
  48795. return rc;
  48796. }
  48797. /* Sync all the db files involved in the transaction. The same call
  48798. ** sets the master journal pointer in each individual journal. If
  48799. ** an error occurs here, do not delete the master journal file.
  48800. **
  48801. ** If the error occurs during the first call to
  48802. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  48803. ** master journal file will be orphaned. But we cannot delete it,
  48804. ** in case the master journal file name was written into the journal
  48805. ** file before the failure occurred.
  48806. */
  48807. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  48808. Btree *pBt = db->aDb[i].pBt;
  48809. if( pBt ){
  48810. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  48811. }
  48812. }
  48813. sqlite3OsCloseFree(pMaster);
  48814. assert( rc!=SQLITE_BUSY );
  48815. if( rc!=SQLITE_OK ){
  48816. sqlite3DbFree(db, zMaster);
  48817. return rc;
  48818. }
  48819. /* Delete the master journal file. This commits the transaction. After
  48820. ** doing this the directory is synced again before any individual
  48821. ** transaction files are deleted.
  48822. */
  48823. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  48824. sqlite3DbFree(db, zMaster);
  48825. zMaster = 0;
  48826. if( rc ){
  48827. return rc;
  48828. }
  48829. /* All files and directories have already been synced, so the following
  48830. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  48831. ** deleting or truncating journals. If something goes wrong while
  48832. ** this is happening we don't really care. The integrity of the
  48833. ** transaction is already guaranteed, but some stray 'cold' journals
  48834. ** may be lying around. Returning an error code won't help matters.
  48835. */
  48836. disable_simulated_io_errors();
  48837. sqlite3BeginBenignMalloc();
  48838. for(i=0; i<db->nDb; i++){
  48839. Btree *pBt = db->aDb[i].pBt;
  48840. if( pBt ){
  48841. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  48842. }
  48843. }
  48844. sqlite3EndBenignMalloc();
  48845. enable_simulated_io_errors();
  48846. sqlite3VtabCommit(db);
  48847. }
  48848. #endif
  48849. return rc;
  48850. }
  48851. /*
  48852. ** This routine checks that the sqlite3.nVdbeActive count variable
  48853. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  48854. ** currently active. An assertion fails if the two counts do not match.
  48855. ** This is an internal self-check only - it is not an essential processing
  48856. ** step.
  48857. **
  48858. ** This is a no-op if NDEBUG is defined.
  48859. */
  48860. #ifndef NDEBUG
  48861. static void checkActiveVdbeCnt(sqlite3 *db){
  48862. Vdbe *p;
  48863. int cnt = 0;
  48864. int nWrite = 0;
  48865. int nRead = 0;
  48866. p = db->pVdbe;
  48867. while( p ){
  48868. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  48869. cnt++;
  48870. if( p->readOnly==0 ) nWrite++;
  48871. if( p->bIsReader ) nRead++;
  48872. }
  48873. p = p->pNext;
  48874. }
  48875. assert( cnt==db->nVdbeActive );
  48876. assert( nWrite==db->nVdbeWrite );
  48877. assert( nRead==db->nVdbeRead );
  48878. }
  48879. #else
  48880. #define checkActiveVdbeCnt(x)
  48881. #endif
  48882. /*
  48883. ** If the Vdbe passed as the first argument opened a statement-transaction,
  48884. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  48885. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  48886. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  48887. ** statement transaction is committed.
  48888. **
  48889. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  48890. ** Otherwise SQLITE_OK.
  48891. */
  48892. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  48893. sqlite3 *const db = p->db;
  48894. int rc = SQLITE_OK;
  48895. /* If p->iStatement is greater than zero, then this Vdbe opened a
  48896. ** statement transaction that should be closed here. The only exception
  48897. ** is that an IO error may have occurred, causing an emergency rollback.
  48898. ** In this case (db->nStatement==0), and there is nothing to do.
  48899. */
  48900. if( db->nStatement && p->iStatement ){
  48901. int i;
  48902. const int iSavepoint = p->iStatement-1;
  48903. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  48904. assert( db->nStatement>0 );
  48905. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  48906. for(i=0; i<db->nDb; i++){
  48907. int rc2 = SQLITE_OK;
  48908. Btree *pBt = db->aDb[i].pBt;
  48909. if( pBt ){
  48910. if( eOp==SAVEPOINT_ROLLBACK ){
  48911. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  48912. }
  48913. if( rc2==SQLITE_OK ){
  48914. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  48915. }
  48916. if( rc==SQLITE_OK ){
  48917. rc = rc2;
  48918. }
  48919. }
  48920. }
  48921. db->nStatement--;
  48922. p->iStatement = 0;
  48923. if( rc==SQLITE_OK ){
  48924. if( eOp==SAVEPOINT_ROLLBACK ){
  48925. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  48926. }
  48927. if( rc==SQLITE_OK ){
  48928. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  48929. }
  48930. }
  48931. /* If the statement transaction is being rolled back, also restore the
  48932. ** database handles deferred constraint counter to the value it had when
  48933. ** the statement transaction was opened. */
  48934. if( eOp==SAVEPOINT_ROLLBACK ){
  48935. db->nDeferredCons = p->nStmtDefCons;
  48936. db->nDeferredImmCons = p->nStmtDefImmCons;
  48937. }
  48938. }
  48939. return rc;
  48940. }
  48941. /*
  48942. ** This function is called when a transaction opened by the database
  48943. ** handle associated with the VM passed as an argument is about to be
  48944. ** committed. If there are outstanding deferred foreign key constraint
  48945. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  48946. **
  48947. ** If there are outstanding FK violations and this function returns
  48948. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  48949. ** and write an error message to it. Then return SQLITE_ERROR.
  48950. */
  48951. #ifndef SQLITE_OMIT_FOREIGN_KEY
  48952. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  48953. sqlite3 *db = p->db;
  48954. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  48955. || (!deferred && p->nFkConstraint>0)
  48956. ){
  48957. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  48958. p->errorAction = OE_Abort;
  48959. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  48960. return SQLITE_ERROR;
  48961. }
  48962. return SQLITE_OK;
  48963. }
  48964. #endif
  48965. /*
  48966. ** This routine is called the when a VDBE tries to halt. If the VDBE
  48967. ** has made changes and is in autocommit mode, then commit those
  48968. ** changes. If a rollback is needed, then do the rollback.
  48969. **
  48970. ** This routine is the only way to move the state of a VM from
  48971. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  48972. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  48973. **
  48974. ** Return an error code. If the commit could not complete because of
  48975. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  48976. ** means the close did not happen and needs to be repeated.
  48977. */
  48978. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  48979. int rc; /* Used to store transient return codes */
  48980. sqlite3 *db = p->db;
  48981. /* This function contains the logic that determines if a statement or
  48982. ** transaction will be committed or rolled back as a result of the
  48983. ** execution of this virtual machine.
  48984. **
  48985. ** If any of the following errors occur:
  48986. **
  48987. ** SQLITE_NOMEM
  48988. ** SQLITE_IOERR
  48989. ** SQLITE_FULL
  48990. ** SQLITE_INTERRUPT
  48991. **
  48992. ** Then the internal cache might have been left in an inconsistent
  48993. ** state. We need to rollback the statement transaction, if there is
  48994. ** one, or the complete transaction if there is no statement transaction.
  48995. */
  48996. if( p->db->mallocFailed ){
  48997. p->rc = SQLITE_NOMEM;
  48998. }
  48999. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  49000. closeAllCursors(p);
  49001. if( p->magic!=VDBE_MAGIC_RUN ){
  49002. return SQLITE_OK;
  49003. }
  49004. checkActiveVdbeCnt(db);
  49005. /* No commit or rollback needed if the program never started or if the
  49006. ** SQL statement does not read or write a database file. */
  49007. if( p->pc>=0 && p->bIsReader ){
  49008. int mrc; /* Primary error code from p->rc */
  49009. int eStatementOp = 0;
  49010. int isSpecialError; /* Set to true if a 'special' error */
  49011. /* Lock all btrees used by the statement */
  49012. sqlite3VdbeEnter(p);
  49013. /* Check for one of the special errors */
  49014. mrc = p->rc & 0xff;
  49015. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  49016. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  49017. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  49018. if( isSpecialError ){
  49019. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  49020. ** no rollback is necessary. Otherwise, at least a savepoint
  49021. ** transaction must be rolled back to restore the database to a
  49022. ** consistent state.
  49023. **
  49024. ** Even if the statement is read-only, it is important to perform
  49025. ** a statement or transaction rollback operation. If the error
  49026. ** occurred while writing to the journal, sub-journal or database
  49027. ** file as part of an effort to free up cache space (see function
  49028. ** pagerStress() in pager.c), the rollback is required to restore
  49029. ** the pager to a consistent state.
  49030. */
  49031. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  49032. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  49033. eStatementOp = SAVEPOINT_ROLLBACK;
  49034. }else{
  49035. /* We are forced to roll back the active transaction. Before doing
  49036. ** so, abort any other statements this handle currently has active.
  49037. */
  49038. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49039. sqlite3CloseSavepoints(db);
  49040. db->autoCommit = 1;
  49041. }
  49042. }
  49043. }
  49044. /* Check for immediate foreign key violations. */
  49045. if( p->rc==SQLITE_OK ){
  49046. sqlite3VdbeCheckFk(p, 0);
  49047. }
  49048. /* If the auto-commit flag is set and this is the only active writer
  49049. ** VM, then we do either a commit or rollback of the current transaction.
  49050. **
  49051. ** Note: This block also runs if one of the special errors handled
  49052. ** above has occurred.
  49053. */
  49054. if( !sqlite3VtabInSync(db)
  49055. && db->autoCommit
  49056. && db->nVdbeWrite==(p->readOnly==0)
  49057. ){
  49058. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  49059. rc = sqlite3VdbeCheckFk(p, 1);
  49060. if( rc!=SQLITE_OK ){
  49061. if( NEVER(p->readOnly) ){
  49062. sqlite3VdbeLeave(p);
  49063. return SQLITE_ERROR;
  49064. }
  49065. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  49066. }else{
  49067. /* The auto-commit flag is true, the vdbe program was successful
  49068. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  49069. ** key constraints to hold up the transaction. This means a commit
  49070. ** is required. */
  49071. rc = vdbeCommit(db, p);
  49072. }
  49073. if( rc==SQLITE_BUSY && p->readOnly ){
  49074. sqlite3VdbeLeave(p);
  49075. return SQLITE_BUSY;
  49076. }else if( rc!=SQLITE_OK ){
  49077. p->rc = rc;
  49078. sqlite3RollbackAll(db, SQLITE_OK);
  49079. }else{
  49080. db->nDeferredCons = 0;
  49081. db->nDeferredImmCons = 0;
  49082. db->flags &= ~SQLITE_DeferFKs;
  49083. sqlite3CommitInternalChanges(db);
  49084. }
  49085. }else{
  49086. sqlite3RollbackAll(db, SQLITE_OK);
  49087. }
  49088. db->nStatement = 0;
  49089. }else if( eStatementOp==0 ){
  49090. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  49091. eStatementOp = SAVEPOINT_RELEASE;
  49092. }else if( p->errorAction==OE_Abort ){
  49093. eStatementOp = SAVEPOINT_ROLLBACK;
  49094. }else{
  49095. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49096. sqlite3CloseSavepoints(db);
  49097. db->autoCommit = 1;
  49098. }
  49099. }
  49100. /* If eStatementOp is non-zero, then a statement transaction needs to
  49101. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  49102. ** do so. If this operation returns an error, and the current statement
  49103. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  49104. ** current statement error code.
  49105. */
  49106. if( eStatementOp ){
  49107. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  49108. if( rc ){
  49109. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  49110. p->rc = rc;
  49111. sqlite3DbFree(db, p->zErrMsg);
  49112. p->zErrMsg = 0;
  49113. }
  49114. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  49115. sqlite3CloseSavepoints(db);
  49116. db->autoCommit = 1;
  49117. }
  49118. }
  49119. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  49120. ** has been rolled back, update the database connection change-counter.
  49121. */
  49122. if( p->changeCntOn ){
  49123. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  49124. sqlite3VdbeSetChanges(db, p->nChange);
  49125. }else{
  49126. sqlite3VdbeSetChanges(db, 0);
  49127. }
  49128. p->nChange = 0;
  49129. }
  49130. /* Release the locks */
  49131. sqlite3VdbeLeave(p);
  49132. }
  49133. /* We have successfully halted and closed the VM. Record this fact. */
  49134. if( p->pc>=0 ){
  49135. db->nVdbeActive--;
  49136. if( !p->readOnly ) db->nVdbeWrite--;
  49137. if( p->bIsReader ) db->nVdbeRead--;
  49138. assert( db->nVdbeActive>=db->nVdbeRead );
  49139. assert( db->nVdbeRead>=db->nVdbeWrite );
  49140. assert( db->nVdbeWrite>=0 );
  49141. }
  49142. p->magic = VDBE_MAGIC_HALT;
  49143. checkActiveVdbeCnt(db);
  49144. if( p->db->mallocFailed ){
  49145. p->rc = SQLITE_NOMEM;
  49146. }
  49147. /* If the auto-commit flag is set to true, then any locks that were held
  49148. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  49149. ** to invoke any required unlock-notify callbacks.
  49150. */
  49151. if( db->autoCommit ){
  49152. sqlite3ConnectionUnlocked(db);
  49153. }
  49154. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  49155. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  49156. }
  49157. /*
  49158. ** Each VDBE holds the result of the most recent sqlite3_step() call
  49159. ** in p->rc. This routine sets that result back to SQLITE_OK.
  49160. */
  49161. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  49162. p->rc = SQLITE_OK;
  49163. }
  49164. /*
  49165. ** Copy the error code and error message belonging to the VDBE passed
  49166. ** as the first argument to its database handle (so that they will be
  49167. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  49168. **
  49169. ** This function does not clear the VDBE error code or message, just
  49170. ** copies them to the database handle.
  49171. */
  49172. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  49173. sqlite3 *db = p->db;
  49174. int rc = p->rc;
  49175. if( p->zErrMsg ){
  49176. u8 mallocFailed = db->mallocFailed;
  49177. sqlite3BeginBenignMalloc();
  49178. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  49179. sqlite3EndBenignMalloc();
  49180. db->mallocFailed = mallocFailed;
  49181. db->errCode = rc;
  49182. }else{
  49183. sqlite3Error(db, rc, 0);
  49184. }
  49185. return rc;
  49186. }
  49187. #ifdef SQLITE_ENABLE_SQLLOG
  49188. /*
  49189. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  49190. ** invoke it.
  49191. */
  49192. static void vdbeInvokeSqllog(Vdbe *v){
  49193. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  49194. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  49195. assert( v->db->init.busy==0 );
  49196. if( zExpanded ){
  49197. sqlite3GlobalConfig.xSqllog(
  49198. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  49199. );
  49200. sqlite3DbFree(v->db, zExpanded);
  49201. }
  49202. }
  49203. }
  49204. #else
  49205. # define vdbeInvokeSqllog(x)
  49206. #endif
  49207. /*
  49208. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  49209. ** Write any error messages into *pzErrMsg. Return the result code.
  49210. **
  49211. ** After this routine is run, the VDBE should be ready to be executed
  49212. ** again.
  49213. **
  49214. ** To look at it another way, this routine resets the state of the
  49215. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  49216. ** VDBE_MAGIC_INIT.
  49217. */
  49218. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  49219. sqlite3 *db;
  49220. db = p->db;
  49221. /* If the VM did not run to completion or if it encountered an
  49222. ** error, then it might not have been halted properly. So halt
  49223. ** it now.
  49224. */
  49225. sqlite3VdbeHalt(p);
  49226. /* If the VDBE has be run even partially, then transfer the error code
  49227. ** and error message from the VDBE into the main database structure. But
  49228. ** if the VDBE has just been set to run but has not actually executed any
  49229. ** instructions yet, leave the main database error information unchanged.
  49230. */
  49231. if( p->pc>=0 ){
  49232. vdbeInvokeSqllog(p);
  49233. sqlite3VdbeTransferError(p);
  49234. sqlite3DbFree(db, p->zErrMsg);
  49235. p->zErrMsg = 0;
  49236. if( p->runOnlyOnce ) p->expired = 1;
  49237. }else if( p->rc && p->expired ){
  49238. /* The expired flag was set on the VDBE before the first call
  49239. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  49240. ** called), set the database error in this case as well.
  49241. */
  49242. sqlite3Error(db, p->rc, 0);
  49243. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  49244. sqlite3DbFree(db, p->zErrMsg);
  49245. p->zErrMsg = 0;
  49246. }
  49247. /* Reclaim all memory used by the VDBE
  49248. */
  49249. Cleanup(p);
  49250. /* Save profiling information from this VDBE run.
  49251. */
  49252. #ifdef VDBE_PROFILE
  49253. {
  49254. FILE *out = fopen("vdbe_profile.out", "a");
  49255. if( out ){
  49256. int i;
  49257. fprintf(out, "---- ");
  49258. for(i=0; i<p->nOp; i++){
  49259. fprintf(out, "%02x", p->aOp[i].opcode);
  49260. }
  49261. fprintf(out, "\n");
  49262. for(i=0; i<p->nOp; i++){
  49263. fprintf(out, "%6d %10lld %8lld ",
  49264. p->aOp[i].cnt,
  49265. p->aOp[i].cycles,
  49266. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  49267. );
  49268. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  49269. }
  49270. fclose(out);
  49271. }
  49272. }
  49273. #endif
  49274. p->iCurrentTime = 0;
  49275. p->magic = VDBE_MAGIC_INIT;
  49276. return p->rc & db->errMask;
  49277. }
  49278. /*
  49279. ** Clean up and delete a VDBE after execution. Return an integer which is
  49280. ** the result code. Write any error message text into *pzErrMsg.
  49281. */
  49282. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  49283. int rc = SQLITE_OK;
  49284. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  49285. rc = sqlite3VdbeReset(p);
  49286. assert( (rc & p->db->errMask)==rc );
  49287. }
  49288. sqlite3VdbeDelete(p);
  49289. return rc;
  49290. }
  49291. /*
  49292. ** If parameter iOp is less than zero, then invoke the destructor for
  49293. ** all auxiliary data pointers currently cached by the VM passed as
  49294. ** the first argument.
  49295. **
  49296. ** Or, if iOp is greater than or equal to zero, then the destructor is
  49297. ** only invoked for those auxiliary data pointers created by the user
  49298. ** function invoked by the OP_Function opcode at instruction iOp of
  49299. ** VM pVdbe, and only then if:
  49300. **
  49301. ** * the associated function parameter is the 32nd or later (counting
  49302. ** from left to right), or
  49303. **
  49304. ** * the corresponding bit in argument mask is clear (where the first
  49305. ** function parameter corrsponds to bit 0 etc.).
  49306. */
  49307. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  49308. AuxData **pp = &pVdbe->pAuxData;
  49309. while( *pp ){
  49310. AuxData *pAux = *pp;
  49311. if( (iOp<0)
  49312. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
  49313. ){
  49314. if( pAux->xDelete ){
  49315. pAux->xDelete(pAux->pAux);
  49316. }
  49317. *pp = pAux->pNext;
  49318. sqlite3DbFree(pVdbe->db, pAux);
  49319. }else{
  49320. pp= &pAux->pNext;
  49321. }
  49322. }
  49323. }
  49324. /*
  49325. ** Free all memory associated with the Vdbe passed as the second argument,
  49326. ** except for object itself, which is preserved.
  49327. **
  49328. ** The difference between this function and sqlite3VdbeDelete() is that
  49329. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  49330. ** the database connection and frees the object itself.
  49331. */
  49332. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  49333. SubProgram *pSub, *pNext;
  49334. int i;
  49335. assert( p->db==0 || p->db==db );
  49336. releaseMemArray(p->aVar, p->nVar);
  49337. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  49338. for(pSub=p->pProgram; pSub; pSub=pNext){
  49339. pNext = pSub->pNext;
  49340. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  49341. sqlite3DbFree(db, pSub);
  49342. }
  49343. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  49344. vdbeFreeOpArray(db, p->aOp, p->nOp);
  49345. sqlite3DbFree(db, p->aLabel);
  49346. sqlite3DbFree(db, p->aColName);
  49347. sqlite3DbFree(db, p->zSql);
  49348. sqlite3DbFree(db, p->pFree);
  49349. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  49350. sqlite3DbFree(db, p->zExplain);
  49351. sqlite3DbFree(db, p->pExplain);
  49352. #endif
  49353. }
  49354. /*
  49355. ** Delete an entire VDBE.
  49356. */
  49357. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  49358. sqlite3 *db;
  49359. if( NEVER(p==0) ) return;
  49360. db = p->db;
  49361. assert( sqlite3_mutex_held(db->mutex) );
  49362. sqlite3VdbeClearObject(db, p);
  49363. if( p->pPrev ){
  49364. p->pPrev->pNext = p->pNext;
  49365. }else{
  49366. assert( db->pVdbe==p );
  49367. db->pVdbe = p->pNext;
  49368. }
  49369. if( p->pNext ){
  49370. p->pNext->pPrev = p->pPrev;
  49371. }
  49372. p->magic = VDBE_MAGIC_DEAD;
  49373. p->db = 0;
  49374. sqlite3DbFree(db, p);
  49375. }
  49376. /*
  49377. ** Make sure the cursor p is ready to read or write the row to which it
  49378. ** was last positioned. Return an error code if an OOM fault or I/O error
  49379. ** prevents us from positioning the cursor to its correct position.
  49380. **
  49381. ** If a MoveTo operation is pending on the given cursor, then do that
  49382. ** MoveTo now. If no move is pending, check to see if the row has been
  49383. ** deleted out from under the cursor and if it has, mark the row as
  49384. ** a NULL row.
  49385. **
  49386. ** If the cursor is already pointing to the correct row and that row has
  49387. ** not been deleted out from under the cursor, then this routine is a no-op.
  49388. */
  49389. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  49390. if( p->deferredMoveto ){
  49391. int res, rc;
  49392. #ifdef SQLITE_TEST
  49393. extern int sqlite3_search_count;
  49394. #endif
  49395. assert( p->isTable );
  49396. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  49397. if( rc ) return rc;
  49398. p->lastRowid = p->movetoTarget;
  49399. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  49400. p->rowidIsValid = 1;
  49401. #ifdef SQLITE_TEST
  49402. sqlite3_search_count++;
  49403. #endif
  49404. p->deferredMoveto = 0;
  49405. p->cacheStatus = CACHE_STALE;
  49406. }else if( ALWAYS(p->pCursor) ){
  49407. int hasMoved;
  49408. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  49409. if( rc ) return rc;
  49410. if( hasMoved ){
  49411. p->cacheStatus = CACHE_STALE;
  49412. p->nullRow = 1;
  49413. }
  49414. }
  49415. return SQLITE_OK;
  49416. }
  49417. /*
  49418. ** The following functions:
  49419. **
  49420. ** sqlite3VdbeSerialType()
  49421. ** sqlite3VdbeSerialTypeLen()
  49422. ** sqlite3VdbeSerialLen()
  49423. ** sqlite3VdbeSerialPut()
  49424. ** sqlite3VdbeSerialGet()
  49425. **
  49426. ** encapsulate the code that serializes values for storage in SQLite
  49427. ** data and index records. Each serialized value consists of a
  49428. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  49429. ** integer, stored as a varint.
  49430. **
  49431. ** In an SQLite index record, the serial type is stored directly before
  49432. ** the blob of data that it corresponds to. In a table record, all serial
  49433. ** types are stored at the start of the record, and the blobs of data at
  49434. ** the end. Hence these functions allow the caller to handle the
  49435. ** serial-type and data blob separately.
  49436. **
  49437. ** The following table describes the various storage classes for data:
  49438. **
  49439. ** serial type bytes of data type
  49440. ** -------------- --------------- ---------------
  49441. ** 0 0 NULL
  49442. ** 1 1 signed integer
  49443. ** 2 2 signed integer
  49444. ** 3 3 signed integer
  49445. ** 4 4 signed integer
  49446. ** 5 6 signed integer
  49447. ** 6 8 signed integer
  49448. ** 7 8 IEEE float
  49449. ** 8 0 Integer constant 0
  49450. ** 9 0 Integer constant 1
  49451. ** 10,11 reserved for expansion
  49452. ** N>=12 and even (N-12)/2 BLOB
  49453. ** N>=13 and odd (N-13)/2 text
  49454. **
  49455. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  49456. ** of SQLite will not understand those serial types.
  49457. */
  49458. /*
  49459. ** Return the serial-type for the value stored in pMem.
  49460. */
  49461. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  49462. int flags = pMem->flags;
  49463. int n;
  49464. if( flags&MEM_Null ){
  49465. return 0;
  49466. }
  49467. if( flags&MEM_Int ){
  49468. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  49469. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  49470. i64 i = pMem->u.i;
  49471. u64 u;
  49472. if( i<0 ){
  49473. if( i<(-MAX_6BYTE) ) return 6;
  49474. /* Previous test prevents: u = -(-9223372036854775808) */
  49475. u = -i;
  49476. }else{
  49477. u = i;
  49478. }
  49479. if( u<=127 ){
  49480. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  49481. }
  49482. if( u<=32767 ) return 2;
  49483. if( u<=8388607 ) return 3;
  49484. if( u<=2147483647 ) return 4;
  49485. if( u<=MAX_6BYTE ) return 5;
  49486. return 6;
  49487. }
  49488. if( flags&MEM_Real ){
  49489. return 7;
  49490. }
  49491. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  49492. n = pMem->n;
  49493. if( flags & MEM_Zero ){
  49494. n += pMem->u.nZero;
  49495. }
  49496. assert( n>=0 );
  49497. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  49498. }
  49499. /*
  49500. ** Return the length of the data corresponding to the supplied serial-type.
  49501. */
  49502. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  49503. if( serial_type>=12 ){
  49504. return (serial_type-12)/2;
  49505. }else{
  49506. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  49507. return aSize[serial_type];
  49508. }
  49509. }
  49510. /*
  49511. ** If we are on an architecture with mixed-endian floating
  49512. ** points (ex: ARM7) then swap the lower 4 bytes with the
  49513. ** upper 4 bytes. Return the result.
  49514. **
  49515. ** For most architectures, this is a no-op.
  49516. **
  49517. ** (later): It is reported to me that the mixed-endian problem
  49518. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  49519. ** that early versions of GCC stored the two words of a 64-bit
  49520. ** float in the wrong order. And that error has been propagated
  49521. ** ever since. The blame is not necessarily with GCC, though.
  49522. ** GCC might have just copying the problem from a prior compiler.
  49523. ** I am also told that newer versions of GCC that follow a different
  49524. ** ABI get the byte order right.
  49525. **
  49526. ** Developers using SQLite on an ARM7 should compile and run their
  49527. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  49528. ** enabled, some asserts below will ensure that the byte order of
  49529. ** floating point values is correct.
  49530. **
  49531. ** (2007-08-30) Frank van Vugt has studied this problem closely
  49532. ** and has send his findings to the SQLite developers. Frank
  49533. ** writes that some Linux kernels offer floating point hardware
  49534. ** emulation that uses only 32-bit mantissas instead of a full
  49535. ** 48-bits as required by the IEEE standard. (This is the
  49536. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  49537. ** byte swapping becomes very complicated. To avoid problems,
  49538. ** the necessary byte swapping is carried out using a 64-bit integer
  49539. ** rather than a 64-bit float. Frank assures us that the code here
  49540. ** works for him. We, the developers, have no way to independently
  49541. ** verify this, but Frank seems to know what he is talking about
  49542. ** so we trust him.
  49543. */
  49544. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  49545. static u64 floatSwap(u64 in){
  49546. union {
  49547. u64 r;
  49548. u32 i[2];
  49549. } u;
  49550. u32 t;
  49551. u.r = in;
  49552. t = u.i[0];
  49553. u.i[0] = u.i[1];
  49554. u.i[1] = t;
  49555. return u.r;
  49556. }
  49557. # define swapMixedEndianFloat(X) X = floatSwap(X)
  49558. #else
  49559. # define swapMixedEndianFloat(X)
  49560. #endif
  49561. /*
  49562. ** Write the serialized data blob for the value stored in pMem into
  49563. ** buf. It is assumed that the caller has allocated sufficient space.
  49564. ** Return the number of bytes written.
  49565. **
  49566. ** nBuf is the amount of space left in buf[]. nBuf must always be
  49567. ** large enough to hold the entire field. Except, if the field is
  49568. ** a blob with a zero-filled tail, then buf[] might be just the right
  49569. ** size to hold everything except for the zero-filled tail. If buf[]
  49570. ** is only big enough to hold the non-zero prefix, then only write that
  49571. ** prefix into buf[]. But if buf[] is large enough to hold both the
  49572. ** prefix and the tail then write the prefix and set the tail to all
  49573. ** zeros.
  49574. **
  49575. ** Return the number of bytes actually written into buf[]. The number
  49576. ** of bytes in the zero-filled tail is included in the return value only
  49577. ** if those bytes were zeroed in buf[].
  49578. */
  49579. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  49580. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  49581. u32 len;
  49582. /* Integer and Real */
  49583. if( serial_type<=7 && serial_type>0 ){
  49584. u64 v;
  49585. u32 i;
  49586. if( serial_type==7 ){
  49587. assert( sizeof(v)==sizeof(pMem->r) );
  49588. memcpy(&v, &pMem->r, sizeof(v));
  49589. swapMixedEndianFloat(v);
  49590. }else{
  49591. v = pMem->u.i;
  49592. }
  49593. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  49594. assert( len<=(u32)nBuf );
  49595. while( i-- ){
  49596. buf[i] = (u8)(v&0xFF);
  49597. v >>= 8;
  49598. }
  49599. return len;
  49600. }
  49601. /* String or blob */
  49602. if( serial_type>=12 ){
  49603. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  49604. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  49605. assert( pMem->n<=nBuf );
  49606. len = pMem->n;
  49607. memcpy(buf, pMem->z, len);
  49608. if( pMem->flags & MEM_Zero ){
  49609. len += pMem->u.nZero;
  49610. assert( nBuf>=0 );
  49611. if( len > (u32)nBuf ){
  49612. len = (u32)nBuf;
  49613. }
  49614. memset(&buf[pMem->n], 0, len-pMem->n);
  49615. }
  49616. return len;
  49617. }
  49618. /* NULL or constants 0 or 1 */
  49619. return 0;
  49620. }
  49621. /*
  49622. ** Deserialize the data blob pointed to by buf as serial type serial_type
  49623. ** and store the result in pMem. Return the number of bytes read.
  49624. */
  49625. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  49626. const unsigned char *buf, /* Buffer to deserialize from */
  49627. u32 serial_type, /* Serial type to deserialize */
  49628. Mem *pMem /* Memory cell to write value into */
  49629. ){
  49630. switch( serial_type ){
  49631. case 10: /* Reserved for future use */
  49632. case 11: /* Reserved for future use */
  49633. case 0: { /* NULL */
  49634. pMem->flags = MEM_Null;
  49635. break;
  49636. }
  49637. case 1: { /* 1-byte signed integer */
  49638. pMem->u.i = (signed char)buf[0];
  49639. pMem->flags = MEM_Int;
  49640. return 1;
  49641. }
  49642. case 2: { /* 2-byte signed integer */
  49643. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  49644. pMem->flags = MEM_Int;
  49645. return 2;
  49646. }
  49647. case 3: { /* 3-byte signed integer */
  49648. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  49649. pMem->flags = MEM_Int;
  49650. return 3;
  49651. }
  49652. case 4: { /* 4-byte signed integer */
  49653. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  49654. pMem->flags = MEM_Int;
  49655. return 4;
  49656. }
  49657. case 5: { /* 6-byte signed integer */
  49658. u64 x = (((signed char)buf[0])<<8) | buf[1];
  49659. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  49660. x = (x<<32) | y;
  49661. pMem->u.i = *(i64*)&x;
  49662. pMem->flags = MEM_Int;
  49663. return 6;
  49664. }
  49665. case 6: /* 8-byte signed integer */
  49666. case 7: { /* IEEE floating point */
  49667. u64 x;
  49668. u32 y;
  49669. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  49670. /* Verify that integers and floating point values use the same
  49671. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  49672. ** defined that 64-bit floating point values really are mixed
  49673. ** endian.
  49674. */
  49675. static const u64 t1 = ((u64)0x3ff00000)<<32;
  49676. static const double r1 = 1.0;
  49677. u64 t2 = t1;
  49678. swapMixedEndianFloat(t2);
  49679. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  49680. #endif
  49681. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  49682. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  49683. x = (x<<32) | y;
  49684. if( serial_type==6 ){
  49685. pMem->u.i = *(i64*)&x;
  49686. pMem->flags = MEM_Int;
  49687. }else{
  49688. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  49689. swapMixedEndianFloat(x);
  49690. memcpy(&pMem->r, &x, sizeof(x));
  49691. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  49692. }
  49693. return 8;
  49694. }
  49695. case 8: /* Integer 0 */
  49696. case 9: { /* Integer 1 */
  49697. pMem->u.i = serial_type-8;
  49698. pMem->flags = MEM_Int;
  49699. return 0;
  49700. }
  49701. default: {
  49702. u32 len = (serial_type-12)/2;
  49703. pMem->z = (char *)buf;
  49704. pMem->n = len;
  49705. pMem->xDel = 0;
  49706. if( serial_type&0x01 ){
  49707. pMem->flags = MEM_Str | MEM_Ephem;
  49708. }else{
  49709. pMem->flags = MEM_Blob | MEM_Ephem;
  49710. }
  49711. return len;
  49712. }
  49713. }
  49714. return 0;
  49715. }
  49716. /*
  49717. ** This routine is used to allocate sufficient space for an UnpackedRecord
  49718. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  49719. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  49720. **
  49721. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  49722. ** the unaligned buffer passed via the second and third arguments (presumably
  49723. ** stack space). If the former, then *ppFree is set to a pointer that should
  49724. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  49725. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  49726. ** before returning.
  49727. **
  49728. ** If an OOM error occurs, NULL is returned.
  49729. */
  49730. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  49731. KeyInfo *pKeyInfo, /* Description of the record */
  49732. char *pSpace, /* Unaligned space available */
  49733. int szSpace, /* Size of pSpace[] in bytes */
  49734. char **ppFree /* OUT: Caller should free this pointer */
  49735. ){
  49736. UnpackedRecord *p; /* Unpacked record to return */
  49737. int nOff; /* Increment pSpace by nOff to align it */
  49738. int nByte; /* Number of bytes required for *p */
  49739. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  49740. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  49741. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  49742. */
  49743. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  49744. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  49745. if( nByte>szSpace+nOff ){
  49746. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  49747. *ppFree = (char *)p;
  49748. if( !p ) return 0;
  49749. }else{
  49750. p = (UnpackedRecord*)&pSpace[nOff];
  49751. *ppFree = 0;
  49752. }
  49753. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  49754. assert( pKeyInfo->aSortOrder!=0 );
  49755. p->pKeyInfo = pKeyInfo;
  49756. p->nField = pKeyInfo->nField + 1;
  49757. return p;
  49758. }
  49759. /*
  49760. ** Given the nKey-byte encoding of a record in pKey[], populate the
  49761. ** UnpackedRecord structure indicated by the fourth argument with the
  49762. ** contents of the decoded record.
  49763. */
  49764. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  49765. KeyInfo *pKeyInfo, /* Information about the record format */
  49766. int nKey, /* Size of the binary record */
  49767. const void *pKey, /* The binary record */
  49768. UnpackedRecord *p /* Populate this structure before returning. */
  49769. ){
  49770. const unsigned char *aKey = (const unsigned char *)pKey;
  49771. int d;
  49772. u32 idx; /* Offset in aKey[] to read from */
  49773. u16 u; /* Unsigned loop counter */
  49774. u32 szHdr;
  49775. Mem *pMem = p->aMem;
  49776. p->flags = 0;
  49777. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  49778. idx = getVarint32(aKey, szHdr);
  49779. d = szHdr;
  49780. u = 0;
  49781. while( idx<szHdr && u<p->nField && d<=nKey ){
  49782. u32 serial_type;
  49783. idx += getVarint32(&aKey[idx], serial_type);
  49784. pMem->enc = pKeyInfo->enc;
  49785. pMem->db = pKeyInfo->db;
  49786. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  49787. pMem->zMalloc = 0;
  49788. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  49789. pMem++;
  49790. u++;
  49791. }
  49792. assert( u<=pKeyInfo->nField + 1 );
  49793. p->nField = u;
  49794. }
  49795. /*
  49796. ** This function compares the two table rows or index records
  49797. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  49798. ** or positive integer if key1 is less than, equal to or
  49799. ** greater than key2. The {nKey1, pKey1} key must be a blob
  49800. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  49801. ** key must be a parsed key such as obtained from
  49802. ** sqlite3VdbeParseRecord.
  49803. **
  49804. ** Key1 and Key2 do not have to contain the same number of fields.
  49805. ** The key with fewer fields is usually compares less than the
  49806. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  49807. ** and the common prefixes are equal, then key1 is less than key2.
  49808. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  49809. ** equal, then the keys are considered to be equal and
  49810. ** the parts beyond the common prefix are ignored.
  49811. */
  49812. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  49813. int nKey1, const void *pKey1, /* Left key */
  49814. UnpackedRecord *pPKey2 /* Right key */
  49815. ){
  49816. u32 d1; /* Offset into aKey[] of next data element */
  49817. u32 idx1; /* Offset into aKey[] of next header element */
  49818. u32 szHdr1; /* Number of bytes in header */
  49819. int i = 0;
  49820. int rc = 0;
  49821. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  49822. KeyInfo *pKeyInfo;
  49823. Mem mem1;
  49824. pKeyInfo = pPKey2->pKeyInfo;
  49825. mem1.enc = pKeyInfo->enc;
  49826. mem1.db = pKeyInfo->db;
  49827. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  49828. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  49829. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  49830. ** We could initialize it, as shown here, to silence those complaints.
  49831. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  49832. ** the unnecessary initialization has a measurable negative performance
  49833. ** impact, since this routine is a very high runner. And so, we choose
  49834. ** to ignore the compiler warnings and leave this variable uninitialized.
  49835. */
  49836. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  49837. idx1 = getVarint32(aKey1, szHdr1);
  49838. d1 = szHdr1;
  49839. assert( pKeyInfo->nField+1>=pPKey2->nField );
  49840. assert( pKeyInfo->aSortOrder!=0 );
  49841. while( idx1<szHdr1 && i<pPKey2->nField ){
  49842. u32 serial_type1;
  49843. /* Read the serial types for the next element in each key. */
  49844. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  49845. /* Verify that there is enough key space remaining to avoid
  49846. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  49847. ** always be greater than or equal to the amount of required key space.
  49848. ** Use that approximation to avoid the more expensive call to
  49849. ** sqlite3VdbeSerialTypeLen() in the common case.
  49850. */
  49851. if( d1+serial_type1+2>(u32)nKey1
  49852. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  49853. ){
  49854. break;
  49855. }
  49856. /* Extract the values to be compared.
  49857. */
  49858. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  49859. /* Do the comparison
  49860. */
  49861. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  49862. if( rc!=0 ){
  49863. assert( mem1.zMalloc==0 ); /* See comment below */
  49864. /* Invert the result if we are using DESC sort order. */
  49865. if( pKeyInfo->aSortOrder[i] ){
  49866. rc = -rc;
  49867. }
  49868. /* If the PREFIX_SEARCH flag is set and all fields except the final
  49869. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  49870. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  49871. ** This is used by the OP_IsUnique opcode.
  49872. */
  49873. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  49874. assert( idx1==szHdr1 && rc );
  49875. assert( mem1.flags & MEM_Int );
  49876. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  49877. pPKey2->rowid = mem1.u.i;
  49878. }
  49879. return rc;
  49880. }
  49881. i++;
  49882. }
  49883. /* No memory allocation is ever used on mem1. Prove this using
  49884. ** the following assert(). If the assert() fails, it indicates a
  49885. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  49886. */
  49887. assert( mem1.zMalloc==0 );
  49888. /* rc==0 here means that one of the keys ran out of fields and
  49889. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  49890. ** flag is set, then break the tie by treating key2 as larger.
  49891. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  49892. ** are considered to be equal. Otherwise, the longer key is the
  49893. ** larger. As it happens, the pPKey2 will always be the longer
  49894. ** if there is a difference.
  49895. */
  49896. assert( rc==0 );
  49897. if( pPKey2->flags & UNPACKED_INCRKEY ){
  49898. rc = -1;
  49899. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  49900. /* Leave rc==0 */
  49901. }else if( idx1<szHdr1 ){
  49902. rc = 1;
  49903. }
  49904. return rc;
  49905. }
  49906. /*
  49907. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  49908. ** Read the rowid (the last field in the record) and store it in *rowid.
  49909. ** Return SQLITE_OK if everything works, or an error code otherwise.
  49910. **
  49911. ** pCur might be pointing to text obtained from a corrupt database file.
  49912. ** So the content cannot be trusted. Do appropriate checks on the content.
  49913. */
  49914. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  49915. i64 nCellKey = 0;
  49916. int rc;
  49917. u32 szHdr; /* Size of the header */
  49918. u32 typeRowid; /* Serial type of the rowid */
  49919. u32 lenRowid; /* Size of the rowid */
  49920. Mem m, v;
  49921. UNUSED_PARAMETER(db);
  49922. /* Get the size of the index entry. Only indices entries of less
  49923. ** than 2GiB are support - anything large must be database corruption.
  49924. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  49925. ** this code can safely assume that nCellKey is 32-bits
  49926. */
  49927. assert( sqlite3BtreeCursorIsValid(pCur) );
  49928. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  49929. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  49930. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  49931. /* Read in the complete content of the index entry */
  49932. memset(&m, 0, sizeof(m));
  49933. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  49934. if( rc ){
  49935. return rc;
  49936. }
  49937. /* The index entry must begin with a header size */
  49938. (void)getVarint32((u8*)m.z, szHdr);
  49939. testcase( szHdr==3 );
  49940. testcase( szHdr==m.n );
  49941. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  49942. goto idx_rowid_corruption;
  49943. }
  49944. /* The last field of the index should be an integer - the ROWID.
  49945. ** Verify that the last entry really is an integer. */
  49946. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  49947. testcase( typeRowid==1 );
  49948. testcase( typeRowid==2 );
  49949. testcase( typeRowid==3 );
  49950. testcase( typeRowid==4 );
  49951. testcase( typeRowid==5 );
  49952. testcase( typeRowid==6 );
  49953. testcase( typeRowid==8 );
  49954. testcase( typeRowid==9 );
  49955. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  49956. goto idx_rowid_corruption;
  49957. }
  49958. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  49959. testcase( (u32)m.n==szHdr+lenRowid );
  49960. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  49961. goto idx_rowid_corruption;
  49962. }
  49963. /* Fetch the integer off the end of the index record */
  49964. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  49965. *rowid = v.u.i;
  49966. sqlite3VdbeMemRelease(&m);
  49967. return SQLITE_OK;
  49968. /* Jump here if database corruption is detected after m has been
  49969. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  49970. idx_rowid_corruption:
  49971. testcase( m.zMalloc!=0 );
  49972. sqlite3VdbeMemRelease(&m);
  49973. return SQLITE_CORRUPT_BKPT;
  49974. }
  49975. /*
  49976. ** Compare the key of the index entry that cursor pC is pointing to against
  49977. ** the key string in pUnpacked. Write into *pRes a number
  49978. ** that is negative, zero, or positive if pC is less than, equal to,
  49979. ** or greater than pUnpacked. Return SQLITE_OK on success.
  49980. **
  49981. ** pUnpacked is either created without a rowid or is truncated so that it
  49982. ** omits the rowid at the end. The rowid at the end of the index entry
  49983. ** is ignored as well. Hence, this routine only compares the prefixes
  49984. ** of the keys prior to the final rowid, not the entire key.
  49985. */
  49986. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  49987. VdbeCursor *pC, /* The cursor to compare against */
  49988. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  49989. int *res /* Write the comparison result here */
  49990. ){
  49991. i64 nCellKey = 0;
  49992. int rc;
  49993. BtCursor *pCur = pC->pCursor;
  49994. Mem m;
  49995. assert( sqlite3BtreeCursorIsValid(pCur) );
  49996. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  49997. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  49998. /* nCellKey will always be between 0 and 0xffffffff because of the say
  49999. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  50000. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  50001. *res = 0;
  50002. return SQLITE_CORRUPT_BKPT;
  50003. }
  50004. memset(&m, 0, sizeof(m));
  50005. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  50006. if( rc ){
  50007. return rc;
  50008. }
  50009. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  50010. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  50011. sqlite3VdbeMemRelease(&m);
  50012. return SQLITE_OK;
  50013. }
  50014. /*
  50015. ** This routine sets the value to be returned by subsequent calls to
  50016. ** sqlite3_changes() on the database handle 'db'.
  50017. */
  50018. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  50019. assert( sqlite3_mutex_held(db->mutex) );
  50020. db->nChange = nChange;
  50021. db->nTotalChange += nChange;
  50022. }
  50023. /*
  50024. ** Set a flag in the vdbe to update the change counter when it is finalised
  50025. ** or reset.
  50026. */
  50027. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  50028. v->changeCntOn = 1;
  50029. }
  50030. /*
  50031. ** Mark every prepared statement associated with a database connection
  50032. ** as expired.
  50033. **
  50034. ** An expired statement means that recompilation of the statement is
  50035. ** recommend. Statements expire when things happen that make their
  50036. ** programs obsolete. Removing user-defined functions or collating
  50037. ** sequences, or changing an authorization function are the types of
  50038. ** things that make prepared statements obsolete.
  50039. */
  50040. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  50041. Vdbe *p;
  50042. for(p = db->pVdbe; p; p=p->pNext){
  50043. p->expired = 1;
  50044. }
  50045. }
  50046. /*
  50047. ** Return the database associated with the Vdbe.
  50048. */
  50049. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  50050. return v->db;
  50051. }
  50052. /*
  50053. ** Return a pointer to an sqlite3_value structure containing the value bound
  50054. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  50055. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  50056. ** constants) to the value before returning it.
  50057. **
  50058. ** The returned value must be freed by the caller using sqlite3ValueFree().
  50059. */
  50060. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  50061. assert( iVar>0 );
  50062. if( v ){
  50063. Mem *pMem = &v->aVar[iVar-1];
  50064. if( 0==(pMem->flags & MEM_Null) ){
  50065. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  50066. if( pRet ){
  50067. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  50068. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  50069. sqlite3VdbeMemStoreType((Mem *)pRet);
  50070. }
  50071. return pRet;
  50072. }
  50073. }
  50074. return 0;
  50075. }
  50076. /*
  50077. ** Configure SQL variable iVar so that binding a new value to it signals
  50078. ** to sqlite3_reoptimize() that re-preparing the statement may result
  50079. ** in a better query plan.
  50080. */
  50081. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  50082. assert( iVar>0 );
  50083. if( iVar>32 ){
  50084. v->expmask = 0xffffffff;
  50085. }else{
  50086. v->expmask |= ((u32)1 << (iVar-1));
  50087. }
  50088. }
  50089. #ifndef SQLITE_OMIT_VIRTUALTABLE
  50090. /*
  50091. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  50092. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  50093. ** in memory obtained from sqlite3DbMalloc).
  50094. */
  50095. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  50096. sqlite3 *db = p->db;
  50097. sqlite3DbFree(db, p->zErrMsg);
  50098. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  50099. sqlite3_free(pVtab->zErrMsg);
  50100. pVtab->zErrMsg = 0;
  50101. }
  50102. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  50103. /************** End of vdbeaux.c *********************************************/
  50104. /************** Begin file vdbeapi.c *****************************************/
  50105. /*
  50106. ** 2004 May 26
  50107. **
  50108. ** The author disclaims copyright to this source code. In place of
  50109. ** a legal notice, here is a blessing:
  50110. **
  50111. ** May you do good and not evil.
  50112. ** May you find forgiveness for yourself and forgive others.
  50113. ** May you share freely, never taking more than you give.
  50114. **
  50115. *************************************************************************
  50116. **
  50117. ** This file contains code use to implement APIs that are part of the
  50118. ** VDBE.
  50119. */
  50120. #ifndef SQLITE_OMIT_DEPRECATED
  50121. /*
  50122. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  50123. ** to be recompiled. A statement needs to be recompiled whenever the
  50124. ** execution environment changes in a way that would alter the program
  50125. ** that sqlite3_prepare() generates. For example, if new functions or
  50126. ** collating sequences are registered or if an authorizer function is
  50127. ** added or changed.
  50128. */
  50129. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  50130. Vdbe *p = (Vdbe*)pStmt;
  50131. return p==0 || p->expired;
  50132. }
  50133. #endif
  50134. /*
  50135. ** Check on a Vdbe to make sure it has not been finalized. Log
  50136. ** an error and return true if it has been finalized (or is otherwise
  50137. ** invalid). Return false if it is ok.
  50138. */
  50139. static int vdbeSafety(Vdbe *p){
  50140. if( p->db==0 ){
  50141. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  50142. return 1;
  50143. }else{
  50144. return 0;
  50145. }
  50146. }
  50147. static int vdbeSafetyNotNull(Vdbe *p){
  50148. if( p==0 ){
  50149. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  50150. return 1;
  50151. }else{
  50152. return vdbeSafety(p);
  50153. }
  50154. }
  50155. /*
  50156. ** The following routine destroys a virtual machine that is created by
  50157. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  50158. ** success/failure code that describes the result of executing the virtual
  50159. ** machine.
  50160. **
  50161. ** This routine sets the error code and string returned by
  50162. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  50163. */
  50164. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  50165. int rc;
  50166. if( pStmt==0 ){
  50167. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  50168. ** pointer is a harmless no-op. */
  50169. rc = SQLITE_OK;
  50170. }else{
  50171. Vdbe *v = (Vdbe*)pStmt;
  50172. sqlite3 *db = v->db;
  50173. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  50174. sqlite3_mutex_enter(db->mutex);
  50175. rc = sqlite3VdbeFinalize(v);
  50176. rc = sqlite3ApiExit(db, rc);
  50177. sqlite3LeaveMutexAndCloseZombie(db);
  50178. }
  50179. return rc;
  50180. }
  50181. /*
  50182. ** Terminate the current execution of an SQL statement and reset it
  50183. ** back to its starting state so that it can be reused. A success code from
  50184. ** the prior execution is returned.
  50185. **
  50186. ** This routine sets the error code and string returned by
  50187. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  50188. */
  50189. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  50190. int rc;
  50191. if( pStmt==0 ){
  50192. rc = SQLITE_OK;
  50193. }else{
  50194. Vdbe *v = (Vdbe*)pStmt;
  50195. sqlite3_mutex_enter(v->db->mutex);
  50196. rc = sqlite3VdbeReset(v);
  50197. sqlite3VdbeRewind(v);
  50198. assert( (rc & (v->db->errMask))==rc );
  50199. rc = sqlite3ApiExit(v->db, rc);
  50200. sqlite3_mutex_leave(v->db->mutex);
  50201. }
  50202. return rc;
  50203. }
  50204. /*
  50205. ** Set all the parameters in the compiled SQL statement to NULL.
  50206. */
  50207. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  50208. int i;
  50209. int rc = SQLITE_OK;
  50210. Vdbe *p = (Vdbe*)pStmt;
  50211. #if SQLITE_THREADSAFE
  50212. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  50213. #endif
  50214. sqlite3_mutex_enter(mutex);
  50215. for(i=0; i<p->nVar; i++){
  50216. sqlite3VdbeMemRelease(&p->aVar[i]);
  50217. p->aVar[i].flags = MEM_Null;
  50218. }
  50219. if( p->isPrepareV2 && p->expmask ){
  50220. p->expired = 1;
  50221. }
  50222. sqlite3_mutex_leave(mutex);
  50223. return rc;
  50224. }
  50225. /**************************** sqlite3_value_ *******************************
  50226. ** The following routines extract information from a Mem or sqlite3_value
  50227. ** structure.
  50228. */
  50229. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  50230. Mem *p = (Mem*)pVal;
  50231. if( p->flags & (MEM_Blob|MEM_Str) ){
  50232. sqlite3VdbeMemExpandBlob(p);
  50233. p->flags &= ~MEM_Str;
  50234. p->flags |= MEM_Blob;
  50235. return p->n ? p->z : 0;
  50236. }else{
  50237. return sqlite3_value_text(pVal);
  50238. }
  50239. }
  50240. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  50241. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  50242. }
  50243. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  50244. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  50245. }
  50246. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  50247. return sqlite3VdbeRealValue((Mem*)pVal);
  50248. }
  50249. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  50250. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  50251. }
  50252. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  50253. return sqlite3VdbeIntValue((Mem*)pVal);
  50254. }
  50255. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  50256. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  50257. }
  50258. #ifndef SQLITE_OMIT_UTF16
  50259. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  50260. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  50261. }
  50262. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  50263. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  50264. }
  50265. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  50266. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  50267. }
  50268. #endif /* SQLITE_OMIT_UTF16 */
  50269. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  50270. return pVal->type;
  50271. }
  50272. /**************************** sqlite3_result_ *******************************
  50273. ** The following routines are used by user-defined functions to specify
  50274. ** the function result.
  50275. **
  50276. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  50277. ** result as a string or blob but if the string or blob is too large, it
  50278. ** then sets the error code to SQLITE_TOOBIG
  50279. */
  50280. static void setResultStrOrError(
  50281. sqlite3_context *pCtx, /* Function context */
  50282. const char *z, /* String pointer */
  50283. int n, /* Bytes in string, or negative */
  50284. u8 enc, /* Encoding of z. 0 for BLOBs */
  50285. void (*xDel)(void*) /* Destructor function */
  50286. ){
  50287. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  50288. sqlite3_result_error_toobig(pCtx);
  50289. }
  50290. }
  50291. SQLITE_API void sqlite3_result_blob(
  50292. sqlite3_context *pCtx,
  50293. const void *z,
  50294. int n,
  50295. void (*xDel)(void *)
  50296. ){
  50297. assert( n>=0 );
  50298. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50299. setResultStrOrError(pCtx, z, n, 0, xDel);
  50300. }
  50301. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  50302. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50303. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  50304. }
  50305. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  50306. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50307. pCtx->isError = SQLITE_ERROR;
  50308. pCtx->fErrorOrAux = 1;
  50309. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  50310. }
  50311. #ifndef SQLITE_OMIT_UTF16
  50312. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  50313. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50314. pCtx->isError = SQLITE_ERROR;
  50315. pCtx->fErrorOrAux = 1;
  50316. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  50317. }
  50318. #endif
  50319. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  50320. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50321. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  50322. }
  50323. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  50324. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50325. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  50326. }
  50327. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  50328. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50329. sqlite3VdbeMemSetNull(&pCtx->s);
  50330. }
  50331. SQLITE_API void sqlite3_result_text(
  50332. sqlite3_context *pCtx,
  50333. const char *z,
  50334. int n,
  50335. void (*xDel)(void *)
  50336. ){
  50337. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50338. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  50339. }
  50340. #ifndef SQLITE_OMIT_UTF16
  50341. SQLITE_API void sqlite3_result_text16(
  50342. sqlite3_context *pCtx,
  50343. const void *z,
  50344. int n,
  50345. void (*xDel)(void *)
  50346. ){
  50347. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50348. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  50349. }
  50350. SQLITE_API void sqlite3_result_text16be(
  50351. sqlite3_context *pCtx,
  50352. const void *z,
  50353. int n,
  50354. void (*xDel)(void *)
  50355. ){
  50356. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50357. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  50358. }
  50359. SQLITE_API void sqlite3_result_text16le(
  50360. sqlite3_context *pCtx,
  50361. const void *z,
  50362. int n,
  50363. void (*xDel)(void *)
  50364. ){
  50365. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50366. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  50367. }
  50368. #endif /* SQLITE_OMIT_UTF16 */
  50369. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  50370. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50371. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  50372. }
  50373. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  50374. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50375. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  50376. }
  50377. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  50378. pCtx->isError = errCode;
  50379. pCtx->fErrorOrAux = 1;
  50380. if( pCtx->s.flags & MEM_Null ){
  50381. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  50382. SQLITE_UTF8, SQLITE_STATIC);
  50383. }
  50384. }
  50385. /* Force an SQLITE_TOOBIG error. */
  50386. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  50387. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50388. pCtx->isError = SQLITE_TOOBIG;
  50389. pCtx->fErrorOrAux = 1;
  50390. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  50391. SQLITE_UTF8, SQLITE_STATIC);
  50392. }
  50393. /* An SQLITE_NOMEM error. */
  50394. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  50395. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50396. sqlite3VdbeMemSetNull(&pCtx->s);
  50397. pCtx->isError = SQLITE_NOMEM;
  50398. pCtx->fErrorOrAux = 1;
  50399. pCtx->s.db->mallocFailed = 1;
  50400. }
  50401. /*
  50402. ** This function is called after a transaction has been committed. It
  50403. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  50404. */
  50405. static int doWalCallbacks(sqlite3 *db){
  50406. int rc = SQLITE_OK;
  50407. #ifndef SQLITE_OMIT_WAL
  50408. int i;
  50409. for(i=0; i<db->nDb; i++){
  50410. Btree *pBt = db->aDb[i].pBt;
  50411. if( pBt ){
  50412. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  50413. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  50414. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  50415. }
  50416. }
  50417. }
  50418. #endif
  50419. return rc;
  50420. }
  50421. /*
  50422. ** Execute the statement pStmt, either until a row of data is ready, the
  50423. ** statement is completely executed or an error occurs.
  50424. **
  50425. ** This routine implements the bulk of the logic behind the sqlite_step()
  50426. ** API. The only thing omitted is the automatic recompile if a
  50427. ** schema change has occurred. That detail is handled by the
  50428. ** outer sqlite3_step() wrapper procedure.
  50429. */
  50430. static int sqlite3Step(Vdbe *p){
  50431. sqlite3 *db;
  50432. int rc;
  50433. assert(p);
  50434. if( p->magic!=VDBE_MAGIC_RUN ){
  50435. /* We used to require that sqlite3_reset() be called before retrying
  50436. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  50437. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  50438. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  50439. ** This "automatic-reset" change is not technically an incompatibility,
  50440. ** since any application that receives an SQLITE_MISUSE is broken by
  50441. ** definition.
  50442. **
  50443. ** Nevertheless, some published applications that were originally written
  50444. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  50445. ** returns, and those were broken by the automatic-reset change. As a
  50446. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  50447. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  50448. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  50449. ** or SQLITE_BUSY error.
  50450. */
  50451. #ifdef SQLITE_OMIT_AUTORESET
  50452. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  50453. sqlite3_reset((sqlite3_stmt*)p);
  50454. }else{
  50455. return SQLITE_MISUSE_BKPT;
  50456. }
  50457. #else
  50458. sqlite3_reset((sqlite3_stmt*)p);
  50459. #endif
  50460. }
  50461. /* Check that malloc() has not failed. If it has, return early. */
  50462. db = p->db;
  50463. if( db->mallocFailed ){
  50464. p->rc = SQLITE_NOMEM;
  50465. return SQLITE_NOMEM;
  50466. }
  50467. if( p->pc<=0 && p->expired ){
  50468. p->rc = SQLITE_SCHEMA;
  50469. rc = SQLITE_ERROR;
  50470. goto end_of_step;
  50471. }
  50472. if( p->pc<0 ){
  50473. /* If there are no other statements currently running, then
  50474. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  50475. ** from interrupting a statement that has not yet started.
  50476. */
  50477. if( db->nVdbeActive==0 ){
  50478. db->u1.isInterrupted = 0;
  50479. }
  50480. assert( db->nVdbeWrite>0 || db->autoCommit==0
  50481. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  50482. );
  50483. #ifndef SQLITE_OMIT_TRACE
  50484. if( db->xProfile && !db->init.busy ){
  50485. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  50486. }
  50487. #endif
  50488. db->nVdbeActive++;
  50489. if( p->readOnly==0 ) db->nVdbeWrite++;
  50490. if( p->bIsReader ) db->nVdbeRead++;
  50491. p->pc = 0;
  50492. }
  50493. #ifndef SQLITE_OMIT_EXPLAIN
  50494. if( p->explain ){
  50495. rc = sqlite3VdbeList(p);
  50496. }else
  50497. #endif /* SQLITE_OMIT_EXPLAIN */
  50498. {
  50499. db->nVdbeExec++;
  50500. rc = sqlite3VdbeExec(p);
  50501. db->nVdbeExec--;
  50502. }
  50503. #ifndef SQLITE_OMIT_TRACE
  50504. /* Invoke the profile callback if there is one
  50505. */
  50506. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  50507. sqlite3_int64 iNow;
  50508. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  50509. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  50510. }
  50511. #endif
  50512. if( rc==SQLITE_DONE ){
  50513. assert( p->rc==SQLITE_OK );
  50514. p->rc = doWalCallbacks(db);
  50515. if( p->rc!=SQLITE_OK ){
  50516. rc = SQLITE_ERROR;
  50517. }
  50518. }
  50519. db->errCode = rc;
  50520. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  50521. p->rc = SQLITE_NOMEM;
  50522. }
  50523. end_of_step:
  50524. /* At this point local variable rc holds the value that should be
  50525. ** returned if this statement was compiled using the legacy
  50526. ** sqlite3_prepare() interface. According to the docs, this can only
  50527. ** be one of the values in the first assert() below. Variable p->rc
  50528. ** contains the value that would be returned if sqlite3_finalize()
  50529. ** were called on statement p.
  50530. */
  50531. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  50532. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  50533. );
  50534. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  50535. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  50536. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  50537. ** error has occurred, then return the error code in p->rc to the
  50538. ** caller. Set the error code in the database handle to the same value.
  50539. */
  50540. rc = sqlite3VdbeTransferError(p);
  50541. }
  50542. return (rc&db->errMask);
  50543. }
  50544. /*
  50545. ** This is the top-level implementation of sqlite3_step(). Call
  50546. ** sqlite3Step() to do most of the work. If a schema error occurs,
  50547. ** call sqlite3Reprepare() and try again.
  50548. */
  50549. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  50550. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  50551. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  50552. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  50553. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  50554. sqlite3 *db; /* The database connection */
  50555. if( vdbeSafetyNotNull(v) ){
  50556. return SQLITE_MISUSE_BKPT;
  50557. }
  50558. db = v->db;
  50559. sqlite3_mutex_enter(db->mutex);
  50560. v->doingRerun = 0;
  50561. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  50562. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  50563. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  50564. sqlite3_reset(pStmt);
  50565. v->doingRerun = 1;
  50566. assert( v->expired==0 );
  50567. }
  50568. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  50569. /* This case occurs after failing to recompile an sql statement.
  50570. ** The error message from the SQL compiler has already been loaded
  50571. ** into the database handle. This block copies the error message
  50572. ** from the database handle into the statement and sets the statement
  50573. ** program counter to 0 to ensure that when the statement is
  50574. ** finalized or reset the parser error message is available via
  50575. ** sqlite3_errmsg() and sqlite3_errcode().
  50576. */
  50577. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  50578. sqlite3DbFree(db, v->zErrMsg);
  50579. if( !db->mallocFailed ){
  50580. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  50581. v->rc = rc2;
  50582. } else {
  50583. v->zErrMsg = 0;
  50584. v->rc = rc = SQLITE_NOMEM;
  50585. }
  50586. }
  50587. rc = sqlite3ApiExit(db, rc);
  50588. sqlite3_mutex_leave(db->mutex);
  50589. return rc;
  50590. }
  50591. /*
  50592. ** Extract the user data from a sqlite3_context structure and return a
  50593. ** pointer to it.
  50594. */
  50595. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  50596. assert( p && p->pFunc );
  50597. return p->pFunc->pUserData;
  50598. }
  50599. /*
  50600. ** Extract the user data from a sqlite3_context structure and return a
  50601. ** pointer to it.
  50602. **
  50603. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  50604. ** returns a copy of the pointer to the database connection (the 1st
  50605. ** parameter) of the sqlite3_create_function() and
  50606. ** sqlite3_create_function16() routines that originally registered the
  50607. ** application defined function.
  50608. */
  50609. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  50610. assert( p && p->pFunc );
  50611. return p->s.db;
  50612. }
  50613. /*
  50614. ** Return the current time for a statement
  50615. */
  50616. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  50617. Vdbe *v = p->pVdbe;
  50618. int rc;
  50619. if( v->iCurrentTime==0 ){
  50620. rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
  50621. if( rc ) v->iCurrentTime = 0;
  50622. }
  50623. return v->iCurrentTime;
  50624. }
  50625. /*
  50626. ** The following is the implementation of an SQL function that always
  50627. ** fails with an error message stating that the function is used in the
  50628. ** wrong context. The sqlite3_overload_function() API might construct
  50629. ** SQL function that use this routine so that the functions will exist
  50630. ** for name resolution but are actually overloaded by the xFindFunction
  50631. ** method of virtual tables.
  50632. */
  50633. SQLITE_PRIVATE void sqlite3InvalidFunction(
  50634. sqlite3_context *context, /* The function calling context */
  50635. int NotUsed, /* Number of arguments to the function */
  50636. sqlite3_value **NotUsed2 /* Value of each argument */
  50637. ){
  50638. const char *zName = context->pFunc->zName;
  50639. char *zErr;
  50640. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  50641. zErr = sqlite3_mprintf(
  50642. "unable to use function %s in the requested context", zName);
  50643. sqlite3_result_error(context, zErr, -1);
  50644. sqlite3_free(zErr);
  50645. }
  50646. /*
  50647. ** Allocate or return the aggregate context for a user function. A new
  50648. ** context is allocated on the first call. Subsequent calls return the
  50649. ** same context that was returned on prior calls.
  50650. */
  50651. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  50652. Mem *pMem;
  50653. assert( p && p->pFunc && p->pFunc->xStep );
  50654. assert( sqlite3_mutex_held(p->s.db->mutex) );
  50655. pMem = p->pMem;
  50656. testcase( nByte<0 );
  50657. if( (pMem->flags & MEM_Agg)==0 ){
  50658. if( nByte<=0 ){
  50659. sqlite3VdbeMemReleaseExternal(pMem);
  50660. pMem->flags = MEM_Null;
  50661. pMem->z = 0;
  50662. }else{
  50663. sqlite3VdbeMemGrow(pMem, nByte, 0);
  50664. pMem->flags = MEM_Agg;
  50665. pMem->u.pDef = p->pFunc;
  50666. if( pMem->z ){
  50667. memset(pMem->z, 0, nByte);
  50668. }
  50669. }
  50670. }
  50671. return (void*)pMem->z;
  50672. }
  50673. /*
  50674. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  50675. ** the user-function defined by pCtx.
  50676. */
  50677. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  50678. AuxData *pAuxData;
  50679. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50680. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  50681. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  50682. }
  50683. return (pAuxData ? pAuxData->pAux : 0);
  50684. }
  50685. /*
  50686. ** Set the auxilary data pointer and delete function, for the iArg'th
  50687. ** argument to the user-function defined by pCtx. Any previous value is
  50688. ** deleted by calling the delete function specified when it was set.
  50689. */
  50690. SQLITE_API void sqlite3_set_auxdata(
  50691. sqlite3_context *pCtx,
  50692. int iArg,
  50693. void *pAux,
  50694. void (*xDelete)(void*)
  50695. ){
  50696. AuxData *pAuxData;
  50697. Vdbe *pVdbe = pCtx->pVdbe;
  50698. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  50699. if( iArg<0 ) goto failed;
  50700. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  50701. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  50702. }
  50703. if( pAuxData==0 ){
  50704. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  50705. if( !pAuxData ) goto failed;
  50706. pAuxData->iOp = pCtx->iOp;
  50707. pAuxData->iArg = iArg;
  50708. pAuxData->pNext = pVdbe->pAuxData;
  50709. pVdbe->pAuxData = pAuxData;
  50710. if( pCtx->fErrorOrAux==0 ){
  50711. pCtx->isError = 0;
  50712. pCtx->fErrorOrAux = 1;
  50713. }
  50714. }else if( pAuxData->xDelete ){
  50715. pAuxData->xDelete(pAuxData->pAux);
  50716. }
  50717. pAuxData->pAux = pAux;
  50718. pAuxData->xDelete = xDelete;
  50719. return;
  50720. failed:
  50721. if( xDelete ){
  50722. xDelete(pAux);
  50723. }
  50724. }
  50725. #ifndef SQLITE_OMIT_DEPRECATED
  50726. /*
  50727. ** Return the number of times the Step function of a aggregate has been
  50728. ** called.
  50729. **
  50730. ** This function is deprecated. Do not use it for new code. It is
  50731. ** provide only to avoid breaking legacy code. New aggregate function
  50732. ** implementations should keep their own counts within their aggregate
  50733. ** context.
  50734. */
  50735. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  50736. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  50737. return p->pMem->n;
  50738. }
  50739. #endif
  50740. /*
  50741. ** Return the number of columns in the result set for the statement pStmt.
  50742. */
  50743. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  50744. Vdbe *pVm = (Vdbe *)pStmt;
  50745. return pVm ? pVm->nResColumn : 0;
  50746. }
  50747. /*
  50748. ** Return the number of values available from the current row of the
  50749. ** currently executing statement pStmt.
  50750. */
  50751. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  50752. Vdbe *pVm = (Vdbe *)pStmt;
  50753. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  50754. return pVm->nResColumn;
  50755. }
  50756. /*
  50757. ** Check to see if column iCol of the given statement is valid. If
  50758. ** it is, return a pointer to the Mem for the value of that column.
  50759. ** If iCol is not valid, return a pointer to a Mem which has a value
  50760. ** of NULL.
  50761. */
  50762. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  50763. Vdbe *pVm;
  50764. Mem *pOut;
  50765. pVm = (Vdbe *)pStmt;
  50766. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  50767. sqlite3_mutex_enter(pVm->db->mutex);
  50768. pOut = &pVm->pResultSet[i];
  50769. }else{
  50770. /* If the value passed as the second argument is out of range, return
  50771. ** a pointer to the following static Mem object which contains the
  50772. ** value SQL NULL. Even though the Mem structure contains an element
  50773. ** of type i64, on certain architectures (x86) with certain compiler
  50774. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  50775. ** instead of an 8-byte one. This all works fine, except that when
  50776. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  50777. ** that a Mem structure is located on an 8-byte boundary. To prevent
  50778. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  50779. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  50780. ** __attribute__((aligned(8))) macro. */
  50781. static const Mem nullMem
  50782. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  50783. __attribute__((aligned(8)))
  50784. #endif
  50785. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  50786. #ifdef SQLITE_DEBUG
  50787. 0, 0, /* pScopyFrom, pFiller */
  50788. #endif
  50789. 0, 0 };
  50790. if( pVm && ALWAYS(pVm->db) ){
  50791. sqlite3_mutex_enter(pVm->db->mutex);
  50792. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  50793. }
  50794. pOut = (Mem*)&nullMem;
  50795. }
  50796. return pOut;
  50797. }
  50798. /*
  50799. ** This function is called after invoking an sqlite3_value_XXX function on a
  50800. ** column value (i.e. a value returned by evaluating an SQL expression in the
  50801. ** select list of a SELECT statement) that may cause a malloc() failure. If
  50802. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  50803. ** code of statement pStmt set to SQLITE_NOMEM.
  50804. **
  50805. ** Specifically, this is called from within:
  50806. **
  50807. ** sqlite3_column_int()
  50808. ** sqlite3_column_int64()
  50809. ** sqlite3_column_text()
  50810. ** sqlite3_column_text16()
  50811. ** sqlite3_column_real()
  50812. ** sqlite3_column_bytes()
  50813. ** sqlite3_column_bytes16()
  50814. ** sqiite3_column_blob()
  50815. */
  50816. static void columnMallocFailure(sqlite3_stmt *pStmt)
  50817. {
  50818. /* If malloc() failed during an encoding conversion within an
  50819. ** sqlite3_column_XXX API, then set the return code of the statement to
  50820. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  50821. ** and _finalize() will return NOMEM.
  50822. */
  50823. Vdbe *p = (Vdbe *)pStmt;
  50824. if( p ){
  50825. p->rc = sqlite3ApiExit(p->db, p->rc);
  50826. sqlite3_mutex_leave(p->db->mutex);
  50827. }
  50828. }
  50829. /**************************** sqlite3_column_ *******************************
  50830. ** The following routines are used to access elements of the current row
  50831. ** in the result set.
  50832. */
  50833. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  50834. const void *val;
  50835. val = sqlite3_value_blob( columnMem(pStmt,i) );
  50836. /* Even though there is no encoding conversion, value_blob() might
  50837. ** need to call malloc() to expand the result of a zeroblob()
  50838. ** expression.
  50839. */
  50840. columnMallocFailure(pStmt);
  50841. return val;
  50842. }
  50843. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  50844. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  50845. columnMallocFailure(pStmt);
  50846. return val;
  50847. }
  50848. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  50849. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  50850. columnMallocFailure(pStmt);
  50851. return val;
  50852. }
  50853. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  50854. double val = sqlite3_value_double( columnMem(pStmt,i) );
  50855. columnMallocFailure(pStmt);
  50856. return val;
  50857. }
  50858. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  50859. int val = sqlite3_value_int( columnMem(pStmt,i) );
  50860. columnMallocFailure(pStmt);
  50861. return val;
  50862. }
  50863. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  50864. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  50865. columnMallocFailure(pStmt);
  50866. return val;
  50867. }
  50868. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  50869. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  50870. columnMallocFailure(pStmt);
  50871. return val;
  50872. }
  50873. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  50874. Mem *pOut = columnMem(pStmt, i);
  50875. if( pOut->flags&MEM_Static ){
  50876. pOut->flags &= ~MEM_Static;
  50877. pOut->flags |= MEM_Ephem;
  50878. }
  50879. columnMallocFailure(pStmt);
  50880. return (sqlite3_value *)pOut;
  50881. }
  50882. #ifndef SQLITE_OMIT_UTF16
  50883. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  50884. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  50885. columnMallocFailure(pStmt);
  50886. return val;
  50887. }
  50888. #endif /* SQLITE_OMIT_UTF16 */
  50889. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  50890. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  50891. columnMallocFailure(pStmt);
  50892. return iType;
  50893. }
  50894. /*
  50895. ** Convert the N-th element of pStmt->pColName[] into a string using
  50896. ** xFunc() then return that string. If N is out of range, return 0.
  50897. **
  50898. ** There are up to 5 names for each column. useType determines which
  50899. ** name is returned. Here are the names:
  50900. **
  50901. ** 0 The column name as it should be displayed for output
  50902. ** 1 The datatype name for the column
  50903. ** 2 The name of the database that the column derives from
  50904. ** 3 The name of the table that the column derives from
  50905. ** 4 The name of the table column that the result column derives from
  50906. **
  50907. ** If the result is not a simple column reference (if it is an expression
  50908. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  50909. */
  50910. static const void *columnName(
  50911. sqlite3_stmt *pStmt,
  50912. int N,
  50913. const void *(*xFunc)(Mem*),
  50914. int useType
  50915. ){
  50916. const void *ret = 0;
  50917. Vdbe *p = (Vdbe *)pStmt;
  50918. int n;
  50919. sqlite3 *db = p->db;
  50920. assert( db!=0 );
  50921. n = sqlite3_column_count(pStmt);
  50922. if( N<n && N>=0 ){
  50923. N += useType*n;
  50924. sqlite3_mutex_enter(db->mutex);
  50925. assert( db->mallocFailed==0 );
  50926. ret = xFunc(&p->aColName[N]);
  50927. /* A malloc may have failed inside of the xFunc() call. If this
  50928. ** is the case, clear the mallocFailed flag and return NULL.
  50929. */
  50930. if( db->mallocFailed ){
  50931. db->mallocFailed = 0;
  50932. ret = 0;
  50933. }
  50934. sqlite3_mutex_leave(db->mutex);
  50935. }
  50936. return ret;
  50937. }
  50938. /*
  50939. ** Return the name of the Nth column of the result set returned by SQL
  50940. ** statement pStmt.
  50941. */
  50942. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  50943. return columnName(
  50944. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  50945. }
  50946. #ifndef SQLITE_OMIT_UTF16
  50947. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  50948. return columnName(
  50949. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  50950. }
  50951. #endif
  50952. /*
  50953. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  50954. ** not define OMIT_DECLTYPE.
  50955. */
  50956. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  50957. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  50958. and SQLITE_ENABLE_COLUMN_METADATA"
  50959. #endif
  50960. #ifndef SQLITE_OMIT_DECLTYPE
  50961. /*
  50962. ** Return the column declaration type (if applicable) of the 'i'th column
  50963. ** of the result set of SQL statement pStmt.
  50964. */
  50965. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  50966. return columnName(
  50967. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  50968. }
  50969. #ifndef SQLITE_OMIT_UTF16
  50970. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  50971. return columnName(
  50972. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  50973. }
  50974. #endif /* SQLITE_OMIT_UTF16 */
  50975. #endif /* SQLITE_OMIT_DECLTYPE */
  50976. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  50977. /*
  50978. ** Return the name of the database from which a result column derives.
  50979. ** NULL is returned if the result column is an expression or constant or
  50980. ** anything else which is not an unabiguous reference to a database column.
  50981. */
  50982. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  50983. return columnName(
  50984. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  50985. }
  50986. #ifndef SQLITE_OMIT_UTF16
  50987. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  50988. return columnName(
  50989. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  50990. }
  50991. #endif /* SQLITE_OMIT_UTF16 */
  50992. /*
  50993. ** Return the name of the table from which a result column derives.
  50994. ** NULL is returned if the result column is an expression or constant or
  50995. ** anything else which is not an unabiguous reference to a database column.
  50996. */
  50997. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  50998. return columnName(
  50999. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  51000. }
  51001. #ifndef SQLITE_OMIT_UTF16
  51002. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  51003. return columnName(
  51004. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  51005. }
  51006. #endif /* SQLITE_OMIT_UTF16 */
  51007. /*
  51008. ** Return the name of the table column from which a result column derives.
  51009. ** NULL is returned if the result column is an expression or constant or
  51010. ** anything else which is not an unabiguous reference to a database column.
  51011. */
  51012. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  51013. return columnName(
  51014. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  51015. }
  51016. #ifndef SQLITE_OMIT_UTF16
  51017. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  51018. return columnName(
  51019. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  51020. }
  51021. #endif /* SQLITE_OMIT_UTF16 */
  51022. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  51023. /******************************* sqlite3_bind_ ***************************
  51024. **
  51025. ** Routines used to attach values to wildcards in a compiled SQL statement.
  51026. */
  51027. /*
  51028. ** Unbind the value bound to variable i in virtual machine p. This is the
  51029. ** the same as binding a NULL value to the column. If the "i" parameter is
  51030. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  51031. **
  51032. ** A successful evaluation of this routine acquires the mutex on p.
  51033. ** the mutex is released if any kind of error occurs.
  51034. **
  51035. ** The error code stored in database p->db is overwritten with the return
  51036. ** value in any case.
  51037. */
  51038. static int vdbeUnbind(Vdbe *p, int i){
  51039. Mem *pVar;
  51040. if( vdbeSafetyNotNull(p) ){
  51041. return SQLITE_MISUSE_BKPT;
  51042. }
  51043. sqlite3_mutex_enter(p->db->mutex);
  51044. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  51045. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  51046. sqlite3_mutex_leave(p->db->mutex);
  51047. sqlite3_log(SQLITE_MISUSE,
  51048. "bind on a busy prepared statement: [%s]", p->zSql);
  51049. return SQLITE_MISUSE_BKPT;
  51050. }
  51051. if( i<1 || i>p->nVar ){
  51052. sqlite3Error(p->db, SQLITE_RANGE, 0);
  51053. sqlite3_mutex_leave(p->db->mutex);
  51054. return SQLITE_RANGE;
  51055. }
  51056. i--;
  51057. pVar = &p->aVar[i];
  51058. sqlite3VdbeMemRelease(pVar);
  51059. pVar->flags = MEM_Null;
  51060. sqlite3Error(p->db, SQLITE_OK, 0);
  51061. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  51062. ** binding a new value to this variable invalidates the current query plan.
  51063. **
  51064. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  51065. ** parameter in the WHERE clause might influence the choice of query plan
  51066. ** for a statement, then the statement will be automatically recompiled,
  51067. ** as if there had been a schema change, on the first sqlite3_step() call
  51068. ** following any change to the bindings of that parameter.
  51069. */
  51070. if( p->isPrepareV2 &&
  51071. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  51072. ){
  51073. p->expired = 1;
  51074. }
  51075. return SQLITE_OK;
  51076. }
  51077. /*
  51078. ** Bind a text or BLOB value.
  51079. */
  51080. static int bindText(
  51081. sqlite3_stmt *pStmt, /* The statement to bind against */
  51082. int i, /* Index of the parameter to bind */
  51083. const void *zData, /* Pointer to the data to be bound */
  51084. int nData, /* Number of bytes of data to be bound */
  51085. void (*xDel)(void*), /* Destructor for the data */
  51086. u8 encoding /* Encoding for the data */
  51087. ){
  51088. Vdbe *p = (Vdbe *)pStmt;
  51089. Mem *pVar;
  51090. int rc;
  51091. rc = vdbeUnbind(p, i);
  51092. if( rc==SQLITE_OK ){
  51093. if( zData!=0 ){
  51094. pVar = &p->aVar[i-1];
  51095. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  51096. if( rc==SQLITE_OK && encoding!=0 ){
  51097. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  51098. }
  51099. sqlite3Error(p->db, rc, 0);
  51100. rc = sqlite3ApiExit(p->db, rc);
  51101. }
  51102. sqlite3_mutex_leave(p->db->mutex);
  51103. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  51104. xDel((void*)zData);
  51105. }
  51106. return rc;
  51107. }
  51108. /*
  51109. ** Bind a blob value to an SQL statement variable.
  51110. */
  51111. SQLITE_API int sqlite3_bind_blob(
  51112. sqlite3_stmt *pStmt,
  51113. int i,
  51114. const void *zData,
  51115. int nData,
  51116. void (*xDel)(void*)
  51117. ){
  51118. return bindText(pStmt, i, zData, nData, xDel, 0);
  51119. }
  51120. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  51121. int rc;
  51122. Vdbe *p = (Vdbe *)pStmt;
  51123. rc = vdbeUnbind(p, i);
  51124. if( rc==SQLITE_OK ){
  51125. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  51126. sqlite3_mutex_leave(p->db->mutex);
  51127. }
  51128. return rc;
  51129. }
  51130. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  51131. return sqlite3_bind_int64(p, i, (i64)iValue);
  51132. }
  51133. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  51134. int rc;
  51135. Vdbe *p = (Vdbe *)pStmt;
  51136. rc = vdbeUnbind(p, i);
  51137. if( rc==SQLITE_OK ){
  51138. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  51139. sqlite3_mutex_leave(p->db->mutex);
  51140. }
  51141. return rc;
  51142. }
  51143. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  51144. int rc;
  51145. Vdbe *p = (Vdbe*)pStmt;
  51146. rc = vdbeUnbind(p, i);
  51147. if( rc==SQLITE_OK ){
  51148. sqlite3_mutex_leave(p->db->mutex);
  51149. }
  51150. return rc;
  51151. }
  51152. SQLITE_API int sqlite3_bind_text(
  51153. sqlite3_stmt *pStmt,
  51154. int i,
  51155. const char *zData,
  51156. int nData,
  51157. void (*xDel)(void*)
  51158. ){
  51159. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  51160. }
  51161. #ifndef SQLITE_OMIT_UTF16
  51162. SQLITE_API int sqlite3_bind_text16(
  51163. sqlite3_stmt *pStmt,
  51164. int i,
  51165. const void *zData,
  51166. int nData,
  51167. void (*xDel)(void*)
  51168. ){
  51169. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  51170. }
  51171. #endif /* SQLITE_OMIT_UTF16 */
  51172. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  51173. int rc;
  51174. switch( pValue->type ){
  51175. case SQLITE_INTEGER: {
  51176. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  51177. break;
  51178. }
  51179. case SQLITE_FLOAT: {
  51180. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  51181. break;
  51182. }
  51183. case SQLITE_BLOB: {
  51184. if( pValue->flags & MEM_Zero ){
  51185. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  51186. }else{
  51187. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  51188. }
  51189. break;
  51190. }
  51191. case SQLITE_TEXT: {
  51192. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  51193. pValue->enc);
  51194. break;
  51195. }
  51196. default: {
  51197. rc = sqlite3_bind_null(pStmt, i);
  51198. break;
  51199. }
  51200. }
  51201. return rc;
  51202. }
  51203. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  51204. int rc;
  51205. Vdbe *p = (Vdbe *)pStmt;
  51206. rc = vdbeUnbind(p, i);
  51207. if( rc==SQLITE_OK ){
  51208. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  51209. sqlite3_mutex_leave(p->db->mutex);
  51210. }
  51211. return rc;
  51212. }
  51213. /*
  51214. ** Return the number of wildcards that can be potentially bound to.
  51215. ** This routine is added to support DBD::SQLite.
  51216. */
  51217. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  51218. Vdbe *p = (Vdbe*)pStmt;
  51219. return p ? p->nVar : 0;
  51220. }
  51221. /*
  51222. ** Return the name of a wildcard parameter. Return NULL if the index
  51223. ** is out of range or if the wildcard is unnamed.
  51224. **
  51225. ** The result is always UTF-8.
  51226. */
  51227. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  51228. Vdbe *p = (Vdbe*)pStmt;
  51229. if( p==0 || i<1 || i>p->nzVar ){
  51230. return 0;
  51231. }
  51232. return p->azVar[i-1];
  51233. }
  51234. /*
  51235. ** Given a wildcard parameter name, return the index of the variable
  51236. ** with that name. If there is no variable with the given name,
  51237. ** return 0.
  51238. */
  51239. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  51240. int i;
  51241. if( p==0 ){
  51242. return 0;
  51243. }
  51244. if( zName ){
  51245. for(i=0; i<p->nzVar; i++){
  51246. const char *z = p->azVar[i];
  51247. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  51248. return i+1;
  51249. }
  51250. }
  51251. }
  51252. return 0;
  51253. }
  51254. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  51255. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  51256. }
  51257. /*
  51258. ** Transfer all bindings from the first statement over to the second.
  51259. */
  51260. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  51261. Vdbe *pFrom = (Vdbe*)pFromStmt;
  51262. Vdbe *pTo = (Vdbe*)pToStmt;
  51263. int i;
  51264. assert( pTo->db==pFrom->db );
  51265. assert( pTo->nVar==pFrom->nVar );
  51266. sqlite3_mutex_enter(pTo->db->mutex);
  51267. for(i=0; i<pFrom->nVar; i++){
  51268. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  51269. }
  51270. sqlite3_mutex_leave(pTo->db->mutex);
  51271. return SQLITE_OK;
  51272. }
  51273. #ifndef SQLITE_OMIT_DEPRECATED
  51274. /*
  51275. ** Deprecated external interface. Internal/core SQLite code
  51276. ** should call sqlite3TransferBindings.
  51277. **
  51278. ** Is is misuse to call this routine with statements from different
  51279. ** database connections. But as this is a deprecated interface, we
  51280. ** will not bother to check for that condition.
  51281. **
  51282. ** If the two statements contain a different number of bindings, then
  51283. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  51284. ** SQLITE_OK is returned.
  51285. */
  51286. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  51287. Vdbe *pFrom = (Vdbe*)pFromStmt;
  51288. Vdbe *pTo = (Vdbe*)pToStmt;
  51289. if( pFrom->nVar!=pTo->nVar ){
  51290. return SQLITE_ERROR;
  51291. }
  51292. if( pTo->isPrepareV2 && pTo->expmask ){
  51293. pTo->expired = 1;
  51294. }
  51295. if( pFrom->isPrepareV2 && pFrom->expmask ){
  51296. pFrom->expired = 1;
  51297. }
  51298. return sqlite3TransferBindings(pFromStmt, pToStmt);
  51299. }
  51300. #endif
  51301. /*
  51302. ** Return the sqlite3* database handle to which the prepared statement given
  51303. ** in the argument belongs. This is the same database handle that was
  51304. ** the first argument to the sqlite3_prepare() that was used to create
  51305. ** the statement in the first place.
  51306. */
  51307. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  51308. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  51309. }
  51310. /*
  51311. ** Return true if the prepared statement is guaranteed to not modify the
  51312. ** database.
  51313. */
  51314. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  51315. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  51316. }
  51317. /*
  51318. ** Return true if the prepared statement is in need of being reset.
  51319. */
  51320. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  51321. Vdbe *v = (Vdbe*)pStmt;
  51322. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  51323. }
  51324. /*
  51325. ** Return a pointer to the next prepared statement after pStmt associated
  51326. ** with database connection pDb. If pStmt is NULL, return the first
  51327. ** prepared statement for the database connection. Return NULL if there
  51328. ** are no more.
  51329. */
  51330. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  51331. sqlite3_stmt *pNext;
  51332. sqlite3_mutex_enter(pDb->mutex);
  51333. if( pStmt==0 ){
  51334. pNext = (sqlite3_stmt*)pDb->pVdbe;
  51335. }else{
  51336. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  51337. }
  51338. sqlite3_mutex_leave(pDb->mutex);
  51339. return pNext;
  51340. }
  51341. /*
  51342. ** Return the value of a status counter for a prepared statement
  51343. */
  51344. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  51345. Vdbe *pVdbe = (Vdbe*)pStmt;
  51346. u32 v = pVdbe->aCounter[op];
  51347. if( resetFlag ) pVdbe->aCounter[op] = 0;
  51348. return (int)v;
  51349. }
  51350. /************** End of vdbeapi.c *********************************************/
  51351. /************** Begin file vdbetrace.c ***************************************/
  51352. /*
  51353. ** 2009 November 25
  51354. **
  51355. ** The author disclaims copyright to this source code. In place of
  51356. ** a legal notice, here is a blessing:
  51357. **
  51358. ** May you do good and not evil.
  51359. ** May you find forgiveness for yourself and forgive others.
  51360. ** May you share freely, never taking more than you give.
  51361. **
  51362. *************************************************************************
  51363. **
  51364. ** This file contains code used to insert the values of host parameters
  51365. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  51366. **
  51367. ** The Vdbe parse-tree explainer is also found here.
  51368. */
  51369. #ifndef SQLITE_OMIT_TRACE
  51370. /*
  51371. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  51372. ** bytes in this text up to but excluding the first character in
  51373. ** a host parameter. If the text contains no host parameters, return
  51374. ** the total number of bytes in the text.
  51375. */
  51376. static int findNextHostParameter(const char *zSql, int *pnToken){
  51377. int tokenType;
  51378. int nTotal = 0;
  51379. int n;
  51380. *pnToken = 0;
  51381. while( zSql[0] ){
  51382. n = sqlite3GetToken((u8*)zSql, &tokenType);
  51383. assert( n>0 && tokenType!=TK_ILLEGAL );
  51384. if( tokenType==TK_VARIABLE ){
  51385. *pnToken = n;
  51386. break;
  51387. }
  51388. nTotal += n;
  51389. zSql += n;
  51390. }
  51391. return nTotal;
  51392. }
  51393. /*
  51394. ** This function returns a pointer to a nul-terminated string in memory
  51395. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  51396. ** string contains a copy of zRawSql but with host parameters expanded to
  51397. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  51398. ** then the returned string holds a copy of zRawSql with "-- " prepended
  51399. ** to each line of text.
  51400. **
  51401. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  51402. ** then long strings and blobs are truncated to that many bytes. This
  51403. ** can be used to prevent unreasonably large trace strings when dealing
  51404. ** with large (multi-megabyte) strings and blobs.
  51405. **
  51406. ** The calling function is responsible for making sure the memory returned
  51407. ** is eventually freed.
  51408. **
  51409. ** ALGORITHM: Scan the input string looking for host parameters in any of
  51410. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  51411. ** string literals, quoted identifier names, and comments. For text forms,
  51412. ** the host parameter index is found by scanning the perpared
  51413. ** statement for the corresponding OP_Variable opcode. Once the host
  51414. ** parameter index is known, locate the value in p->aVar[]. Then render
  51415. ** the value as a literal in place of the host parameter name.
  51416. */
  51417. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  51418. Vdbe *p, /* The prepared statement being evaluated */
  51419. const char *zRawSql /* Raw text of the SQL statement */
  51420. ){
  51421. sqlite3 *db; /* The database connection */
  51422. int idx = 0; /* Index of a host parameter */
  51423. int nextIndex = 1; /* Index of next ? host parameter */
  51424. int n; /* Length of a token prefix */
  51425. int nToken; /* Length of the parameter token */
  51426. int i; /* Loop counter */
  51427. Mem *pVar; /* Value of a host parameter */
  51428. StrAccum out; /* Accumulate the output here */
  51429. char zBase[100]; /* Initial working space */
  51430. db = p->db;
  51431. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  51432. db->aLimit[SQLITE_LIMIT_LENGTH]);
  51433. out.db = db;
  51434. if( db->nVdbeExec>1 ){
  51435. while( *zRawSql ){
  51436. const char *zStart = zRawSql;
  51437. while( *(zRawSql++)!='\n' && *zRawSql );
  51438. sqlite3StrAccumAppend(&out, "-- ", 3);
  51439. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  51440. }
  51441. }else{
  51442. while( zRawSql[0] ){
  51443. n = findNextHostParameter(zRawSql, &nToken);
  51444. assert( n>0 );
  51445. sqlite3StrAccumAppend(&out, zRawSql, n);
  51446. zRawSql += n;
  51447. assert( zRawSql[0] || nToken==0 );
  51448. if( nToken==0 ) break;
  51449. if( zRawSql[0]=='?' ){
  51450. if( nToken>1 ){
  51451. assert( sqlite3Isdigit(zRawSql[1]) );
  51452. sqlite3GetInt32(&zRawSql[1], &idx);
  51453. }else{
  51454. idx = nextIndex;
  51455. }
  51456. }else{
  51457. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  51458. testcase( zRawSql[0]==':' );
  51459. testcase( zRawSql[0]=='$' );
  51460. testcase( zRawSql[0]=='@' );
  51461. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  51462. assert( idx>0 );
  51463. }
  51464. zRawSql += nToken;
  51465. nextIndex = idx + 1;
  51466. assert( idx>0 && idx<=p->nVar );
  51467. pVar = &p->aVar[idx-1];
  51468. if( pVar->flags & MEM_Null ){
  51469. sqlite3StrAccumAppend(&out, "NULL", 4);
  51470. }else if( pVar->flags & MEM_Int ){
  51471. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  51472. }else if( pVar->flags & MEM_Real ){
  51473. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  51474. }else if( pVar->flags & MEM_Str ){
  51475. int nOut; /* Number of bytes of the string text to include in output */
  51476. #ifndef SQLITE_OMIT_UTF16
  51477. u8 enc = ENC(db);
  51478. Mem utf8;
  51479. if( enc!=SQLITE_UTF8 ){
  51480. memset(&utf8, 0, sizeof(utf8));
  51481. utf8.db = db;
  51482. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  51483. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  51484. pVar = &utf8;
  51485. }
  51486. #endif
  51487. nOut = pVar->n;
  51488. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51489. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  51490. nOut = SQLITE_TRACE_SIZE_LIMIT;
  51491. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  51492. }
  51493. #endif
  51494. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  51495. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51496. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  51497. #endif
  51498. #ifndef SQLITE_OMIT_UTF16
  51499. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  51500. #endif
  51501. }else if( pVar->flags & MEM_Zero ){
  51502. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  51503. }else{
  51504. int nOut; /* Number of bytes of the blob to include in output */
  51505. assert( pVar->flags & MEM_Blob );
  51506. sqlite3StrAccumAppend(&out, "x'", 2);
  51507. nOut = pVar->n;
  51508. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51509. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  51510. #endif
  51511. for(i=0; i<nOut; i++){
  51512. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  51513. }
  51514. sqlite3StrAccumAppend(&out, "'", 1);
  51515. #ifdef SQLITE_TRACE_SIZE_LIMIT
  51516. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  51517. #endif
  51518. }
  51519. }
  51520. }
  51521. return sqlite3StrAccumFinish(&out);
  51522. }
  51523. #endif /* #ifndef SQLITE_OMIT_TRACE */
  51524. /*****************************************************************************
  51525. ** The following code implements the data-structure explaining logic
  51526. ** for the Vdbe.
  51527. */
  51528. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  51529. /*
  51530. ** Allocate a new Explain object
  51531. */
  51532. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  51533. if( pVdbe ){
  51534. Explain *p;
  51535. sqlite3BeginBenignMalloc();
  51536. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  51537. if( p ){
  51538. p->pVdbe = pVdbe;
  51539. sqlite3_free(pVdbe->pExplain);
  51540. pVdbe->pExplain = p;
  51541. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  51542. SQLITE_MAX_LENGTH);
  51543. p->str.useMalloc = 2;
  51544. }else{
  51545. sqlite3EndBenignMalloc();
  51546. }
  51547. }
  51548. }
  51549. /*
  51550. ** Return true if the Explain ends with a new-line.
  51551. */
  51552. static int endsWithNL(Explain *p){
  51553. return p && p->str.zText && p->str.nChar
  51554. && p->str.zText[p->str.nChar-1]=='\n';
  51555. }
  51556. /*
  51557. ** Append text to the indentation
  51558. */
  51559. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  51560. Explain *p;
  51561. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  51562. va_list ap;
  51563. if( p->nIndent && endsWithNL(p) ){
  51564. int n = p->nIndent;
  51565. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  51566. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  51567. }
  51568. va_start(ap, zFormat);
  51569. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  51570. va_end(ap);
  51571. }
  51572. }
  51573. /*
  51574. ** Append a '\n' if there is not already one.
  51575. */
  51576. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  51577. Explain *p;
  51578. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  51579. sqlite3StrAccumAppend(&p->str, "\n", 1);
  51580. }
  51581. }
  51582. /*
  51583. ** Push a new indentation level. Subsequent lines will be indented
  51584. ** so that they begin at the current cursor position.
  51585. */
  51586. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  51587. Explain *p;
  51588. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  51589. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  51590. const char *z = p->str.zText;
  51591. int i = p->str.nChar-1;
  51592. int x;
  51593. while( i>=0 && z[i]!='\n' ){ i--; }
  51594. x = (p->str.nChar - 1) - i;
  51595. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  51596. x = p->aIndent[p->nIndent-1];
  51597. }
  51598. p->aIndent[p->nIndent] = x;
  51599. }
  51600. p->nIndent++;
  51601. }
  51602. }
  51603. /*
  51604. ** Pop the indentation stack by one level.
  51605. */
  51606. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  51607. if( p && p->pExplain ) p->pExplain->nIndent--;
  51608. }
  51609. /*
  51610. ** Free the indentation structure
  51611. */
  51612. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  51613. if( pVdbe && pVdbe->pExplain ){
  51614. sqlite3_free(pVdbe->zExplain);
  51615. sqlite3ExplainNL(pVdbe);
  51616. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  51617. sqlite3_free(pVdbe->pExplain);
  51618. pVdbe->pExplain = 0;
  51619. sqlite3EndBenignMalloc();
  51620. }
  51621. }
  51622. /*
  51623. ** Return the explanation of a virtual machine.
  51624. */
  51625. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  51626. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  51627. }
  51628. #endif /* defined(SQLITE_DEBUG) */
  51629. /************** End of vdbetrace.c *******************************************/
  51630. /************** Begin file vdbe.c ********************************************/
  51631. /*
  51632. ** 2001 September 15
  51633. **
  51634. ** The author disclaims copyright to this source code. In place of
  51635. ** a legal notice, here is a blessing:
  51636. **
  51637. ** May you do good and not evil.
  51638. ** May you find forgiveness for yourself and forgive others.
  51639. ** May you share freely, never taking more than you give.
  51640. **
  51641. *************************************************************************
  51642. ** The code in this file implements execution method of the
  51643. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  51644. ** handles housekeeping details such as creating and deleting
  51645. ** VDBE instances. This file is solely interested in executing
  51646. ** the VDBE program.
  51647. **
  51648. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  51649. ** to a VDBE.
  51650. **
  51651. ** The SQL parser generates a program which is then executed by
  51652. ** the VDBE to do the work of the SQL statement. VDBE programs are
  51653. ** similar in form to assembly language. The program consists of
  51654. ** a linear sequence of operations. Each operation has an opcode
  51655. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  51656. ** is a null-terminated string. Operand P5 is an unsigned character.
  51657. ** Few opcodes use all 5 operands.
  51658. **
  51659. ** Computation results are stored on a set of registers numbered beginning
  51660. ** with 1 and going up to Vdbe.nMem. Each register can store
  51661. ** either an integer, a null-terminated string, a floating point
  51662. ** number, or the SQL "NULL" value. An implicit conversion from one
  51663. ** type to the other occurs as necessary.
  51664. **
  51665. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  51666. ** function which does the work of interpreting a VDBE program.
  51667. ** But other routines are also provided to help in building up
  51668. ** a program instruction by instruction.
  51669. **
  51670. ** Various scripts scan this source file in order to generate HTML
  51671. ** documentation, headers files, or other derived files. The formatting
  51672. ** of the code in this file is, therefore, important. See other comments
  51673. ** in this file for details. If in doubt, do not deviate from existing
  51674. ** commenting and indentation practices when changing or adding code.
  51675. */
  51676. /*
  51677. ** Invoke this macro on memory cells just prior to changing the
  51678. ** value of the cell. This macro verifies that shallow copies are
  51679. ** not misused.
  51680. */
  51681. #ifdef SQLITE_DEBUG
  51682. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  51683. #else
  51684. # define memAboutToChange(P,M)
  51685. #endif
  51686. /*
  51687. ** The following global variable is incremented every time a cursor
  51688. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  51689. ** procedures use this information to make sure that indices are
  51690. ** working correctly. This variable has no function other than to
  51691. ** help verify the correct operation of the library.
  51692. */
  51693. #ifdef SQLITE_TEST
  51694. SQLITE_API int sqlite3_search_count = 0;
  51695. #endif
  51696. /*
  51697. ** When this global variable is positive, it gets decremented once before
  51698. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  51699. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  51700. **
  51701. ** This facility is used for testing purposes only. It does not function
  51702. ** in an ordinary build.
  51703. */
  51704. #ifdef SQLITE_TEST
  51705. SQLITE_API int sqlite3_interrupt_count = 0;
  51706. #endif
  51707. /*
  51708. ** The next global variable is incremented each type the OP_Sort opcode
  51709. ** is executed. The test procedures use this information to make sure that
  51710. ** sorting is occurring or not occurring at appropriate times. This variable
  51711. ** has no function other than to help verify the correct operation of the
  51712. ** library.
  51713. */
  51714. #ifdef SQLITE_TEST
  51715. SQLITE_API int sqlite3_sort_count = 0;
  51716. #endif
  51717. /*
  51718. ** The next global variable records the size of the largest MEM_Blob
  51719. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  51720. ** use this information to make sure that the zero-blob functionality
  51721. ** is working correctly. This variable has no function other than to
  51722. ** help verify the correct operation of the library.
  51723. */
  51724. #ifdef SQLITE_TEST
  51725. SQLITE_API int sqlite3_max_blobsize = 0;
  51726. static void updateMaxBlobsize(Mem *p){
  51727. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  51728. sqlite3_max_blobsize = p->n;
  51729. }
  51730. }
  51731. #endif
  51732. /*
  51733. ** The next global variable is incremented each type the OP_Found opcode
  51734. ** is executed. This is used to test whether or not the foreign key
  51735. ** operation implemented using OP_FkIsZero is working. This variable
  51736. ** has no function other than to help verify the correct operation of the
  51737. ** library.
  51738. */
  51739. #ifdef SQLITE_TEST
  51740. SQLITE_API int sqlite3_found_count = 0;
  51741. #endif
  51742. /*
  51743. ** Test a register to see if it exceeds the current maximum blob size.
  51744. ** If it does, record the new maximum blob size.
  51745. */
  51746. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  51747. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  51748. #else
  51749. # define UPDATE_MAX_BLOBSIZE(P)
  51750. #endif
  51751. /*
  51752. ** Convert the given register into a string if it isn't one
  51753. ** already. Return non-zero if a malloc() fails.
  51754. */
  51755. #define Stringify(P, enc) \
  51756. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  51757. { goto no_mem; }
  51758. /*
  51759. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  51760. ** a pointer to a dynamically allocated string where some other entity
  51761. ** is responsible for deallocating that string. Because the register
  51762. ** does not control the string, it might be deleted without the register
  51763. ** knowing it.
  51764. **
  51765. ** This routine converts an ephemeral string into a dynamically allocated
  51766. ** string that the register itself controls. In other words, it
  51767. ** converts an MEM_Ephem string into an MEM_Dyn string.
  51768. */
  51769. #define Deephemeralize(P) \
  51770. if( ((P)->flags&MEM_Ephem)!=0 \
  51771. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  51772. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  51773. # define isSorter(x) ((x)->pSorter!=0)
  51774. /*
  51775. ** Argument pMem points at a register that will be passed to a
  51776. ** user-defined function or returned to the user as the result of a query.
  51777. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  51778. ** routines.
  51779. */
  51780. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  51781. int flags = pMem->flags;
  51782. if( flags & MEM_Null ){
  51783. pMem->type = SQLITE_NULL;
  51784. }
  51785. else if( flags & MEM_Int ){
  51786. pMem->type = SQLITE_INTEGER;
  51787. }
  51788. else if( flags & MEM_Real ){
  51789. pMem->type = SQLITE_FLOAT;
  51790. }
  51791. else if( flags & MEM_Str ){
  51792. pMem->type = SQLITE_TEXT;
  51793. }else{
  51794. pMem->type = SQLITE_BLOB;
  51795. }
  51796. }
  51797. /*
  51798. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  51799. ** if we run out of memory.
  51800. */
  51801. static VdbeCursor *allocateCursor(
  51802. Vdbe *p, /* The virtual machine */
  51803. int iCur, /* Index of the new VdbeCursor */
  51804. int nField, /* Number of fields in the table or index */
  51805. int iDb, /* Database the cursor belongs to, or -1 */
  51806. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  51807. ){
  51808. /* Find the memory cell that will be used to store the blob of memory
  51809. ** required for this VdbeCursor structure. It is convenient to use a
  51810. ** vdbe memory cell to manage the memory allocation required for a
  51811. ** VdbeCursor structure for the following reasons:
  51812. **
  51813. ** * Sometimes cursor numbers are used for a couple of different
  51814. ** purposes in a vdbe program. The different uses might require
  51815. ** different sized allocations. Memory cells provide growable
  51816. ** allocations.
  51817. **
  51818. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  51819. ** be freed lazily via the sqlite3_release_memory() API. This
  51820. ** minimizes the number of malloc calls made by the system.
  51821. **
  51822. ** Memory cells for cursors are allocated at the top of the address
  51823. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  51824. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  51825. */
  51826. Mem *pMem = &p->aMem[p->nMem-iCur];
  51827. int nByte;
  51828. VdbeCursor *pCx = 0;
  51829. nByte =
  51830. ROUND8(sizeof(VdbeCursor)) +
  51831. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  51832. 2*nField*sizeof(u32);
  51833. assert( iCur<p->nCursor );
  51834. if( p->apCsr[iCur] ){
  51835. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  51836. p->apCsr[iCur] = 0;
  51837. }
  51838. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  51839. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  51840. memset(pCx, 0, sizeof(VdbeCursor));
  51841. pCx->iDb = iDb;
  51842. pCx->nField = nField;
  51843. if( nField ){
  51844. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  51845. }
  51846. if( isBtreeCursor ){
  51847. pCx->pCursor = (BtCursor*)
  51848. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  51849. sqlite3BtreeCursorZero(pCx->pCursor);
  51850. }
  51851. }
  51852. return pCx;
  51853. }
  51854. /*
  51855. ** Try to convert a value into a numeric representation if we can
  51856. ** do so without loss of information. In other words, if the string
  51857. ** looks like a number, convert it into a number. If it does not
  51858. ** look like a number, leave it alone.
  51859. */
  51860. static void applyNumericAffinity(Mem *pRec){
  51861. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  51862. double rValue;
  51863. i64 iValue;
  51864. u8 enc = pRec->enc;
  51865. if( (pRec->flags&MEM_Str)==0 ) return;
  51866. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  51867. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  51868. pRec->u.i = iValue;
  51869. pRec->flags |= MEM_Int;
  51870. }else{
  51871. pRec->r = rValue;
  51872. pRec->flags |= MEM_Real;
  51873. }
  51874. }
  51875. }
  51876. /*
  51877. ** Processing is determine by the affinity parameter:
  51878. **
  51879. ** SQLITE_AFF_INTEGER:
  51880. ** SQLITE_AFF_REAL:
  51881. ** SQLITE_AFF_NUMERIC:
  51882. ** Try to convert pRec to an integer representation or a
  51883. ** floating-point representation if an integer representation
  51884. ** is not possible. Note that the integer representation is
  51885. ** always preferred, even if the affinity is REAL, because
  51886. ** an integer representation is more space efficient on disk.
  51887. **
  51888. ** SQLITE_AFF_TEXT:
  51889. ** Convert pRec to a text representation.
  51890. **
  51891. ** SQLITE_AFF_NONE:
  51892. ** No-op. pRec is unchanged.
  51893. */
  51894. static void applyAffinity(
  51895. Mem *pRec, /* The value to apply affinity to */
  51896. char affinity, /* The affinity to be applied */
  51897. u8 enc /* Use this text encoding */
  51898. ){
  51899. if( affinity==SQLITE_AFF_TEXT ){
  51900. /* Only attempt the conversion to TEXT if there is an integer or real
  51901. ** representation (blob and NULL do not get converted) but no string
  51902. ** representation.
  51903. */
  51904. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  51905. sqlite3VdbeMemStringify(pRec, enc);
  51906. }
  51907. pRec->flags &= ~(MEM_Real|MEM_Int);
  51908. }else if( affinity!=SQLITE_AFF_NONE ){
  51909. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  51910. || affinity==SQLITE_AFF_NUMERIC );
  51911. applyNumericAffinity(pRec);
  51912. if( pRec->flags & MEM_Real ){
  51913. sqlite3VdbeIntegerAffinity(pRec);
  51914. }
  51915. }
  51916. }
  51917. /*
  51918. ** Try to convert the type of a function argument or a result column
  51919. ** into a numeric representation. Use either INTEGER or REAL whichever
  51920. ** is appropriate. But only do the conversion if it is possible without
  51921. ** loss of information and return the revised type of the argument.
  51922. */
  51923. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  51924. Mem *pMem = (Mem*)pVal;
  51925. if( pMem->type==SQLITE_TEXT ){
  51926. applyNumericAffinity(pMem);
  51927. sqlite3VdbeMemStoreType(pMem);
  51928. }
  51929. return pMem->type;
  51930. }
  51931. /*
  51932. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  51933. ** not the internal Mem* type.
  51934. */
  51935. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  51936. sqlite3_value *pVal,
  51937. u8 affinity,
  51938. u8 enc
  51939. ){
  51940. applyAffinity((Mem *)pVal, affinity, enc);
  51941. }
  51942. #ifdef SQLITE_DEBUG
  51943. /*
  51944. ** Write a nice string representation of the contents of cell pMem
  51945. ** into buffer zBuf, length nBuf.
  51946. */
  51947. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  51948. char *zCsr = zBuf;
  51949. int f = pMem->flags;
  51950. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  51951. if( f&MEM_Blob ){
  51952. int i;
  51953. char c;
  51954. if( f & MEM_Dyn ){
  51955. c = 'z';
  51956. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  51957. }else if( f & MEM_Static ){
  51958. c = 't';
  51959. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  51960. }else if( f & MEM_Ephem ){
  51961. c = 'e';
  51962. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  51963. }else{
  51964. c = 's';
  51965. }
  51966. sqlite3_snprintf(100, zCsr, "%c", c);
  51967. zCsr += sqlite3Strlen30(zCsr);
  51968. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  51969. zCsr += sqlite3Strlen30(zCsr);
  51970. for(i=0; i<16 && i<pMem->n; i++){
  51971. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  51972. zCsr += sqlite3Strlen30(zCsr);
  51973. }
  51974. for(i=0; i<16 && i<pMem->n; i++){
  51975. char z = pMem->z[i];
  51976. if( z<32 || z>126 ) *zCsr++ = '.';
  51977. else *zCsr++ = z;
  51978. }
  51979. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  51980. zCsr += sqlite3Strlen30(zCsr);
  51981. if( f & MEM_Zero ){
  51982. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  51983. zCsr += sqlite3Strlen30(zCsr);
  51984. }
  51985. *zCsr = '\0';
  51986. }else if( f & MEM_Str ){
  51987. int j, k;
  51988. zBuf[0] = ' ';
  51989. if( f & MEM_Dyn ){
  51990. zBuf[1] = 'z';
  51991. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  51992. }else if( f & MEM_Static ){
  51993. zBuf[1] = 't';
  51994. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  51995. }else if( f & MEM_Ephem ){
  51996. zBuf[1] = 'e';
  51997. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  51998. }else{
  51999. zBuf[1] = 's';
  52000. }
  52001. k = 2;
  52002. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  52003. k += sqlite3Strlen30(&zBuf[k]);
  52004. zBuf[k++] = '[';
  52005. for(j=0; j<15 && j<pMem->n; j++){
  52006. u8 c = pMem->z[j];
  52007. if( c>=0x20 && c<0x7f ){
  52008. zBuf[k++] = c;
  52009. }else{
  52010. zBuf[k++] = '.';
  52011. }
  52012. }
  52013. zBuf[k++] = ']';
  52014. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  52015. k += sqlite3Strlen30(&zBuf[k]);
  52016. zBuf[k++] = 0;
  52017. }
  52018. }
  52019. #endif
  52020. #ifdef SQLITE_DEBUG
  52021. /*
  52022. ** Print the value of a register for tracing purposes:
  52023. */
  52024. static void memTracePrint(FILE *out, Mem *p){
  52025. if( p->flags & MEM_Invalid ){
  52026. fprintf(out, " undefined");
  52027. }else if( p->flags & MEM_Null ){
  52028. fprintf(out, " NULL");
  52029. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  52030. fprintf(out, " si:%lld", p->u.i);
  52031. }else if( p->flags & MEM_Int ){
  52032. fprintf(out, " i:%lld", p->u.i);
  52033. #ifndef SQLITE_OMIT_FLOATING_POINT
  52034. }else if( p->flags & MEM_Real ){
  52035. fprintf(out, " r:%g", p->r);
  52036. #endif
  52037. }else if( p->flags & MEM_RowSet ){
  52038. fprintf(out, " (rowset)");
  52039. }else{
  52040. char zBuf[200];
  52041. sqlite3VdbeMemPrettyPrint(p, zBuf);
  52042. fprintf(out, " ");
  52043. fprintf(out, "%s", zBuf);
  52044. }
  52045. }
  52046. static void registerTrace(FILE *out, int iReg, Mem *p){
  52047. fprintf(out, "REG[%d] = ", iReg);
  52048. memTracePrint(out, p);
  52049. fprintf(out, "\n");
  52050. }
  52051. #endif
  52052. #ifdef SQLITE_DEBUG
  52053. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  52054. #else
  52055. # define REGISTER_TRACE(R,M)
  52056. #endif
  52057. #ifdef VDBE_PROFILE
  52058. /*
  52059. ** hwtime.h contains inline assembler code for implementing
  52060. ** high-performance timing routines.
  52061. */
  52062. /************** Include hwtime.h in the middle of vdbe.c *********************/
  52063. /************** Begin file hwtime.h ******************************************/
  52064. /*
  52065. ** 2008 May 27
  52066. **
  52067. ** The author disclaims copyright to this source code. In place of
  52068. ** a legal notice, here is a blessing:
  52069. **
  52070. ** May you do good and not evil.
  52071. ** May you find forgiveness for yourself and forgive others.
  52072. ** May you share freely, never taking more than you give.
  52073. **
  52074. ******************************************************************************
  52075. **
  52076. ** This file contains inline asm code for retrieving "high-performance"
  52077. ** counters for x86 class CPUs.
  52078. */
  52079. #ifndef _HWTIME_H_
  52080. #define _HWTIME_H_
  52081. /*
  52082. ** The following routine only works on pentium-class (or newer) processors.
  52083. ** It uses the RDTSC opcode to read the cycle count value out of the
  52084. ** processor and returns that value. This can be used for high-res
  52085. ** profiling.
  52086. */
  52087. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  52088. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  52089. #if defined(__GNUC__)
  52090. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52091. unsigned int lo, hi;
  52092. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  52093. return (sqlite_uint64)hi << 32 | lo;
  52094. }
  52095. #elif defined(_MSC_VER)
  52096. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  52097. __asm {
  52098. rdtsc
  52099. ret ; return value at EDX:EAX
  52100. }
  52101. }
  52102. #endif
  52103. #elif (defined(__GNUC__) && defined(__x86_64__))
  52104. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52105. unsigned long val;
  52106. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  52107. return val;
  52108. }
  52109. #elif (defined(__GNUC__) && defined(__ppc__))
  52110. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  52111. unsigned long long retval;
  52112. unsigned long junk;
  52113. __asm__ __volatile__ ("\n\
  52114. 1: mftbu %1\n\
  52115. mftb %L0\n\
  52116. mftbu %0\n\
  52117. cmpw %0,%1\n\
  52118. bne 1b"
  52119. : "=r" (retval), "=r" (junk));
  52120. return retval;
  52121. }
  52122. #else
  52123. #error Need implementation of sqlite3Hwtime() for your platform.
  52124. /*
  52125. ** To compile without implementing sqlite3Hwtime() for your platform,
  52126. ** you can remove the above #error and use the following
  52127. ** stub function. You will lose timing support for many
  52128. ** of the debugging and testing utilities, but it should at
  52129. ** least compile and run.
  52130. */
  52131. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  52132. #endif
  52133. #endif /* !defined(_HWTIME_H_) */
  52134. /************** End of hwtime.h **********************************************/
  52135. /************** Continuing where we left off in vdbe.c ***********************/
  52136. #endif
  52137. /*
  52138. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  52139. ** sqlite3_interrupt() routine has been called. If it has been, then
  52140. ** processing of the VDBE program is interrupted.
  52141. **
  52142. ** This macro added to every instruction that does a jump in order to
  52143. ** implement a loop. This test used to be on every single instruction,
  52144. ** but that meant we more testing than we needed. By only testing the
  52145. ** flag on jump instructions, we get a (small) speed improvement.
  52146. */
  52147. #define CHECK_FOR_INTERRUPT \
  52148. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  52149. #ifndef NDEBUG
  52150. /*
  52151. ** This function is only called from within an assert() expression. It
  52152. ** checks that the sqlite3.nTransaction variable is correctly set to
  52153. ** the number of non-transaction savepoints currently in the
  52154. ** linked list starting at sqlite3.pSavepoint.
  52155. **
  52156. ** Usage:
  52157. **
  52158. ** assert( checkSavepointCount(db) );
  52159. */
  52160. static int checkSavepointCount(sqlite3 *db){
  52161. int n = 0;
  52162. Savepoint *p;
  52163. for(p=db->pSavepoint; p; p=p->pNext) n++;
  52164. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  52165. return 1;
  52166. }
  52167. #endif
  52168. /*
  52169. ** Execute as much of a VDBE program as we can then return.
  52170. **
  52171. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  52172. ** close the program with a final OP_Halt and to set up the callbacks
  52173. ** and the error message pointer.
  52174. **
  52175. ** Whenever a row or result data is available, this routine will either
  52176. ** invoke the result callback (if there is one) or return with
  52177. ** SQLITE_ROW.
  52178. **
  52179. ** If an attempt is made to open a locked database, then this routine
  52180. ** will either invoke the busy callback (if there is one) or it will
  52181. ** return SQLITE_BUSY.
  52182. **
  52183. ** If an error occurs, an error message is written to memory obtained
  52184. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  52185. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  52186. **
  52187. ** If the callback ever returns non-zero, then the program exits
  52188. ** immediately. There will be no error message but the p->rc field is
  52189. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  52190. **
  52191. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  52192. ** routine to return SQLITE_ERROR.
  52193. **
  52194. ** Other fatal errors return SQLITE_ERROR.
  52195. **
  52196. ** After this routine has finished, sqlite3VdbeFinalize() should be
  52197. ** used to clean up the mess that was left behind.
  52198. */
  52199. SQLITE_PRIVATE int sqlite3VdbeExec(
  52200. Vdbe *p /* The VDBE */
  52201. ){
  52202. int pc=0; /* The program counter */
  52203. Op *aOp = p->aOp; /* Copy of p->aOp */
  52204. Op *pOp; /* Current operation */
  52205. int rc = SQLITE_OK; /* Value to return */
  52206. sqlite3 *db = p->db; /* The database */
  52207. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  52208. u8 encoding = ENC(db); /* The database encoding */
  52209. int iCompare = 0; /* Result of last OP_Compare operation */
  52210. unsigned nVmStep = 0; /* Number of virtual machine steps */
  52211. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52212. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  52213. #endif
  52214. Mem *aMem = p->aMem; /* Copy of p->aMem */
  52215. Mem *pIn1 = 0; /* 1st input operand */
  52216. Mem *pIn2 = 0; /* 2nd input operand */
  52217. Mem *pIn3 = 0; /* 3rd input operand */
  52218. Mem *pOut = 0; /* Output operand */
  52219. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  52220. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  52221. #ifdef VDBE_PROFILE
  52222. u64 start; /* CPU clock count at start of opcode */
  52223. int origPc; /* Program counter at start of opcode */
  52224. #endif
  52225. /********************************************************************
  52226. ** Automatically generated code
  52227. **
  52228. ** The following union is automatically generated by the
  52229. ** vdbe-compress.tcl script. The purpose of this union is to
  52230. ** reduce the amount of stack space required by this function.
  52231. ** See comments in the vdbe-compress.tcl script for details.
  52232. */
  52233. union vdbeExecUnion {
  52234. struct OP_Yield_stack_vars {
  52235. int pcDest;
  52236. } aa;
  52237. struct OP_Null_stack_vars {
  52238. int cnt;
  52239. u16 nullFlag;
  52240. } ab;
  52241. struct OP_Variable_stack_vars {
  52242. Mem *pVar; /* Value being transferred */
  52243. } ac;
  52244. struct OP_Move_stack_vars {
  52245. char *zMalloc; /* Holding variable for allocated memory */
  52246. int n; /* Number of registers left to copy */
  52247. int p1; /* Register to copy from */
  52248. int p2; /* Register to copy to */
  52249. } ad;
  52250. struct OP_Copy_stack_vars {
  52251. int n;
  52252. } ae;
  52253. struct OP_ResultRow_stack_vars {
  52254. Mem *pMem;
  52255. int i;
  52256. } af;
  52257. struct OP_Concat_stack_vars {
  52258. i64 nByte;
  52259. } ag;
  52260. struct OP_Remainder_stack_vars {
  52261. char bIntint; /* Started out as two integer operands */
  52262. int flags; /* Combined MEM_* flags from both inputs */
  52263. i64 iA; /* Integer value of left operand */
  52264. i64 iB; /* Integer value of right operand */
  52265. double rA; /* Real value of left operand */
  52266. double rB; /* Real value of right operand */
  52267. } ah;
  52268. struct OP_Function_stack_vars {
  52269. int i;
  52270. Mem *pArg;
  52271. sqlite3_context ctx;
  52272. sqlite3_value **apVal;
  52273. int n;
  52274. } ai;
  52275. struct OP_ShiftRight_stack_vars {
  52276. i64 iA;
  52277. u64 uA;
  52278. i64 iB;
  52279. u8 op;
  52280. } aj;
  52281. struct OP_Ge_stack_vars {
  52282. int res; /* Result of the comparison of pIn1 against pIn3 */
  52283. char affinity; /* Affinity to use for comparison */
  52284. u16 flags1; /* Copy of initial value of pIn1->flags */
  52285. u16 flags3; /* Copy of initial value of pIn3->flags */
  52286. } ak;
  52287. struct OP_Compare_stack_vars {
  52288. int n;
  52289. int i;
  52290. int p1;
  52291. int p2;
  52292. const KeyInfo *pKeyInfo;
  52293. int idx;
  52294. CollSeq *pColl; /* Collating sequence to use on this term */
  52295. int bRev; /* True for DESCENDING sort order */
  52296. } al;
  52297. struct OP_Or_stack_vars {
  52298. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  52299. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  52300. } am;
  52301. struct OP_IfNot_stack_vars {
  52302. int c;
  52303. } an;
  52304. struct OP_Column_stack_vars {
  52305. u32 payloadSize; /* Number of bytes in the record */
  52306. i64 payloadSize64; /* Number of bytes in the record */
  52307. int p1; /* P1 value of the opcode */
  52308. int p2; /* column number to retrieve */
  52309. VdbeCursor *pC; /* The VDBE cursor */
  52310. char *zRec; /* Pointer to complete record-data */
  52311. BtCursor *pCrsr; /* The BTree cursor */
  52312. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  52313. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  52314. int nField; /* number of fields in the record */
  52315. int len; /* The length of the serialized data for the column */
  52316. int i; /* Loop counter */
  52317. char *zData; /* Part of the record being decoded */
  52318. Mem *pDest; /* Where to write the extracted value */
  52319. Mem sMem; /* For storing the record being decoded */
  52320. u8 *zIdx; /* Index into header */
  52321. u8 *zEndHdr; /* Pointer to first byte after the header */
  52322. u32 offset; /* Offset into the data */
  52323. u32 szField; /* Number of bytes in the content of a field */
  52324. int szHdr; /* Size of the header size field at start of record */
  52325. int avail; /* Number of bytes of available data */
  52326. u32 t; /* A type code from the record header */
  52327. Mem *pReg; /* PseudoTable input register */
  52328. } ao;
  52329. struct OP_Affinity_stack_vars {
  52330. const char *zAffinity; /* The affinity to be applied */
  52331. char cAff; /* A single character of affinity */
  52332. } ap;
  52333. struct OP_MakeRecord_stack_vars {
  52334. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  52335. Mem *pRec; /* The new record */
  52336. u64 nData; /* Number of bytes of data space */
  52337. int nHdr; /* Number of bytes of header space */
  52338. i64 nByte; /* Data space required for this record */
  52339. int nZero; /* Number of zero bytes at the end of the record */
  52340. int nVarint; /* Number of bytes in a varint */
  52341. u32 serial_type; /* Type field */
  52342. Mem *pData0; /* First field to be combined into the record */
  52343. Mem *pLast; /* Last field of the record */
  52344. int nField; /* Number of fields in the record */
  52345. char *zAffinity; /* The affinity string for the record */
  52346. int file_format; /* File format to use for encoding */
  52347. int i; /* Space used in zNewRecord[] */
  52348. int len; /* Length of a field */
  52349. } aq;
  52350. struct OP_Count_stack_vars {
  52351. i64 nEntry;
  52352. BtCursor *pCrsr;
  52353. } ar;
  52354. struct OP_Savepoint_stack_vars {
  52355. int p1; /* Value of P1 operand */
  52356. char *zName; /* Name of savepoint */
  52357. int nName;
  52358. Savepoint *pNew;
  52359. Savepoint *pSavepoint;
  52360. Savepoint *pTmp;
  52361. int iSavepoint;
  52362. int ii;
  52363. } as;
  52364. struct OP_AutoCommit_stack_vars {
  52365. int desiredAutoCommit;
  52366. int iRollback;
  52367. int turnOnAC;
  52368. } at;
  52369. struct OP_Transaction_stack_vars {
  52370. Btree *pBt;
  52371. } au;
  52372. struct OP_ReadCookie_stack_vars {
  52373. int iMeta;
  52374. int iDb;
  52375. int iCookie;
  52376. } av;
  52377. struct OP_SetCookie_stack_vars {
  52378. Db *pDb;
  52379. } aw;
  52380. struct OP_VerifyCookie_stack_vars {
  52381. int iMeta;
  52382. int iGen;
  52383. Btree *pBt;
  52384. } ax;
  52385. struct OP_OpenWrite_stack_vars {
  52386. int nField;
  52387. KeyInfo *pKeyInfo;
  52388. int p2;
  52389. int iDb;
  52390. int wrFlag;
  52391. Btree *pX;
  52392. VdbeCursor *pCur;
  52393. Db *pDb;
  52394. } ay;
  52395. struct OP_OpenEphemeral_stack_vars {
  52396. VdbeCursor *pCx;
  52397. } az;
  52398. struct OP_SorterOpen_stack_vars {
  52399. VdbeCursor *pCx;
  52400. } ba;
  52401. struct OP_OpenPseudo_stack_vars {
  52402. VdbeCursor *pCx;
  52403. } bb;
  52404. struct OP_SeekGt_stack_vars {
  52405. int res;
  52406. int oc;
  52407. VdbeCursor *pC;
  52408. UnpackedRecord r;
  52409. int nField;
  52410. i64 iKey; /* The rowid we are to seek to */
  52411. } bc;
  52412. struct OP_Seek_stack_vars {
  52413. VdbeCursor *pC;
  52414. } bd;
  52415. struct OP_Found_stack_vars {
  52416. int alreadyExists;
  52417. VdbeCursor *pC;
  52418. int res;
  52419. char *pFree;
  52420. UnpackedRecord *pIdxKey;
  52421. UnpackedRecord r;
  52422. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  52423. } be;
  52424. struct OP_IsUnique_stack_vars {
  52425. u16 ii;
  52426. VdbeCursor *pCx;
  52427. BtCursor *pCrsr;
  52428. u16 nField;
  52429. Mem *aMx;
  52430. UnpackedRecord r; /* B-Tree index search key */
  52431. i64 R; /* Rowid stored in register P3 */
  52432. } bf;
  52433. struct OP_NotExists_stack_vars {
  52434. VdbeCursor *pC;
  52435. BtCursor *pCrsr;
  52436. int res;
  52437. u64 iKey;
  52438. } bg;
  52439. struct OP_NewRowid_stack_vars {
  52440. i64 v; /* The new rowid */
  52441. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  52442. int res; /* Result of an sqlite3BtreeLast() */
  52443. int cnt; /* Counter to limit the number of searches */
  52444. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  52445. VdbeFrame *pFrame; /* Root frame of VDBE */
  52446. } bh;
  52447. struct OP_InsertInt_stack_vars {
  52448. Mem *pData; /* MEM cell holding data for the record to be inserted */
  52449. Mem *pKey; /* MEM cell holding key for the record */
  52450. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  52451. VdbeCursor *pC; /* Cursor to table into which insert is written */
  52452. int nZero; /* Number of zero-bytes to append */
  52453. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  52454. const char *zDb; /* database name - used by the update hook */
  52455. const char *zTbl; /* Table name - used by the opdate hook */
  52456. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  52457. } bi;
  52458. struct OP_Delete_stack_vars {
  52459. i64 iKey;
  52460. VdbeCursor *pC;
  52461. } bj;
  52462. struct OP_SorterCompare_stack_vars {
  52463. VdbeCursor *pC;
  52464. int res;
  52465. } bk;
  52466. struct OP_SorterData_stack_vars {
  52467. VdbeCursor *pC;
  52468. } bl;
  52469. struct OP_RowData_stack_vars {
  52470. VdbeCursor *pC;
  52471. BtCursor *pCrsr;
  52472. u32 n;
  52473. i64 n64;
  52474. } bm;
  52475. struct OP_Rowid_stack_vars {
  52476. VdbeCursor *pC;
  52477. i64 v;
  52478. sqlite3_vtab *pVtab;
  52479. const sqlite3_module *pModule;
  52480. } bn;
  52481. struct OP_NullRow_stack_vars {
  52482. VdbeCursor *pC;
  52483. } bo;
  52484. struct OP_Last_stack_vars {
  52485. VdbeCursor *pC;
  52486. BtCursor *pCrsr;
  52487. int res;
  52488. } bp;
  52489. struct OP_Rewind_stack_vars {
  52490. VdbeCursor *pC;
  52491. BtCursor *pCrsr;
  52492. int res;
  52493. } bq;
  52494. struct OP_Next_stack_vars {
  52495. VdbeCursor *pC;
  52496. int res;
  52497. } br;
  52498. struct OP_IdxInsert_stack_vars {
  52499. VdbeCursor *pC;
  52500. BtCursor *pCrsr;
  52501. int nKey;
  52502. const char *zKey;
  52503. } bs;
  52504. struct OP_IdxDelete_stack_vars {
  52505. VdbeCursor *pC;
  52506. BtCursor *pCrsr;
  52507. int res;
  52508. UnpackedRecord r;
  52509. } bt;
  52510. struct OP_IdxRowid_stack_vars {
  52511. BtCursor *pCrsr;
  52512. VdbeCursor *pC;
  52513. i64 rowid;
  52514. } bu;
  52515. struct OP_IdxGE_stack_vars {
  52516. VdbeCursor *pC;
  52517. int res;
  52518. UnpackedRecord r;
  52519. } bv;
  52520. struct OP_Destroy_stack_vars {
  52521. int iMoved;
  52522. int iCnt;
  52523. Vdbe *pVdbe;
  52524. int iDb;
  52525. } bw;
  52526. struct OP_Clear_stack_vars {
  52527. int nChange;
  52528. } bx;
  52529. struct OP_CreateTable_stack_vars {
  52530. int pgno;
  52531. int flags;
  52532. Db *pDb;
  52533. } by;
  52534. struct OP_ParseSchema_stack_vars {
  52535. int iDb;
  52536. const char *zMaster;
  52537. char *zSql;
  52538. InitData initData;
  52539. } bz;
  52540. struct OP_IntegrityCk_stack_vars {
  52541. int nRoot; /* Number of tables to check. (Number of root pages.) */
  52542. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  52543. int j; /* Loop counter */
  52544. int nErr; /* Number of errors reported */
  52545. char *z; /* Text of the error report */
  52546. Mem *pnErr; /* Register keeping track of errors remaining */
  52547. } ca;
  52548. struct OP_RowSetRead_stack_vars {
  52549. i64 val;
  52550. } cb;
  52551. struct OP_RowSetTest_stack_vars {
  52552. int iSet;
  52553. int exists;
  52554. } cc;
  52555. struct OP_Program_stack_vars {
  52556. int nMem; /* Number of memory registers for sub-program */
  52557. int nByte; /* Bytes of runtime space required for sub-program */
  52558. Mem *pRt; /* Register to allocate runtime space */
  52559. Mem *pMem; /* Used to iterate through memory cells */
  52560. Mem *pEnd; /* Last memory cell in new array */
  52561. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  52562. SubProgram *pProgram; /* Sub-program to execute */
  52563. void *t; /* Token identifying trigger */
  52564. } cd;
  52565. struct OP_Param_stack_vars {
  52566. VdbeFrame *pFrame;
  52567. Mem *pIn;
  52568. } ce;
  52569. struct OP_MemMax_stack_vars {
  52570. Mem *pIn1;
  52571. VdbeFrame *pFrame;
  52572. } cf;
  52573. struct OP_AggStep_stack_vars {
  52574. int n;
  52575. int i;
  52576. Mem *pMem;
  52577. Mem *pRec;
  52578. sqlite3_context ctx;
  52579. sqlite3_value **apVal;
  52580. } cg;
  52581. struct OP_AggFinal_stack_vars {
  52582. Mem *pMem;
  52583. } ch;
  52584. struct OP_Checkpoint_stack_vars {
  52585. int i; /* Loop counter */
  52586. int aRes[3]; /* Results */
  52587. Mem *pMem; /* Write results here */
  52588. } ci;
  52589. struct OP_JournalMode_stack_vars {
  52590. Btree *pBt; /* Btree to change journal mode of */
  52591. Pager *pPager; /* Pager associated with pBt */
  52592. int eNew; /* New journal mode */
  52593. int eOld; /* The old journal mode */
  52594. #ifndef SQLITE_OMIT_WAL
  52595. const char *zFilename; /* Name of database file for pPager */
  52596. #endif
  52597. } cj;
  52598. struct OP_IncrVacuum_stack_vars {
  52599. Btree *pBt;
  52600. } ck;
  52601. struct OP_VBegin_stack_vars {
  52602. VTable *pVTab;
  52603. } cl;
  52604. struct OP_VOpen_stack_vars {
  52605. VdbeCursor *pCur;
  52606. sqlite3_vtab_cursor *pVtabCursor;
  52607. sqlite3_vtab *pVtab;
  52608. sqlite3_module *pModule;
  52609. } cm;
  52610. struct OP_VFilter_stack_vars {
  52611. int nArg;
  52612. int iQuery;
  52613. const sqlite3_module *pModule;
  52614. Mem *pQuery;
  52615. Mem *pArgc;
  52616. sqlite3_vtab_cursor *pVtabCursor;
  52617. sqlite3_vtab *pVtab;
  52618. VdbeCursor *pCur;
  52619. int res;
  52620. int i;
  52621. Mem **apArg;
  52622. } cn;
  52623. struct OP_VColumn_stack_vars {
  52624. sqlite3_vtab *pVtab;
  52625. const sqlite3_module *pModule;
  52626. Mem *pDest;
  52627. sqlite3_context sContext;
  52628. } co;
  52629. struct OP_VNext_stack_vars {
  52630. sqlite3_vtab *pVtab;
  52631. const sqlite3_module *pModule;
  52632. int res;
  52633. VdbeCursor *pCur;
  52634. } cp;
  52635. struct OP_VRename_stack_vars {
  52636. sqlite3_vtab *pVtab;
  52637. Mem *pName;
  52638. } cq;
  52639. struct OP_VUpdate_stack_vars {
  52640. sqlite3_vtab *pVtab;
  52641. sqlite3_module *pModule;
  52642. int nArg;
  52643. int i;
  52644. sqlite_int64 rowid;
  52645. Mem **apArg;
  52646. Mem *pX;
  52647. } cr;
  52648. struct OP_Trace_stack_vars {
  52649. char *zTrace;
  52650. char *z;
  52651. } cs;
  52652. } u;
  52653. /* End automatically generated code
  52654. ********************************************************************/
  52655. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  52656. sqlite3VdbeEnter(p);
  52657. if( p->rc==SQLITE_NOMEM ){
  52658. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  52659. ** sqlite3_column_text16() failed. */
  52660. goto no_mem;
  52661. }
  52662. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  52663. assert( p->bIsReader || p->readOnly!=0 );
  52664. p->rc = SQLITE_OK;
  52665. p->iCurrentTime = 0;
  52666. assert( p->explain==0 );
  52667. p->pResultSet = 0;
  52668. db->busyHandler.nBusy = 0;
  52669. CHECK_FOR_INTERRUPT;
  52670. sqlite3VdbeIOTraceSql(p);
  52671. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52672. if( db->xProgress ){
  52673. assert( 0 < db->nProgressOps );
  52674. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  52675. if( nProgressLimit==0 ){
  52676. nProgressLimit = db->nProgressOps;
  52677. }else{
  52678. nProgressLimit %= (unsigned)db->nProgressOps;
  52679. }
  52680. }
  52681. #endif
  52682. #ifdef SQLITE_DEBUG
  52683. sqlite3BeginBenignMalloc();
  52684. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  52685. int i;
  52686. printf("VDBE Program Listing:\n");
  52687. sqlite3VdbePrintSql(p);
  52688. for(i=0; i<p->nOp; i++){
  52689. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  52690. }
  52691. }
  52692. sqlite3EndBenignMalloc();
  52693. #endif
  52694. for(pc=p->pc; rc==SQLITE_OK; pc++){
  52695. assert( pc>=0 && pc<p->nOp );
  52696. if( db->mallocFailed ) goto no_mem;
  52697. #ifdef VDBE_PROFILE
  52698. origPc = pc;
  52699. start = sqlite3Hwtime();
  52700. #endif
  52701. nVmStep++;
  52702. pOp = &aOp[pc];
  52703. /* Only allow tracing if SQLITE_DEBUG is defined.
  52704. */
  52705. #ifdef SQLITE_DEBUG
  52706. if( p->trace ){
  52707. if( pc==0 ){
  52708. printf("VDBE Execution Trace:\n");
  52709. sqlite3VdbePrintSql(p);
  52710. }
  52711. sqlite3VdbePrintOp(p->trace, pc, pOp);
  52712. }
  52713. #endif
  52714. /* Check to see if we need to simulate an interrupt. This only happens
  52715. ** if we have a special test build.
  52716. */
  52717. #ifdef SQLITE_TEST
  52718. if( sqlite3_interrupt_count>0 ){
  52719. sqlite3_interrupt_count--;
  52720. if( sqlite3_interrupt_count==0 ){
  52721. sqlite3_interrupt(db);
  52722. }
  52723. }
  52724. #endif
  52725. /* On any opcode with the "out2-prerelease" tag, free any
  52726. ** external allocations out of mem[p2] and set mem[p2] to be
  52727. ** an undefined integer. Opcodes will either fill in the integer
  52728. ** value or convert mem[p2] to a different type.
  52729. */
  52730. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  52731. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  52732. assert( pOp->p2>0 );
  52733. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52734. pOut = &aMem[pOp->p2];
  52735. memAboutToChange(p, pOut);
  52736. VdbeMemRelease(pOut);
  52737. pOut->flags = MEM_Int;
  52738. }
  52739. /* Sanity checking on other operands */
  52740. #ifdef SQLITE_DEBUG
  52741. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  52742. assert( pOp->p1>0 );
  52743. assert( pOp->p1<=(p->nMem-p->nCursor) );
  52744. assert( memIsValid(&aMem[pOp->p1]) );
  52745. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  52746. }
  52747. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  52748. assert( pOp->p2>0 );
  52749. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52750. assert( memIsValid(&aMem[pOp->p2]) );
  52751. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  52752. }
  52753. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  52754. assert( pOp->p3>0 );
  52755. assert( pOp->p3<=(p->nMem-p->nCursor) );
  52756. assert( memIsValid(&aMem[pOp->p3]) );
  52757. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  52758. }
  52759. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  52760. assert( pOp->p2>0 );
  52761. assert( pOp->p2<=(p->nMem-p->nCursor) );
  52762. memAboutToChange(p, &aMem[pOp->p2]);
  52763. }
  52764. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  52765. assert( pOp->p3>0 );
  52766. assert( pOp->p3<=(p->nMem-p->nCursor) );
  52767. memAboutToChange(p, &aMem[pOp->p3]);
  52768. }
  52769. #endif
  52770. switch( pOp->opcode ){
  52771. /*****************************************************************************
  52772. ** What follows is a massive switch statement where each case implements a
  52773. ** separate instruction in the virtual machine. If we follow the usual
  52774. ** indentation conventions, each case should be indented by 6 spaces. But
  52775. ** that is a lot of wasted space on the left margin. So the code within
  52776. ** the switch statement will break with convention and be flush-left. Another
  52777. ** big comment (similar to this one) will mark the point in the code where
  52778. ** we transition back to normal indentation.
  52779. **
  52780. ** The formatting of each case is important. The makefile for SQLite
  52781. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  52782. ** file looking for lines that begin with "case OP_". The opcodes.h files
  52783. ** will be filled with #defines that give unique integer values to each
  52784. ** opcode and the opcodes.c file is filled with an array of strings where
  52785. ** each string is the symbolic name for the corresponding opcode. If the
  52786. ** case statement is followed by a comment of the form "/# same as ... #/"
  52787. ** that comment is used to determine the particular value of the opcode.
  52788. **
  52789. ** Other keywords in the comment that follows each case are used to
  52790. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  52791. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  52792. ** the mkopcodeh.awk script for additional information.
  52793. **
  52794. ** Documentation about VDBE opcodes is generated by scanning this file
  52795. ** for lines of that contain "Opcode:". That line and all subsequent
  52796. ** comment lines are used in the generation of the opcode.html documentation
  52797. ** file.
  52798. **
  52799. ** SUMMARY:
  52800. **
  52801. ** Formatting is important to scripts that scan this file.
  52802. ** Do not deviate from the formatting style currently in use.
  52803. **
  52804. *****************************************************************************/
  52805. /* Opcode: Goto * P2 * * *
  52806. **
  52807. ** An unconditional jump to address P2.
  52808. ** The next instruction executed will be
  52809. ** the one at index P2 from the beginning of
  52810. ** the program.
  52811. */
  52812. case OP_Goto: { /* jump */
  52813. pc = pOp->p2 - 1;
  52814. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  52815. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  52816. ** completion. Check to see if sqlite3_interrupt() has been called
  52817. ** or if the progress callback needs to be invoked.
  52818. **
  52819. ** This code uses unstructured "goto" statements and does not look clean.
  52820. ** But that is not due to sloppy coding habits. The code is written this
  52821. ** way for performance, to avoid having to run the interrupt and progress
  52822. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  52823. ** faster according to "valgrind --tool=cachegrind" */
  52824. check_for_interrupt:
  52825. CHECK_FOR_INTERRUPT;
  52826. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  52827. /* Call the progress callback if it is configured and the required number
  52828. ** of VDBE ops have been executed (either since this invocation of
  52829. ** sqlite3VdbeExec() or since last time the progress callback was called).
  52830. ** If the progress callback returns non-zero, exit the virtual machine with
  52831. ** a return code SQLITE_ABORT.
  52832. */
  52833. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  52834. int prc;
  52835. prc = db->xProgress(db->pProgressArg);
  52836. if( prc!=0 ){
  52837. rc = SQLITE_INTERRUPT;
  52838. goto vdbe_error_halt;
  52839. }
  52840. if( db->xProgress!=0 ){
  52841. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  52842. }
  52843. }
  52844. #endif
  52845. break;
  52846. }
  52847. /* Opcode: Gosub P1 P2 * * *
  52848. **
  52849. ** Write the current address onto register P1
  52850. ** and then jump to address P2.
  52851. */
  52852. case OP_Gosub: { /* jump */
  52853. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  52854. pIn1 = &aMem[pOp->p1];
  52855. assert( (pIn1->flags & MEM_Dyn)==0 );
  52856. memAboutToChange(p, pIn1);
  52857. pIn1->flags = MEM_Int;
  52858. pIn1->u.i = pc;
  52859. REGISTER_TRACE(pOp->p1, pIn1);
  52860. pc = pOp->p2 - 1;
  52861. break;
  52862. }
  52863. /* Opcode: Return P1 * * * *
  52864. **
  52865. ** Jump to the next instruction after the address in register P1.
  52866. */
  52867. case OP_Return: { /* in1 */
  52868. pIn1 = &aMem[pOp->p1];
  52869. assert( pIn1->flags & MEM_Int );
  52870. pc = (int)pIn1->u.i;
  52871. break;
  52872. }
  52873. /* Opcode: Yield P1 * * * *
  52874. **
  52875. ** Swap the program counter with the value in register P1.
  52876. */
  52877. case OP_Yield: { /* in1 */
  52878. #if 0 /* local variables moved into u.aa */
  52879. int pcDest;
  52880. #endif /* local variables moved into u.aa */
  52881. pIn1 = &aMem[pOp->p1];
  52882. assert( (pIn1->flags & MEM_Dyn)==0 );
  52883. pIn1->flags = MEM_Int;
  52884. u.aa.pcDest = (int)pIn1->u.i;
  52885. pIn1->u.i = pc;
  52886. REGISTER_TRACE(pOp->p1, pIn1);
  52887. pc = u.aa.pcDest;
  52888. break;
  52889. }
  52890. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  52891. **
  52892. ** Check the value in register P3. If it is NULL then Halt using
  52893. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  52894. ** value in register P3 is not NULL, then this routine is a no-op.
  52895. */
  52896. case OP_HaltIfNull: { /* in3 */
  52897. pIn3 = &aMem[pOp->p3];
  52898. if( (pIn3->flags & MEM_Null)==0 ) break;
  52899. /* Fall through into OP_Halt */
  52900. }
  52901. /* Opcode: Halt P1 P2 * P4 *
  52902. **
  52903. ** Exit immediately. All open cursors, etc are closed
  52904. ** automatically.
  52905. **
  52906. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  52907. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  52908. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  52909. ** whether or not to rollback the current transaction. Do not rollback
  52910. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  52911. ** then back out all changes that have occurred during this execution of the
  52912. ** VDBE, but do not rollback the transaction.
  52913. **
  52914. ** If P4 is not null then it is an error message string.
  52915. **
  52916. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  52917. ** every program. So a jump past the last instruction of the program
  52918. ** is the same as executing Halt.
  52919. */
  52920. case OP_Halt: {
  52921. if( pOp->p1==SQLITE_OK && p->pFrame ){
  52922. /* Halt the sub-program. Return control to the parent frame. */
  52923. VdbeFrame *pFrame = p->pFrame;
  52924. p->pFrame = pFrame->pParent;
  52925. p->nFrame--;
  52926. sqlite3VdbeSetChanges(db, p->nChange);
  52927. pc = sqlite3VdbeFrameRestore(pFrame);
  52928. lastRowid = db->lastRowid;
  52929. if( pOp->p2==OE_Ignore ){
  52930. /* Instruction pc is the OP_Program that invoked the sub-program
  52931. ** currently being halted. If the p2 instruction of this OP_Halt
  52932. ** instruction is set to OE_Ignore, then the sub-program is throwing
  52933. ** an IGNORE exception. In this case jump to the address specified
  52934. ** as the p2 of the calling OP_Program. */
  52935. pc = p->aOp[pc].p2-1;
  52936. }
  52937. aOp = p->aOp;
  52938. aMem = p->aMem;
  52939. break;
  52940. }
  52941. p->rc = pOp->p1;
  52942. p->errorAction = (u8)pOp->p2;
  52943. p->pc = pc;
  52944. if( pOp->p4.z ){
  52945. assert( p->rc!=SQLITE_OK );
  52946. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  52947. testcase( sqlite3GlobalConfig.xLog!=0 );
  52948. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  52949. }else if( p->rc ){
  52950. testcase( sqlite3GlobalConfig.xLog!=0 );
  52951. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  52952. }
  52953. rc = sqlite3VdbeHalt(p);
  52954. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  52955. if( rc==SQLITE_BUSY ){
  52956. p->rc = rc = SQLITE_BUSY;
  52957. }else{
  52958. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  52959. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  52960. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  52961. }
  52962. goto vdbe_return;
  52963. }
  52964. /* Opcode: Integer P1 P2 * * *
  52965. **
  52966. ** The 32-bit integer value P1 is written into register P2.
  52967. */
  52968. case OP_Integer: { /* out2-prerelease */
  52969. pOut->u.i = pOp->p1;
  52970. break;
  52971. }
  52972. /* Opcode: Int64 * P2 * P4 *
  52973. **
  52974. ** P4 is a pointer to a 64-bit integer value.
  52975. ** Write that value into register P2.
  52976. */
  52977. case OP_Int64: { /* out2-prerelease */
  52978. assert( pOp->p4.pI64!=0 );
  52979. pOut->u.i = *pOp->p4.pI64;
  52980. break;
  52981. }
  52982. #ifndef SQLITE_OMIT_FLOATING_POINT
  52983. /* Opcode: Real * P2 * P4 *
  52984. **
  52985. ** P4 is a pointer to a 64-bit floating point value.
  52986. ** Write that value into register P2.
  52987. */
  52988. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  52989. pOut->flags = MEM_Real;
  52990. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  52991. pOut->r = *pOp->p4.pReal;
  52992. break;
  52993. }
  52994. #endif
  52995. /* Opcode: String8 * P2 * P4 *
  52996. **
  52997. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  52998. ** into an OP_String before it is executed for the first time.
  52999. */
  53000. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  53001. assert( pOp->p4.z!=0 );
  53002. pOp->opcode = OP_String;
  53003. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  53004. #ifndef SQLITE_OMIT_UTF16
  53005. if( encoding!=SQLITE_UTF8 ){
  53006. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  53007. if( rc==SQLITE_TOOBIG ) goto too_big;
  53008. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  53009. assert( pOut->zMalloc==pOut->z );
  53010. assert( pOut->flags & MEM_Dyn );
  53011. pOut->zMalloc = 0;
  53012. pOut->flags |= MEM_Static;
  53013. pOut->flags &= ~MEM_Dyn;
  53014. if( pOp->p4type==P4_DYNAMIC ){
  53015. sqlite3DbFree(db, pOp->p4.z);
  53016. }
  53017. pOp->p4type = P4_DYNAMIC;
  53018. pOp->p4.z = pOut->z;
  53019. pOp->p1 = pOut->n;
  53020. }
  53021. #endif
  53022. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  53023. goto too_big;
  53024. }
  53025. /* Fall through to the next case, OP_String */
  53026. }
  53027. /* Opcode: String P1 P2 * P4 *
  53028. **
  53029. ** The string value P4 of length P1 (bytes) is stored in register P2.
  53030. */
  53031. case OP_String: { /* out2-prerelease */
  53032. assert( pOp->p4.z!=0 );
  53033. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  53034. pOut->z = pOp->p4.z;
  53035. pOut->n = pOp->p1;
  53036. pOut->enc = encoding;
  53037. UPDATE_MAX_BLOBSIZE(pOut);
  53038. break;
  53039. }
  53040. /* Opcode: Null P1 P2 P3 * *
  53041. **
  53042. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  53043. ** NULL into register P3 and every register in between P2 and P3. If P3
  53044. ** is less than P2 (typically P3 is zero) then only register P2 is
  53045. ** set to NULL.
  53046. **
  53047. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  53048. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  53049. ** OP_Ne or OP_Eq.
  53050. */
  53051. case OP_Null: { /* out2-prerelease */
  53052. #if 0 /* local variables moved into u.ab */
  53053. int cnt;
  53054. u16 nullFlag;
  53055. #endif /* local variables moved into u.ab */
  53056. u.ab.cnt = pOp->p3-pOp->p2;
  53057. assert( pOp->p3<=(p->nMem-p->nCursor) );
  53058. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  53059. while( u.ab.cnt>0 ){
  53060. pOut++;
  53061. memAboutToChange(p, pOut);
  53062. VdbeMemRelease(pOut);
  53063. pOut->flags = u.ab.nullFlag;
  53064. u.ab.cnt--;
  53065. }
  53066. break;
  53067. }
  53068. /* Opcode: Blob P1 P2 * P4
  53069. **
  53070. ** P4 points to a blob of data P1 bytes long. Store this
  53071. ** blob in register P2.
  53072. */
  53073. case OP_Blob: { /* out2-prerelease */
  53074. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  53075. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  53076. pOut->enc = encoding;
  53077. UPDATE_MAX_BLOBSIZE(pOut);
  53078. break;
  53079. }
  53080. /* Opcode: Variable P1 P2 * P4 *
  53081. **
  53082. ** Transfer the values of bound parameter P1 into register P2
  53083. **
  53084. ** If the parameter is named, then its name appears in P4 and P3==1.
  53085. ** The P4 value is used by sqlite3_bind_parameter_name().
  53086. */
  53087. case OP_Variable: { /* out2-prerelease */
  53088. #if 0 /* local variables moved into u.ac */
  53089. Mem *pVar; /* Value being transferred */
  53090. #endif /* local variables moved into u.ac */
  53091. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  53092. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  53093. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  53094. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  53095. goto too_big;
  53096. }
  53097. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  53098. UPDATE_MAX_BLOBSIZE(pOut);
  53099. break;
  53100. }
  53101. /* Opcode: Move P1 P2 P3 * *
  53102. **
  53103. ** Move the values in register P1..P1+P3 over into
  53104. ** registers P2..P2+P3. Registers P1..P1+P3 are
  53105. ** left holding a NULL. It is an error for register ranges
  53106. ** P1..P1+P3 and P2..P2+P3 to overlap.
  53107. */
  53108. case OP_Move: {
  53109. #if 0 /* local variables moved into u.ad */
  53110. char *zMalloc; /* Holding variable for allocated memory */
  53111. int n; /* Number of registers left to copy */
  53112. int p1; /* Register to copy from */
  53113. int p2; /* Register to copy to */
  53114. #endif /* local variables moved into u.ad */
  53115. u.ad.n = pOp->p3 + 1;
  53116. u.ad.p1 = pOp->p1;
  53117. u.ad.p2 = pOp->p2;
  53118. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  53119. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  53120. pIn1 = &aMem[u.ad.p1];
  53121. pOut = &aMem[u.ad.p2];
  53122. while( u.ad.n-- ){
  53123. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  53124. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  53125. assert( memIsValid(pIn1) );
  53126. memAboutToChange(p, pOut);
  53127. u.ad.zMalloc = pOut->zMalloc;
  53128. pOut->zMalloc = 0;
  53129. sqlite3VdbeMemMove(pOut, pIn1);
  53130. #ifdef SQLITE_DEBUG
  53131. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  53132. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  53133. }
  53134. #endif
  53135. pIn1->zMalloc = u.ad.zMalloc;
  53136. REGISTER_TRACE(u.ad.p2++, pOut);
  53137. pIn1++;
  53138. pOut++;
  53139. }
  53140. break;
  53141. }
  53142. /* Opcode: Copy P1 P2 P3 * *
  53143. **
  53144. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  53145. **
  53146. ** This instruction makes a deep copy of the value. A duplicate
  53147. ** is made of any string or blob constant. See also OP_SCopy.
  53148. */
  53149. case OP_Copy: {
  53150. #if 0 /* local variables moved into u.ae */
  53151. int n;
  53152. #endif /* local variables moved into u.ae */
  53153. u.ae.n = pOp->p3;
  53154. pIn1 = &aMem[pOp->p1];
  53155. pOut = &aMem[pOp->p2];
  53156. assert( pOut!=pIn1 );
  53157. while( 1 ){
  53158. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  53159. Deephemeralize(pOut);
  53160. #ifdef SQLITE_DEBUG
  53161. pOut->pScopyFrom = 0;
  53162. #endif
  53163. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  53164. if( (u.ae.n--)==0 ) break;
  53165. pOut++;
  53166. pIn1++;
  53167. }
  53168. break;
  53169. }
  53170. /* Opcode: SCopy P1 P2 * * *
  53171. **
  53172. ** Make a shallow copy of register P1 into register P2.
  53173. **
  53174. ** This instruction makes a shallow copy of the value. If the value
  53175. ** is a string or blob, then the copy is only a pointer to the
  53176. ** original and hence if the original changes so will the copy.
  53177. ** Worse, if the original is deallocated, the copy becomes invalid.
  53178. ** Thus the program must guarantee that the original will not change
  53179. ** during the lifetime of the copy. Use OP_Copy to make a complete
  53180. ** copy.
  53181. */
  53182. case OP_SCopy: { /* in1, out2 */
  53183. pIn1 = &aMem[pOp->p1];
  53184. pOut = &aMem[pOp->p2];
  53185. assert( pOut!=pIn1 );
  53186. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  53187. #ifdef SQLITE_DEBUG
  53188. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  53189. #endif
  53190. REGISTER_TRACE(pOp->p2, pOut);
  53191. break;
  53192. }
  53193. /* Opcode: ResultRow P1 P2 * * *
  53194. **
  53195. ** The registers P1 through P1+P2-1 contain a single row of
  53196. ** results. This opcode causes the sqlite3_step() call to terminate
  53197. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  53198. ** structure to provide access to the top P1 values as the result
  53199. ** row.
  53200. */
  53201. case OP_ResultRow: {
  53202. #if 0 /* local variables moved into u.af */
  53203. Mem *pMem;
  53204. int i;
  53205. #endif /* local variables moved into u.af */
  53206. assert( p->nResColumn==pOp->p2 );
  53207. assert( pOp->p1>0 );
  53208. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  53209. /* If this statement has violated immediate foreign key constraints, do
  53210. ** not return the number of rows modified. And do not RELEASE the statement
  53211. ** transaction. It needs to be rolled back. */
  53212. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  53213. assert( db->flags&SQLITE_CountRows );
  53214. assert( p->usesStmtJournal );
  53215. break;
  53216. }
  53217. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  53218. ** DML statements invoke this opcode to return the number of rows
  53219. ** modified to the user. This is the only way that a VM that
  53220. ** opens a statement transaction may invoke this opcode.
  53221. **
  53222. ** In case this is such a statement, close any statement transaction
  53223. ** opened by this VM before returning control to the user. This is to
  53224. ** ensure that statement-transactions are always nested, not overlapping.
  53225. ** If the open statement-transaction is not closed here, then the user
  53226. ** may step another VM that opens its own statement transaction. This
  53227. ** may lead to overlapping statement transactions.
  53228. **
  53229. ** The statement transaction is never a top-level transaction. Hence
  53230. ** the RELEASE call below can never fail.
  53231. */
  53232. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  53233. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  53234. if( NEVER(rc!=SQLITE_OK) ){
  53235. break;
  53236. }
  53237. /* Invalidate all ephemeral cursor row caches */
  53238. p->cacheCtr = (p->cacheCtr + 2)|1;
  53239. /* Make sure the results of the current row are \000 terminated
  53240. ** and have an assigned type. The results are de-ephemeralized as
  53241. ** a side effect.
  53242. */
  53243. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  53244. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  53245. assert( memIsValid(&u.af.pMem[u.af.i]) );
  53246. Deephemeralize(&u.af.pMem[u.af.i]);
  53247. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  53248. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  53249. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  53250. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  53251. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  53252. }
  53253. if( db->mallocFailed ) goto no_mem;
  53254. /* Return SQLITE_ROW
  53255. */
  53256. p->pc = pc + 1;
  53257. rc = SQLITE_ROW;
  53258. goto vdbe_return;
  53259. }
  53260. /* Opcode: Concat P1 P2 P3 * *
  53261. **
  53262. ** Add the text in register P1 onto the end of the text in
  53263. ** register P2 and store the result in register P3.
  53264. ** If either the P1 or P2 text are NULL then store NULL in P3.
  53265. **
  53266. ** P3 = P2 || P1
  53267. **
  53268. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  53269. ** if P3 is the same register as P2, the implementation is able
  53270. ** to avoid a memcpy().
  53271. */
  53272. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  53273. #if 0 /* local variables moved into u.ag */
  53274. i64 nByte;
  53275. #endif /* local variables moved into u.ag */
  53276. pIn1 = &aMem[pOp->p1];
  53277. pIn2 = &aMem[pOp->p2];
  53278. pOut = &aMem[pOp->p3];
  53279. assert( pIn1!=pOut );
  53280. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  53281. sqlite3VdbeMemSetNull(pOut);
  53282. break;
  53283. }
  53284. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  53285. Stringify(pIn1, encoding);
  53286. Stringify(pIn2, encoding);
  53287. u.ag.nByte = pIn1->n + pIn2->n;
  53288. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  53289. goto too_big;
  53290. }
  53291. MemSetTypeFlag(pOut, MEM_Str);
  53292. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  53293. goto no_mem;
  53294. }
  53295. if( pOut!=pIn2 ){
  53296. memcpy(pOut->z, pIn2->z, pIn2->n);
  53297. }
  53298. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  53299. pOut->z[u.ag.nByte] = 0;
  53300. pOut->z[u.ag.nByte+1] = 0;
  53301. pOut->flags |= MEM_Term;
  53302. pOut->n = (int)u.ag.nByte;
  53303. pOut->enc = encoding;
  53304. UPDATE_MAX_BLOBSIZE(pOut);
  53305. break;
  53306. }
  53307. /* Opcode: Add P1 P2 P3 * *
  53308. **
  53309. ** Add the value in register P1 to the value in register P2
  53310. ** and store the result in register P3.
  53311. ** If either input is NULL, the result is NULL.
  53312. */
  53313. /* Opcode: Multiply P1 P2 P3 * *
  53314. **
  53315. **
  53316. ** Multiply the value in register P1 by the value in register P2
  53317. ** and store the result in register P3.
  53318. ** If either input is NULL, the result is NULL.
  53319. */
  53320. /* Opcode: Subtract P1 P2 P3 * *
  53321. **
  53322. ** Subtract the value in register P1 from the value in register P2
  53323. ** and store the result in register P3.
  53324. ** If either input is NULL, the result is NULL.
  53325. */
  53326. /* Opcode: Divide P1 P2 P3 * *
  53327. **
  53328. ** Divide the value in register P1 by the value in register P2
  53329. ** and store the result in register P3 (P3=P2/P1). If the value in
  53330. ** register P1 is zero, then the result is NULL. If either input is
  53331. ** NULL, the result is NULL.
  53332. */
  53333. /* Opcode: Remainder P1 P2 P3 * *
  53334. **
  53335. ** Compute the remainder after integer division of the value in
  53336. ** register P1 by the value in register P2 and store the result in P3.
  53337. ** If the value in register P2 is zero the result is NULL.
  53338. ** If either operand is NULL, the result is NULL.
  53339. */
  53340. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  53341. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  53342. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  53343. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  53344. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  53345. #if 0 /* local variables moved into u.ah */
  53346. char bIntint; /* Started out as two integer operands */
  53347. int flags; /* Combined MEM_* flags from both inputs */
  53348. i64 iA; /* Integer value of left operand */
  53349. i64 iB; /* Integer value of right operand */
  53350. double rA; /* Real value of left operand */
  53351. double rB; /* Real value of right operand */
  53352. #endif /* local variables moved into u.ah */
  53353. pIn1 = &aMem[pOp->p1];
  53354. applyNumericAffinity(pIn1);
  53355. pIn2 = &aMem[pOp->p2];
  53356. applyNumericAffinity(pIn2);
  53357. pOut = &aMem[pOp->p3];
  53358. u.ah.flags = pIn1->flags | pIn2->flags;
  53359. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  53360. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  53361. u.ah.iA = pIn1->u.i;
  53362. u.ah.iB = pIn2->u.i;
  53363. u.ah.bIntint = 1;
  53364. switch( pOp->opcode ){
  53365. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53366. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53367. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  53368. case OP_Divide: {
  53369. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53370. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  53371. u.ah.iB /= u.ah.iA;
  53372. break;
  53373. }
  53374. default: {
  53375. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53376. if( u.ah.iA==-1 ) u.ah.iA = 1;
  53377. u.ah.iB %= u.ah.iA;
  53378. break;
  53379. }
  53380. }
  53381. pOut->u.i = u.ah.iB;
  53382. MemSetTypeFlag(pOut, MEM_Int);
  53383. }else{
  53384. u.ah.bIntint = 0;
  53385. fp_math:
  53386. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  53387. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  53388. switch( pOp->opcode ){
  53389. case OP_Add: u.ah.rB += u.ah.rA; break;
  53390. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  53391. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  53392. case OP_Divide: {
  53393. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  53394. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  53395. u.ah.rB /= u.ah.rA;
  53396. break;
  53397. }
  53398. default: {
  53399. u.ah.iA = (i64)u.ah.rA;
  53400. u.ah.iB = (i64)u.ah.rB;
  53401. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  53402. if( u.ah.iA==-1 ) u.ah.iA = 1;
  53403. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  53404. break;
  53405. }
  53406. }
  53407. #ifdef SQLITE_OMIT_FLOATING_POINT
  53408. pOut->u.i = u.ah.rB;
  53409. MemSetTypeFlag(pOut, MEM_Int);
  53410. #else
  53411. if( sqlite3IsNaN(u.ah.rB) ){
  53412. goto arithmetic_result_is_null;
  53413. }
  53414. pOut->r = u.ah.rB;
  53415. MemSetTypeFlag(pOut, MEM_Real);
  53416. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  53417. sqlite3VdbeIntegerAffinity(pOut);
  53418. }
  53419. #endif
  53420. }
  53421. break;
  53422. arithmetic_result_is_null:
  53423. sqlite3VdbeMemSetNull(pOut);
  53424. break;
  53425. }
  53426. /* Opcode: CollSeq P1 * * P4
  53427. **
  53428. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  53429. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  53430. ** be returned. This is used by the built-in min(), max() and nullif()
  53431. ** functions.
  53432. **
  53433. ** If P1 is not zero, then it is a register that a subsequent min() or
  53434. ** max() aggregate will set to 1 if the current row is not the minimum or
  53435. ** maximum. The P1 register is initialized to 0 by this instruction.
  53436. **
  53437. ** The interface used by the implementation of the aforementioned functions
  53438. ** to retrieve the collation sequence set by this opcode is not available
  53439. ** publicly, only to user functions defined in func.c.
  53440. */
  53441. case OP_CollSeq: {
  53442. assert( pOp->p4type==P4_COLLSEQ );
  53443. if( pOp->p1 ){
  53444. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  53445. }
  53446. break;
  53447. }
  53448. /* Opcode: Function P1 P2 P3 P4 P5
  53449. **
  53450. ** Invoke a user function (P4 is a pointer to a Function structure that
  53451. ** defines the function) with P5 arguments taken from register P2 and
  53452. ** successors. The result of the function is stored in register P3.
  53453. ** Register P3 must not be one of the function inputs.
  53454. **
  53455. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  53456. ** function was determined to be constant at compile time. If the first
  53457. ** argument was constant then bit 0 of P1 is set. This is used to determine
  53458. ** whether meta data associated with a user function argument using the
  53459. ** sqlite3_set_auxdata() API may be safely retained until the next
  53460. ** invocation of this opcode.
  53461. **
  53462. ** See also: AggStep and AggFinal
  53463. */
  53464. case OP_Function: {
  53465. #if 0 /* local variables moved into u.ai */
  53466. int i;
  53467. Mem *pArg;
  53468. sqlite3_context ctx;
  53469. sqlite3_value **apVal;
  53470. int n;
  53471. #endif /* local variables moved into u.ai */
  53472. u.ai.n = pOp->p5;
  53473. u.ai.apVal = p->apArg;
  53474. assert( u.ai.apVal || u.ai.n==0 );
  53475. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  53476. pOut = &aMem[pOp->p3];
  53477. memAboutToChange(p, pOut);
  53478. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) );
  53479. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  53480. u.ai.pArg = &aMem[pOp->p2];
  53481. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  53482. assert( memIsValid(u.ai.pArg) );
  53483. u.ai.apVal[u.ai.i] = u.ai.pArg;
  53484. Deephemeralize(u.ai.pArg);
  53485. sqlite3VdbeMemStoreType(u.ai.pArg);
  53486. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  53487. }
  53488. assert( pOp->p4type==P4_FUNCDEF );
  53489. u.ai.ctx.pFunc = pOp->p4.pFunc;
  53490. u.ai.ctx.s.flags = MEM_Null;
  53491. u.ai.ctx.s.db = db;
  53492. u.ai.ctx.s.xDel = 0;
  53493. u.ai.ctx.s.zMalloc = 0;
  53494. u.ai.ctx.iOp = pc;
  53495. u.ai.ctx.pVdbe = p;
  53496. /* The output cell may already have a buffer allocated. Move
  53497. ** the pointer to u.ai.ctx.s so in case the user-function can use
  53498. ** the already allocated buffer instead of allocating a new one.
  53499. */
  53500. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  53501. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  53502. u.ai.ctx.fErrorOrAux = 0;
  53503. if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  53504. assert( pOp>aOp );
  53505. assert( pOp[-1].p4type==P4_COLLSEQ );
  53506. assert( pOp[-1].opcode==OP_CollSeq );
  53507. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  53508. }
  53509. db->lastRowid = lastRowid;
  53510. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  53511. lastRowid = db->lastRowid;
  53512. if( db->mallocFailed ){
  53513. /* Even though a malloc() has failed, the implementation of the
  53514. ** user function may have called an sqlite3_result_XXX() function
  53515. ** to return a value. The following call releases any resources
  53516. ** associated with such a value.
  53517. */
  53518. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  53519. goto no_mem;
  53520. }
  53521. /* If the function returned an error, throw an exception */
  53522. if( u.ai.ctx.fErrorOrAux ){
  53523. if( u.ai.ctx.isError ){
  53524. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  53525. rc = u.ai.ctx.isError;
  53526. }
  53527. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  53528. }
  53529. /* Copy the result of the function into register P3 */
  53530. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  53531. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  53532. if( sqlite3VdbeMemTooBig(pOut) ){
  53533. goto too_big;
  53534. }
  53535. #if 0
  53536. /* The app-defined function has done something that as caused this
  53537. ** statement to expire. (Perhaps the function called sqlite3_exec()
  53538. ** with a CREATE TABLE statement.)
  53539. */
  53540. if( p->expired ) rc = SQLITE_ABORT;
  53541. #endif
  53542. REGISTER_TRACE(pOp->p3, pOut);
  53543. UPDATE_MAX_BLOBSIZE(pOut);
  53544. break;
  53545. }
  53546. /* Opcode: BitAnd P1 P2 P3 * *
  53547. **
  53548. ** Take the bit-wise AND of the values in register P1 and P2 and
  53549. ** store the result in register P3.
  53550. ** If either input is NULL, the result is NULL.
  53551. */
  53552. /* Opcode: BitOr P1 P2 P3 * *
  53553. **
  53554. ** Take the bit-wise OR of the values in register P1 and P2 and
  53555. ** store the result in register P3.
  53556. ** If either input is NULL, the result is NULL.
  53557. */
  53558. /* Opcode: ShiftLeft P1 P2 P3 * *
  53559. **
  53560. ** Shift the integer value in register P2 to the left by the
  53561. ** number of bits specified by the integer in register P1.
  53562. ** Store the result in register P3.
  53563. ** If either input is NULL, the result is NULL.
  53564. */
  53565. /* Opcode: ShiftRight P1 P2 P3 * *
  53566. **
  53567. ** Shift the integer value in register P2 to the right by the
  53568. ** number of bits specified by the integer in register P1.
  53569. ** Store the result in register P3.
  53570. ** If either input is NULL, the result is NULL.
  53571. */
  53572. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  53573. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  53574. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  53575. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  53576. #if 0 /* local variables moved into u.aj */
  53577. i64 iA;
  53578. u64 uA;
  53579. i64 iB;
  53580. u8 op;
  53581. #endif /* local variables moved into u.aj */
  53582. pIn1 = &aMem[pOp->p1];
  53583. pIn2 = &aMem[pOp->p2];
  53584. pOut = &aMem[pOp->p3];
  53585. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  53586. sqlite3VdbeMemSetNull(pOut);
  53587. break;
  53588. }
  53589. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  53590. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  53591. u.aj.op = pOp->opcode;
  53592. if( u.aj.op==OP_BitAnd ){
  53593. u.aj.iA &= u.aj.iB;
  53594. }else if( u.aj.op==OP_BitOr ){
  53595. u.aj.iA |= u.aj.iB;
  53596. }else if( u.aj.iB!=0 ){
  53597. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  53598. /* If shifting by a negative amount, shift in the other direction */
  53599. if( u.aj.iB<0 ){
  53600. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  53601. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  53602. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  53603. }
  53604. if( u.aj.iB>=64 ){
  53605. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  53606. }else{
  53607. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  53608. if( u.aj.op==OP_ShiftLeft ){
  53609. u.aj.uA <<= u.aj.iB;
  53610. }else{
  53611. u.aj.uA >>= u.aj.iB;
  53612. /* Sign-extend on a right shift of a negative number */
  53613. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  53614. }
  53615. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  53616. }
  53617. }
  53618. pOut->u.i = u.aj.iA;
  53619. MemSetTypeFlag(pOut, MEM_Int);
  53620. break;
  53621. }
  53622. /* Opcode: AddImm P1 P2 * * *
  53623. **
  53624. ** Add the constant P2 to the value in register P1.
  53625. ** The result is always an integer.
  53626. **
  53627. ** To force any register to be an integer, just add 0.
  53628. */
  53629. case OP_AddImm: { /* in1 */
  53630. pIn1 = &aMem[pOp->p1];
  53631. memAboutToChange(p, pIn1);
  53632. sqlite3VdbeMemIntegerify(pIn1);
  53633. pIn1->u.i += pOp->p2;
  53634. break;
  53635. }
  53636. /* Opcode: MustBeInt P1 P2 * * *
  53637. **
  53638. ** Force the value in register P1 to be an integer. If the value
  53639. ** in P1 is not an integer and cannot be converted into an integer
  53640. ** without data loss, then jump immediately to P2, or if P2==0
  53641. ** raise an SQLITE_MISMATCH exception.
  53642. */
  53643. case OP_MustBeInt: { /* jump, in1 */
  53644. pIn1 = &aMem[pOp->p1];
  53645. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  53646. if( (pIn1->flags & MEM_Int)==0 ){
  53647. if( pOp->p2==0 ){
  53648. rc = SQLITE_MISMATCH;
  53649. goto abort_due_to_error;
  53650. }else{
  53651. pc = pOp->p2 - 1;
  53652. }
  53653. }else{
  53654. MemSetTypeFlag(pIn1, MEM_Int);
  53655. }
  53656. break;
  53657. }
  53658. #ifndef SQLITE_OMIT_FLOATING_POINT
  53659. /* Opcode: RealAffinity P1 * * * *
  53660. **
  53661. ** If register P1 holds an integer convert it to a real value.
  53662. **
  53663. ** This opcode is used when extracting information from a column that
  53664. ** has REAL affinity. Such column values may still be stored as
  53665. ** integers, for space efficiency, but after extraction we want them
  53666. ** to have only a real value.
  53667. */
  53668. case OP_RealAffinity: { /* in1 */
  53669. pIn1 = &aMem[pOp->p1];
  53670. if( pIn1->flags & MEM_Int ){
  53671. sqlite3VdbeMemRealify(pIn1);
  53672. }
  53673. break;
  53674. }
  53675. #endif
  53676. #ifndef SQLITE_OMIT_CAST
  53677. /* Opcode: ToText P1 * * * *
  53678. **
  53679. ** Force the value in register P1 to be text.
  53680. ** If the value is numeric, convert it to a string using the
  53681. ** equivalent of printf(). Blob values are unchanged and
  53682. ** are afterwards simply interpreted as text.
  53683. **
  53684. ** A NULL value is not changed by this routine. It remains NULL.
  53685. */
  53686. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  53687. pIn1 = &aMem[pOp->p1];
  53688. memAboutToChange(p, pIn1);
  53689. if( pIn1->flags & MEM_Null ) break;
  53690. assert( MEM_Str==(MEM_Blob>>3) );
  53691. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  53692. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  53693. rc = ExpandBlob(pIn1);
  53694. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  53695. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  53696. UPDATE_MAX_BLOBSIZE(pIn1);
  53697. break;
  53698. }
  53699. /* Opcode: ToBlob P1 * * * *
  53700. **
  53701. ** Force the value in register P1 to be a BLOB.
  53702. ** If the value is numeric, convert it to a string first.
  53703. ** Strings are simply reinterpreted as blobs with no change
  53704. ** to the underlying data.
  53705. **
  53706. ** A NULL value is not changed by this routine. It remains NULL.
  53707. */
  53708. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  53709. pIn1 = &aMem[pOp->p1];
  53710. if( pIn1->flags & MEM_Null ) break;
  53711. if( (pIn1->flags & MEM_Blob)==0 ){
  53712. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  53713. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  53714. MemSetTypeFlag(pIn1, MEM_Blob);
  53715. }else{
  53716. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  53717. }
  53718. UPDATE_MAX_BLOBSIZE(pIn1);
  53719. break;
  53720. }
  53721. /* Opcode: ToNumeric P1 * * * *
  53722. **
  53723. ** Force the value in register P1 to be numeric (either an
  53724. ** integer or a floating-point number.)
  53725. ** If the value is text or blob, try to convert it to an using the
  53726. ** equivalent of atoi() or atof() and store 0 if no such conversion
  53727. ** is possible.
  53728. **
  53729. ** A NULL value is not changed by this routine. It remains NULL.
  53730. */
  53731. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  53732. pIn1 = &aMem[pOp->p1];
  53733. sqlite3VdbeMemNumerify(pIn1);
  53734. break;
  53735. }
  53736. #endif /* SQLITE_OMIT_CAST */
  53737. /* Opcode: ToInt P1 * * * *
  53738. **
  53739. ** Force the value in register P1 to be an integer. If
  53740. ** The value is currently a real number, drop its fractional part.
  53741. ** If the value is text or blob, try to convert it to an integer using the
  53742. ** equivalent of atoi() and store 0 if no such conversion is possible.
  53743. **
  53744. ** A NULL value is not changed by this routine. It remains NULL.
  53745. */
  53746. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  53747. pIn1 = &aMem[pOp->p1];
  53748. if( (pIn1->flags & MEM_Null)==0 ){
  53749. sqlite3VdbeMemIntegerify(pIn1);
  53750. }
  53751. break;
  53752. }
  53753. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  53754. /* Opcode: ToReal P1 * * * *
  53755. **
  53756. ** Force the value in register P1 to be a floating point number.
  53757. ** If The value is currently an integer, convert it.
  53758. ** If the value is text or blob, try to convert it to an integer using the
  53759. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  53760. **
  53761. ** A NULL value is not changed by this routine. It remains NULL.
  53762. */
  53763. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  53764. pIn1 = &aMem[pOp->p1];
  53765. memAboutToChange(p, pIn1);
  53766. if( (pIn1->flags & MEM_Null)==0 ){
  53767. sqlite3VdbeMemRealify(pIn1);
  53768. }
  53769. break;
  53770. }
  53771. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  53772. /* Opcode: Lt P1 P2 P3 P4 P5
  53773. **
  53774. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  53775. ** jump to address P2.
  53776. **
  53777. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  53778. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  53779. ** bit is clear then fall through if either operand is NULL.
  53780. **
  53781. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  53782. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  53783. ** to coerce both inputs according to this affinity before the
  53784. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  53785. ** affinity is used. Note that the affinity conversions are stored
  53786. ** back into the input registers P1 and P3. So this opcode can cause
  53787. ** persistent changes to registers P1 and P3.
  53788. **
  53789. ** Once any conversions have taken place, and neither value is NULL,
  53790. ** the values are compared. If both values are blobs then memcmp() is
  53791. ** used to determine the results of the comparison. If both values
  53792. ** are text, then the appropriate collating function specified in
  53793. ** P4 is used to do the comparison. If P4 is not specified then
  53794. ** memcmp() is used to compare text string. If both values are
  53795. ** numeric, then a numeric comparison is used. If the two values
  53796. ** are of different types, then numbers are considered less than
  53797. ** strings and strings are considered less than blobs.
  53798. **
  53799. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  53800. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  53801. **
  53802. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  53803. ** equal to one another, provided that they do not have their MEM_Cleared
  53804. ** bit set.
  53805. */
  53806. /* Opcode: Ne P1 P2 P3 P4 P5
  53807. **
  53808. ** This works just like the Lt opcode except that the jump is taken if
  53809. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  53810. ** additional information.
  53811. **
  53812. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  53813. ** true or false and is never NULL. If both operands are NULL then the result
  53814. ** of comparison is false. If either operand is NULL then the result is true.
  53815. ** If neither operand is NULL the result is the same as it would be if
  53816. ** the SQLITE_NULLEQ flag were omitted from P5.
  53817. */
  53818. /* Opcode: Eq P1 P2 P3 P4 P5
  53819. **
  53820. ** This works just like the Lt opcode except that the jump is taken if
  53821. ** the operands in registers P1 and P3 are equal.
  53822. ** See the Lt opcode for additional information.
  53823. **
  53824. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  53825. ** true or false and is never NULL. If both operands are NULL then the result
  53826. ** of comparison is true. If either operand is NULL then the result is false.
  53827. ** If neither operand is NULL the result is the same as it would be if
  53828. ** the SQLITE_NULLEQ flag were omitted from P5.
  53829. */
  53830. /* Opcode: Le P1 P2 P3 P4 P5
  53831. **
  53832. ** This works just like the Lt opcode except that the jump is taken if
  53833. ** the content of register P3 is less than or equal to the content of
  53834. ** register P1. See the Lt opcode for additional information.
  53835. */
  53836. /* Opcode: Gt P1 P2 P3 P4 P5
  53837. **
  53838. ** This works just like the Lt opcode except that the jump is taken if
  53839. ** the content of register P3 is greater than the content of
  53840. ** register P1. See the Lt opcode for additional information.
  53841. */
  53842. /* Opcode: Ge P1 P2 P3 P4 P5
  53843. **
  53844. ** This works just like the Lt opcode except that the jump is taken if
  53845. ** the content of register P3 is greater than or equal to the content of
  53846. ** register P1. See the Lt opcode for additional information.
  53847. */
  53848. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  53849. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  53850. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  53851. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  53852. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  53853. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  53854. #if 0 /* local variables moved into u.ak */
  53855. int res; /* Result of the comparison of pIn1 against pIn3 */
  53856. char affinity; /* Affinity to use for comparison */
  53857. u16 flags1; /* Copy of initial value of pIn1->flags */
  53858. u16 flags3; /* Copy of initial value of pIn3->flags */
  53859. #endif /* local variables moved into u.ak */
  53860. pIn1 = &aMem[pOp->p1];
  53861. pIn3 = &aMem[pOp->p3];
  53862. u.ak.flags1 = pIn1->flags;
  53863. u.ak.flags3 = pIn3->flags;
  53864. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  53865. /* One or both operands are NULL */
  53866. if( pOp->p5 & SQLITE_NULLEQ ){
  53867. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  53868. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  53869. ** or not both operands are null.
  53870. */
  53871. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  53872. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  53873. if( (u.ak.flags1&MEM_Null)!=0
  53874. && (u.ak.flags3&MEM_Null)!=0
  53875. && (u.ak.flags3&MEM_Cleared)==0
  53876. ){
  53877. u.ak.res = 0; /* Results are equal */
  53878. }else{
  53879. u.ak.res = 1; /* Results are not equal */
  53880. }
  53881. }else{
  53882. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  53883. ** then the result is always NULL.
  53884. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  53885. */
  53886. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  53887. pc = pOp->p2-1;
  53888. }else if( pOp->p5 & SQLITE_STOREP2 ){
  53889. pOut = &aMem[pOp->p2];
  53890. MemSetTypeFlag(pOut, MEM_Null);
  53891. REGISTER_TRACE(pOp->p2, pOut);
  53892. }
  53893. break;
  53894. }
  53895. }else{
  53896. /* Neither operand is NULL. Do a comparison. */
  53897. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  53898. if( u.ak.affinity ){
  53899. applyAffinity(pIn1, u.ak.affinity, encoding);
  53900. applyAffinity(pIn3, u.ak.affinity, encoding);
  53901. if( db->mallocFailed ) goto no_mem;
  53902. }
  53903. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  53904. ExpandBlob(pIn1);
  53905. ExpandBlob(pIn3);
  53906. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  53907. }
  53908. switch( pOp->opcode ){
  53909. case OP_Eq: u.ak.res = u.ak.res==0; break;
  53910. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  53911. case OP_Lt: u.ak.res = u.ak.res<0; break;
  53912. case OP_Le: u.ak.res = u.ak.res<=0; break;
  53913. case OP_Gt: u.ak.res = u.ak.res>0; break;
  53914. default: u.ak.res = u.ak.res>=0; break;
  53915. }
  53916. if( pOp->p5 & SQLITE_STOREP2 ){
  53917. pOut = &aMem[pOp->p2];
  53918. memAboutToChange(p, pOut);
  53919. MemSetTypeFlag(pOut, MEM_Int);
  53920. pOut->u.i = u.ak.res;
  53921. REGISTER_TRACE(pOp->p2, pOut);
  53922. }else if( u.ak.res ){
  53923. pc = pOp->p2-1;
  53924. }
  53925. /* Undo any changes made by applyAffinity() to the input registers. */
  53926. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  53927. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  53928. break;
  53929. }
  53930. /* Opcode: Permutation * * * P4 *
  53931. **
  53932. ** Set the permutation used by the OP_Compare operator to be the array
  53933. ** of integers in P4.
  53934. **
  53935. ** The permutation is only valid until the next OP_Compare that has
  53936. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  53937. ** occur immediately prior to the OP_Compare.
  53938. */
  53939. case OP_Permutation: {
  53940. assert( pOp->p4type==P4_INTARRAY );
  53941. assert( pOp->p4.ai );
  53942. aPermute = pOp->p4.ai;
  53943. break;
  53944. }
  53945. /* Opcode: Compare P1 P2 P3 P4 P5
  53946. **
  53947. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  53948. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  53949. ** the comparison for use by the next OP_Jump instruct.
  53950. **
  53951. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  53952. ** determined by the most recent OP_Permutation operator. If the
  53953. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  53954. ** order.
  53955. **
  53956. ** P4 is a KeyInfo structure that defines collating sequences and sort
  53957. ** orders for the comparison. The permutation applies to registers
  53958. ** only. The KeyInfo elements are used sequentially.
  53959. **
  53960. ** The comparison is a sort comparison, so NULLs compare equal,
  53961. ** NULLs are less than numbers, numbers are less than strings,
  53962. ** and strings are less than blobs.
  53963. */
  53964. case OP_Compare: {
  53965. #if 0 /* local variables moved into u.al */
  53966. int n;
  53967. int i;
  53968. int p1;
  53969. int p2;
  53970. const KeyInfo *pKeyInfo;
  53971. int idx;
  53972. CollSeq *pColl; /* Collating sequence to use on this term */
  53973. int bRev; /* True for DESCENDING sort order */
  53974. #endif /* local variables moved into u.al */
  53975. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  53976. u.al.n = pOp->p3;
  53977. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  53978. assert( u.al.n>0 );
  53979. assert( u.al.pKeyInfo!=0 );
  53980. u.al.p1 = pOp->p1;
  53981. u.al.p2 = pOp->p2;
  53982. #if SQLITE_DEBUG
  53983. if( aPermute ){
  53984. int k, mx = 0;
  53985. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  53986. assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 );
  53987. assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 );
  53988. }else{
  53989. assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 );
  53990. assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 );
  53991. }
  53992. #endif /* SQLITE_DEBUG */
  53993. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  53994. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  53995. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  53996. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  53997. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  53998. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  53999. assert( u.al.i<u.al.pKeyInfo->nField );
  54000. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  54001. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  54002. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  54003. if( iCompare ){
  54004. if( u.al.bRev ) iCompare = -iCompare;
  54005. break;
  54006. }
  54007. }
  54008. aPermute = 0;
  54009. break;
  54010. }
  54011. /* Opcode: Jump P1 P2 P3 * *
  54012. **
  54013. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  54014. ** in the most recent OP_Compare instruction the P1 vector was less than
  54015. ** equal to, or greater than the P2 vector, respectively.
  54016. */
  54017. case OP_Jump: { /* jump */
  54018. if( iCompare<0 ){
  54019. pc = pOp->p1 - 1;
  54020. }else if( iCompare==0 ){
  54021. pc = pOp->p2 - 1;
  54022. }else{
  54023. pc = pOp->p3 - 1;
  54024. }
  54025. break;
  54026. }
  54027. /* Opcode: And P1 P2 P3 * *
  54028. **
  54029. ** Take the logical AND of the values in registers P1 and P2 and
  54030. ** write the result into register P3.
  54031. **
  54032. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  54033. ** the other input is NULL. A NULL and true or two NULLs give
  54034. ** a NULL output.
  54035. */
  54036. /* Opcode: Or P1 P2 P3 * *
  54037. **
  54038. ** Take the logical OR of the values in register P1 and P2 and
  54039. ** store the answer in register P3.
  54040. **
  54041. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  54042. ** even if the other input is NULL. A NULL and false or two NULLs
  54043. ** give a NULL output.
  54044. */
  54045. case OP_And: /* same as TK_AND, in1, in2, out3 */
  54046. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  54047. #if 0 /* local variables moved into u.am */
  54048. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  54049. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  54050. #endif /* local variables moved into u.am */
  54051. pIn1 = &aMem[pOp->p1];
  54052. if( pIn1->flags & MEM_Null ){
  54053. u.am.v1 = 2;
  54054. }else{
  54055. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  54056. }
  54057. pIn2 = &aMem[pOp->p2];
  54058. if( pIn2->flags & MEM_Null ){
  54059. u.am.v2 = 2;
  54060. }else{
  54061. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  54062. }
  54063. if( pOp->opcode==OP_And ){
  54064. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  54065. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  54066. }else{
  54067. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  54068. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  54069. }
  54070. pOut = &aMem[pOp->p3];
  54071. if( u.am.v1==2 ){
  54072. MemSetTypeFlag(pOut, MEM_Null);
  54073. }else{
  54074. pOut->u.i = u.am.v1;
  54075. MemSetTypeFlag(pOut, MEM_Int);
  54076. }
  54077. break;
  54078. }
  54079. /* Opcode: Not P1 P2 * * *
  54080. **
  54081. ** Interpret the value in register P1 as a boolean value. Store the
  54082. ** boolean complement in register P2. If the value in register P1 is
  54083. ** NULL, then a NULL is stored in P2.
  54084. */
  54085. case OP_Not: { /* same as TK_NOT, in1, out2 */
  54086. pIn1 = &aMem[pOp->p1];
  54087. pOut = &aMem[pOp->p2];
  54088. if( pIn1->flags & MEM_Null ){
  54089. sqlite3VdbeMemSetNull(pOut);
  54090. }else{
  54091. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  54092. }
  54093. break;
  54094. }
  54095. /* Opcode: BitNot P1 P2 * * *
  54096. **
  54097. ** Interpret the content of register P1 as an integer. Store the
  54098. ** ones-complement of the P1 value into register P2. If P1 holds
  54099. ** a NULL then store a NULL in P2.
  54100. */
  54101. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  54102. pIn1 = &aMem[pOp->p1];
  54103. pOut = &aMem[pOp->p2];
  54104. if( pIn1->flags & MEM_Null ){
  54105. sqlite3VdbeMemSetNull(pOut);
  54106. }else{
  54107. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  54108. }
  54109. break;
  54110. }
  54111. /* Opcode: Once P1 P2 * * *
  54112. **
  54113. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  54114. ** set the flag and fall through to the next instruction.
  54115. */
  54116. case OP_Once: { /* jump */
  54117. assert( pOp->p1<p->nOnceFlag );
  54118. if( p->aOnceFlag[pOp->p1] ){
  54119. pc = pOp->p2-1;
  54120. }else{
  54121. p->aOnceFlag[pOp->p1] = 1;
  54122. }
  54123. break;
  54124. }
  54125. /* Opcode: If P1 P2 P3 * *
  54126. **
  54127. ** Jump to P2 if the value in register P1 is true. The value
  54128. ** is considered true if it is numeric and non-zero. If the value
  54129. ** in P1 is NULL then take the jump if P3 is non-zero.
  54130. */
  54131. /* Opcode: IfNot P1 P2 P3 * *
  54132. **
  54133. ** Jump to P2 if the value in register P1 is False. The value
  54134. ** is considered false if it has a numeric value of zero. If the value
  54135. ** in P1 is NULL then take the jump if P3 is zero.
  54136. */
  54137. case OP_If: /* jump, in1 */
  54138. case OP_IfNot: { /* jump, in1 */
  54139. #if 0 /* local variables moved into u.an */
  54140. int c;
  54141. #endif /* local variables moved into u.an */
  54142. pIn1 = &aMem[pOp->p1];
  54143. if( pIn1->flags & MEM_Null ){
  54144. u.an.c = pOp->p3;
  54145. }else{
  54146. #ifdef SQLITE_OMIT_FLOATING_POINT
  54147. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  54148. #else
  54149. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  54150. #endif
  54151. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  54152. }
  54153. if( u.an.c ){
  54154. pc = pOp->p2-1;
  54155. }
  54156. break;
  54157. }
  54158. /* Opcode: IsNull P1 P2 * * *
  54159. **
  54160. ** Jump to P2 if the value in register P1 is NULL.
  54161. */
  54162. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  54163. pIn1 = &aMem[pOp->p1];
  54164. if( (pIn1->flags & MEM_Null)!=0 ){
  54165. pc = pOp->p2 - 1;
  54166. }
  54167. break;
  54168. }
  54169. /* Opcode: NotNull P1 P2 * * *
  54170. **
  54171. ** Jump to P2 if the value in register P1 is not NULL.
  54172. */
  54173. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  54174. pIn1 = &aMem[pOp->p1];
  54175. if( (pIn1->flags & MEM_Null)==0 ){
  54176. pc = pOp->p2 - 1;
  54177. }
  54178. break;
  54179. }
  54180. /* Opcode: Column P1 P2 P3 P4 P5
  54181. **
  54182. ** Interpret the data that cursor P1 points to as a structure built using
  54183. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  54184. ** information about the format of the data.) Extract the P2-th column
  54185. ** from this record. If there are less that (P2+1)
  54186. ** values in the record, extract a NULL.
  54187. **
  54188. ** The value extracted is stored in register P3.
  54189. **
  54190. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  54191. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  54192. ** the result.
  54193. **
  54194. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  54195. ** then the cache of the cursor is reset prior to extracting the column.
  54196. ** The first OP_Column against a pseudo-table after the value of the content
  54197. ** register has changed should have this bit set.
  54198. **
  54199. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  54200. ** the result is guaranteed to only be used as the argument of a length()
  54201. ** or typeof() function, respectively. The loading of large blobs can be
  54202. ** skipped for length() and all content loading can be skipped for typeof().
  54203. */
  54204. case OP_Column: {
  54205. #if 0 /* local variables moved into u.ao */
  54206. u32 payloadSize; /* Number of bytes in the record */
  54207. i64 payloadSize64; /* Number of bytes in the record */
  54208. int p1; /* P1 value of the opcode */
  54209. int p2; /* column number to retrieve */
  54210. VdbeCursor *pC; /* The VDBE cursor */
  54211. char *zRec; /* Pointer to complete record-data */
  54212. BtCursor *pCrsr; /* The BTree cursor */
  54213. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  54214. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  54215. int nField; /* number of fields in the record */
  54216. int len; /* The length of the serialized data for the column */
  54217. int i; /* Loop counter */
  54218. char *zData; /* Part of the record being decoded */
  54219. Mem *pDest; /* Where to write the extracted value */
  54220. Mem sMem; /* For storing the record being decoded */
  54221. u8 *zIdx; /* Index into header */
  54222. u8 *zEndHdr; /* Pointer to first byte after the header */
  54223. u32 offset; /* Offset into the data */
  54224. u32 szField; /* Number of bytes in the content of a field */
  54225. int szHdr; /* Size of the header size field at start of record */
  54226. int avail; /* Number of bytes of available data */
  54227. u32 t; /* A type code from the record header */
  54228. Mem *pReg; /* PseudoTable input register */
  54229. #endif /* local variables moved into u.ao */
  54230. u.ao.p1 = pOp->p1;
  54231. u.ao.p2 = pOp->p2;
  54232. u.ao.pC = 0;
  54233. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  54234. assert( u.ao.p1<p->nCursor );
  54235. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  54236. u.ao.pDest = &aMem[pOp->p3];
  54237. memAboutToChange(p, u.ao.pDest);
  54238. u.ao.zRec = 0;
  54239. /* This block sets the variable u.ao.payloadSize to be the total number of
  54240. ** bytes in the record.
  54241. **
  54242. ** u.ao.zRec is set to be the complete text of the record if it is available.
  54243. ** The complete record text is always available for pseudo-tables
  54244. ** If the record is stored in a cursor, the complete record text
  54245. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  54246. ** If the data is unavailable, u.ao.zRec is set to NULL.
  54247. **
  54248. ** We also compute the number of columns in the record. For cursors,
  54249. ** the number of columns is stored in the VdbeCursor.nField element.
  54250. */
  54251. u.ao.pC = p->apCsr[u.ao.p1];
  54252. assert( u.ao.pC!=0 );
  54253. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54254. assert( u.ao.pC->pVtabCursor==0 );
  54255. #endif
  54256. u.ao.pCrsr = u.ao.pC->pCursor;
  54257. if( u.ao.pCrsr!=0 ){
  54258. /* The record is stored in a B-Tree */
  54259. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  54260. if( rc ) goto abort_due_to_error;
  54261. if( u.ao.pC->nullRow ){
  54262. u.ao.payloadSize = 0;
  54263. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  54264. u.ao.payloadSize = u.ao.pC->payloadSize;
  54265. u.ao.zRec = (char*)u.ao.pC->aRow;
  54266. }else if( u.ao.pC->isIndex ){
  54267. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  54268. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  54269. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  54270. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  54271. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  54272. ** larger than 32 bits. */
  54273. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  54274. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  54275. }else{
  54276. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  54277. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  54278. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  54279. }
  54280. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  54281. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  54282. if( u.ao.pC->multiPseudo ){
  54283. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  54284. Deephemeralize(u.ao.pDest);
  54285. goto op_column_out;
  54286. }
  54287. assert( u.ao.pReg->flags & MEM_Blob );
  54288. assert( memIsValid(u.ao.pReg) );
  54289. u.ao.payloadSize = u.ao.pReg->n;
  54290. u.ao.zRec = u.ao.pReg->z;
  54291. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  54292. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  54293. }else{
  54294. /* Consider the row to be NULL */
  54295. u.ao.payloadSize = 0;
  54296. }
  54297. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  54298. ** nullRow or because of a corrupt database. */
  54299. if( u.ao.payloadSize==0 ){
  54300. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  54301. goto op_column_out;
  54302. }
  54303. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  54304. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  54305. goto too_big;
  54306. }
  54307. u.ao.nField = u.ao.pC->nField;
  54308. assert( u.ao.p2<u.ao.nField );
  54309. /* Read and parse the table header. Store the results of the parse
  54310. ** into the record header cache fields of the cursor.
  54311. */
  54312. u.ao.aType = u.ao.pC->aType;
  54313. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  54314. u.ao.aOffset = u.ao.pC->aOffset;
  54315. }else{
  54316. assert(u.ao.aType);
  54317. u.ao.avail = 0;
  54318. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  54319. u.ao.pC->payloadSize = u.ao.payloadSize;
  54320. u.ao.pC->cacheStatus = p->cacheCtr;
  54321. /* Figure out how many bytes are in the header */
  54322. if( u.ao.zRec ){
  54323. u.ao.zData = u.ao.zRec;
  54324. }else{
  54325. if( u.ao.pC->isIndex ){
  54326. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  54327. }else{
  54328. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  54329. }
  54330. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  54331. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  54332. ** having to make additional calls to fetch the content portion of
  54333. ** the record.
  54334. */
  54335. assert( u.ao.avail>=0 );
  54336. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  54337. u.ao.zRec = u.ao.zData;
  54338. u.ao.pC->aRow = (u8*)u.ao.zData;
  54339. }else{
  54340. u.ao.pC->aRow = 0;
  54341. }
  54342. }
  54343. /* The following assert is true in all cases except when
  54344. ** the database file has been corrupted externally.
  54345. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  54346. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  54347. /* Make sure a corrupt database has not given us an oversize header.
  54348. ** Do this now to avoid an oversize memory allocation.
  54349. **
  54350. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  54351. ** types use so much data space that there can only be 4096 and 32 of
  54352. ** them, respectively. So the maximum header length results from a
  54353. ** 3-byte type for each of the maximum of 32768 columns plus three
  54354. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  54355. */
  54356. if( u.ao.offset > 98307 ){
  54357. rc = SQLITE_CORRUPT_BKPT;
  54358. goto op_column_out;
  54359. }
  54360. /* Compute in u.ao.len the number of bytes of data we need to read in order
  54361. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  54362. ** u.ao.nField might be significantly less than the true number of columns
  54363. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  54364. ** We want to minimize u.ao.len in order to limit the size of the memory
  54365. ** allocation, especially if a corrupt database file has caused u.ao.offset
  54366. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  54367. ** still exceed Robson memory allocation limits on some configurations.
  54368. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  54369. ** will likely be much smaller since u.ao.nField will likely be less than
  54370. ** 20 or so. This insures that Robson memory allocation limits are
  54371. ** not exceeded even for corrupt database files.
  54372. */
  54373. u.ao.len = u.ao.nField*5 + 3;
  54374. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  54375. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  54376. ** record header in most cases. But they will fail to get the complete
  54377. ** record header if the record header does not fit on a single page
  54378. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  54379. ** acquire the complete header text.
  54380. */
  54381. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  54382. u.ao.sMem.flags = 0;
  54383. u.ao.sMem.db = 0;
  54384. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  54385. if( rc!=SQLITE_OK ){
  54386. goto op_column_out;
  54387. }
  54388. u.ao.zData = u.ao.sMem.z;
  54389. }
  54390. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  54391. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  54392. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  54393. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  54394. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  54395. ** of the record to the start of the data for the u.ao.i-th column
  54396. */
  54397. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  54398. if( u.ao.zIdx<u.ao.zEndHdr ){
  54399. u.ao.aOffset[u.ao.i] = u.ao.offset;
  54400. if( u.ao.zIdx[0]<0x80 ){
  54401. u.ao.t = u.ao.zIdx[0];
  54402. u.ao.zIdx++;
  54403. }else{
  54404. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  54405. }
  54406. u.ao.aType[u.ao.i] = u.ao.t;
  54407. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  54408. u.ao.offset += u.ao.szField;
  54409. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  54410. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  54411. break;
  54412. }
  54413. }else{
  54414. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  54415. ** record than SetNumColumns indicated there are columns in the
  54416. ** table. Set the u.ao.offset for any extra columns not present in
  54417. ** the record to 0. This tells code below to store the default value
  54418. ** for the column instead of deserializing a value from the record.
  54419. */
  54420. u.ao.aOffset[u.ao.i] = 0;
  54421. }
  54422. }
  54423. sqlite3VdbeMemRelease(&u.ao.sMem);
  54424. u.ao.sMem.flags = MEM_Null;
  54425. /* If we have read more header data than was contained in the header,
  54426. ** or if the end of the last field appears to be past the end of the
  54427. ** record, or if the end of the last field appears to be before the end
  54428. ** of the record (when all fields present), then we must be dealing
  54429. ** with a corrupt database.
  54430. */
  54431. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  54432. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  54433. rc = SQLITE_CORRUPT_BKPT;
  54434. goto op_column_out;
  54435. }
  54436. }
  54437. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  54438. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  54439. ** then there are not enough fields in the record to satisfy the
  54440. ** request. In this case, set the value NULL or to P4 if P4 is
  54441. ** a pointer to a Mem object.
  54442. */
  54443. if( u.ao.aOffset[u.ao.p2] ){
  54444. assert( rc==SQLITE_OK );
  54445. if( u.ao.zRec ){
  54446. /* This is the common case where the whole row fits on a single page */
  54447. VdbeMemRelease(u.ao.pDest);
  54448. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  54449. }else{
  54450. /* This branch happens only when the row overflows onto multiple pages */
  54451. u.ao.t = u.ao.aType[u.ao.p2];
  54452. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  54453. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  54454. ){
  54455. /* Content is irrelevant for the typeof() function and for
  54456. ** the length(X) function if X is a blob. So we might as well use
  54457. ** bogus content rather than reading content from disk. NULL works
  54458. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  54459. ** will work for everything else. */
  54460. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  54461. }else{
  54462. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  54463. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  54464. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  54465. &u.ao.sMem);
  54466. if( rc!=SQLITE_OK ){
  54467. goto op_column_out;
  54468. }
  54469. u.ao.zData = u.ao.sMem.z;
  54470. }
  54471. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  54472. }
  54473. u.ao.pDest->enc = encoding;
  54474. }else{
  54475. if( pOp->p4type==P4_MEM ){
  54476. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  54477. }else{
  54478. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  54479. }
  54480. }
  54481. /* If we dynamically allocated space to hold the data (in the
  54482. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  54483. ** dynamically allocated space over to the u.ao.pDest structure.
  54484. ** This prevents a memory copy.
  54485. */
  54486. if( u.ao.sMem.zMalloc ){
  54487. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  54488. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  54489. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  54490. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  54491. u.ao.pDest->flags |= MEM_Term;
  54492. u.ao.pDest->z = u.ao.sMem.z;
  54493. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  54494. }
  54495. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  54496. op_column_out:
  54497. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  54498. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  54499. break;
  54500. }
  54501. /* Opcode: Affinity P1 P2 * P4 *
  54502. **
  54503. ** Apply affinities to a range of P2 registers starting with P1.
  54504. **
  54505. ** P4 is a string that is P2 characters long. The nth character of the
  54506. ** string indicates the column affinity that should be used for the nth
  54507. ** memory cell in the range.
  54508. */
  54509. case OP_Affinity: {
  54510. #if 0 /* local variables moved into u.ap */
  54511. const char *zAffinity; /* The affinity to be applied */
  54512. char cAff; /* A single character of affinity */
  54513. #endif /* local variables moved into u.ap */
  54514. u.ap.zAffinity = pOp->p4.z;
  54515. assert( u.ap.zAffinity!=0 );
  54516. assert( u.ap.zAffinity[pOp->p2]==0 );
  54517. pIn1 = &aMem[pOp->p1];
  54518. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  54519. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  54520. assert( memIsValid(pIn1) );
  54521. ExpandBlob(pIn1);
  54522. applyAffinity(pIn1, u.ap.cAff, encoding);
  54523. pIn1++;
  54524. }
  54525. break;
  54526. }
  54527. /* Opcode: MakeRecord P1 P2 P3 P4 *
  54528. **
  54529. ** Convert P2 registers beginning with P1 into the [record format]
  54530. ** use as a data record in a database table or as a key
  54531. ** in an index. The OP_Column opcode can decode the record later.
  54532. **
  54533. ** P4 may be a string that is P2 characters long. The nth character of the
  54534. ** string indicates the column affinity that should be used for the nth
  54535. ** field of the index key.
  54536. **
  54537. ** The mapping from character to affinity is given by the SQLITE_AFF_
  54538. ** macros defined in sqliteInt.h.
  54539. **
  54540. ** If P4 is NULL then all index fields have the affinity NONE.
  54541. */
  54542. case OP_MakeRecord: {
  54543. #if 0 /* local variables moved into u.aq */
  54544. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  54545. Mem *pRec; /* The new record */
  54546. u64 nData; /* Number of bytes of data space */
  54547. int nHdr; /* Number of bytes of header space */
  54548. i64 nByte; /* Data space required for this record */
  54549. int nZero; /* Number of zero bytes at the end of the record */
  54550. int nVarint; /* Number of bytes in a varint */
  54551. u32 serial_type; /* Type field */
  54552. Mem *pData0; /* First field to be combined into the record */
  54553. Mem *pLast; /* Last field of the record */
  54554. int nField; /* Number of fields in the record */
  54555. char *zAffinity; /* The affinity string for the record */
  54556. int file_format; /* File format to use for encoding */
  54557. int i; /* Space used in zNewRecord[] */
  54558. int len; /* Length of a field */
  54559. #endif /* local variables moved into u.aq */
  54560. /* Assuming the record contains N fields, the record format looks
  54561. ** like this:
  54562. **
  54563. ** ------------------------------------------------------------------------
  54564. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  54565. ** ------------------------------------------------------------------------
  54566. **
  54567. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  54568. ** and so froth.
  54569. **
  54570. ** Each type field is a varint representing the serial type of the
  54571. ** corresponding data element (see sqlite3VdbeSerialType()). The
  54572. ** hdr-size field is also a varint which is the offset from the beginning
  54573. ** of the record to data0.
  54574. */
  54575. u.aq.nData = 0; /* Number of bytes of data space */
  54576. u.aq.nHdr = 0; /* Number of bytes of header space */
  54577. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  54578. u.aq.nField = pOp->p1;
  54579. u.aq.zAffinity = pOp->p4.z;
  54580. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 );
  54581. u.aq.pData0 = &aMem[u.aq.nField];
  54582. u.aq.nField = pOp->p2;
  54583. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  54584. u.aq.file_format = p->minWriteFileFormat;
  54585. /* Identify the output register */
  54586. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  54587. pOut = &aMem[pOp->p3];
  54588. memAboutToChange(p, pOut);
  54589. /* Loop through the elements that will make up the record to figure
  54590. ** out how much space is required for the new record.
  54591. */
  54592. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  54593. assert( memIsValid(u.aq.pRec) );
  54594. if( u.aq.zAffinity ){
  54595. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  54596. }
  54597. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  54598. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  54599. }
  54600. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  54601. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  54602. u.aq.nData += u.aq.len;
  54603. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  54604. if( u.aq.pRec->flags & MEM_Zero ){
  54605. /* Only pure zero-filled BLOBs can be input to this Opcode.
  54606. ** We do not allow blobs with a prefix and a zero-filled tail. */
  54607. u.aq.nZero += u.aq.pRec->u.nZero;
  54608. }else if( u.aq.len ){
  54609. u.aq.nZero = 0;
  54610. }
  54611. }
  54612. /* Add the initial header varint and total the size */
  54613. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  54614. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  54615. u.aq.nHdr++;
  54616. }
  54617. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  54618. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  54619. goto too_big;
  54620. }
  54621. /* Make sure the output register has a buffer large enough to store
  54622. ** the new record. The output register (pOp->p3) is not allowed to
  54623. ** be one of the input registers (because the following call to
  54624. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  54625. */
  54626. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  54627. goto no_mem;
  54628. }
  54629. u.aq.zNewRecord = (u8 *)pOut->z;
  54630. /* Write the record */
  54631. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  54632. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  54633. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  54634. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  54635. }
  54636. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  54637. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  54638. }
  54639. assert( u.aq.i==u.aq.nByte );
  54640. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  54641. pOut->n = (int)u.aq.nByte;
  54642. pOut->flags = MEM_Blob | MEM_Dyn;
  54643. pOut->xDel = 0;
  54644. if( u.aq.nZero ){
  54645. pOut->u.nZero = u.aq.nZero;
  54646. pOut->flags |= MEM_Zero;
  54647. }
  54648. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  54649. REGISTER_TRACE(pOp->p3, pOut);
  54650. UPDATE_MAX_BLOBSIZE(pOut);
  54651. break;
  54652. }
  54653. /* Opcode: Count P1 P2 * * *
  54654. **
  54655. ** Store the number of entries (an integer value) in the table or index
  54656. ** opened by cursor P1 in register P2
  54657. */
  54658. #ifndef SQLITE_OMIT_BTREECOUNT
  54659. case OP_Count: { /* out2-prerelease */
  54660. #if 0 /* local variables moved into u.ar */
  54661. i64 nEntry;
  54662. BtCursor *pCrsr;
  54663. #endif /* local variables moved into u.ar */
  54664. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  54665. if( ALWAYS(u.ar.pCrsr) ){
  54666. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  54667. }else{
  54668. u.ar.nEntry = 0;
  54669. }
  54670. pOut->u.i = u.ar.nEntry;
  54671. break;
  54672. }
  54673. #endif
  54674. /* Opcode: Savepoint P1 * * P4 *
  54675. **
  54676. ** Open, release or rollback the savepoint named by parameter P4, depending
  54677. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  54678. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  54679. */
  54680. case OP_Savepoint: {
  54681. #if 0 /* local variables moved into u.as */
  54682. int p1; /* Value of P1 operand */
  54683. char *zName; /* Name of savepoint */
  54684. int nName;
  54685. Savepoint *pNew;
  54686. Savepoint *pSavepoint;
  54687. Savepoint *pTmp;
  54688. int iSavepoint;
  54689. int ii;
  54690. #endif /* local variables moved into u.as */
  54691. u.as.p1 = pOp->p1;
  54692. u.as.zName = pOp->p4.z;
  54693. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  54694. ** transaction, then there cannot be any savepoints.
  54695. */
  54696. assert( db->pSavepoint==0 || db->autoCommit==0 );
  54697. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  54698. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  54699. assert( checkSavepointCount(db) );
  54700. assert( p->bIsReader );
  54701. if( u.as.p1==SAVEPOINT_BEGIN ){
  54702. if( db->nVdbeWrite>0 ){
  54703. /* A new savepoint cannot be created if there are active write
  54704. ** statements (i.e. open read/write incremental blob handles).
  54705. */
  54706. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  54707. "SQL statements in progress");
  54708. rc = SQLITE_BUSY;
  54709. }else{
  54710. u.as.nName = sqlite3Strlen30(u.as.zName);
  54711. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54712. /* This call is Ok even if this savepoint is actually a transaction
  54713. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  54714. ** If this is a transaction savepoint being opened, it is guaranteed
  54715. ** that the db->aVTrans[] array is empty. */
  54716. assert( db->autoCommit==0 || db->nVTrans==0 );
  54717. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  54718. db->nStatement+db->nSavepoint);
  54719. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  54720. #endif
  54721. /* Create a new savepoint structure. */
  54722. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  54723. if( u.as.pNew ){
  54724. u.as.pNew->zName = (char *)&u.as.pNew[1];
  54725. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  54726. /* If there is no open transaction, then mark this as a special
  54727. ** "transaction savepoint". */
  54728. if( db->autoCommit ){
  54729. db->autoCommit = 0;
  54730. db->isTransactionSavepoint = 1;
  54731. }else{
  54732. db->nSavepoint++;
  54733. }
  54734. /* Link the new savepoint into the database handle's list. */
  54735. u.as.pNew->pNext = db->pSavepoint;
  54736. db->pSavepoint = u.as.pNew;
  54737. u.as.pNew->nDeferredCons = db->nDeferredCons;
  54738. u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
  54739. }
  54740. }
  54741. }else{
  54742. u.as.iSavepoint = 0;
  54743. /* Find the named savepoint. If there is no such savepoint, then an
  54744. ** an error is returned to the user. */
  54745. for(
  54746. u.as.pSavepoint = db->pSavepoint;
  54747. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  54748. u.as.pSavepoint = u.as.pSavepoint->pNext
  54749. ){
  54750. u.as.iSavepoint++;
  54751. }
  54752. if( !u.as.pSavepoint ){
  54753. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  54754. rc = SQLITE_ERROR;
  54755. }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
  54756. /* It is not possible to release (commit) a savepoint if there are
  54757. ** active write statements.
  54758. */
  54759. sqlite3SetString(&p->zErrMsg, db,
  54760. "cannot release savepoint - SQL statements in progress"
  54761. );
  54762. rc = SQLITE_BUSY;
  54763. }else{
  54764. /* Determine whether or not this is a transaction savepoint. If so,
  54765. ** and this is a RELEASE command, then the current transaction
  54766. ** is committed.
  54767. */
  54768. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  54769. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  54770. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  54771. goto vdbe_return;
  54772. }
  54773. db->autoCommit = 1;
  54774. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  54775. p->pc = pc;
  54776. db->autoCommit = 0;
  54777. p->rc = rc = SQLITE_BUSY;
  54778. goto vdbe_return;
  54779. }
  54780. db->isTransactionSavepoint = 0;
  54781. rc = p->rc;
  54782. }else{
  54783. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  54784. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  54785. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  54786. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  54787. }
  54788. }
  54789. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  54790. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  54791. if( rc!=SQLITE_OK ){
  54792. goto abort_due_to_error;
  54793. }
  54794. }
  54795. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  54796. sqlite3ExpirePreparedStatements(db);
  54797. sqlite3ResetAllSchemasOfConnection(db);
  54798. db->flags = (db->flags | SQLITE_InternChanges);
  54799. }
  54800. }
  54801. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  54802. ** savepoints nested inside of the savepoint being operated on. */
  54803. while( db->pSavepoint!=u.as.pSavepoint ){
  54804. u.as.pTmp = db->pSavepoint;
  54805. db->pSavepoint = u.as.pTmp->pNext;
  54806. sqlite3DbFree(db, u.as.pTmp);
  54807. db->nSavepoint--;
  54808. }
  54809. /* If it is a RELEASE, then destroy the savepoint being operated on
  54810. ** too. If it is a ROLLBACK TO, then set the number of deferred
  54811. ** constraint violations present in the database to the value stored
  54812. ** when the savepoint was created. */
  54813. if( u.as.p1==SAVEPOINT_RELEASE ){
  54814. assert( u.as.pSavepoint==db->pSavepoint );
  54815. db->pSavepoint = u.as.pSavepoint->pNext;
  54816. sqlite3DbFree(db, u.as.pSavepoint);
  54817. if( !isTransaction ){
  54818. db->nSavepoint--;
  54819. }
  54820. }else{
  54821. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  54822. db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
  54823. }
  54824. if( !isTransaction ){
  54825. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  54826. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  54827. }
  54828. }
  54829. }
  54830. break;
  54831. }
  54832. /* Opcode: AutoCommit P1 P2 * * *
  54833. **
  54834. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  54835. ** back any currently active btree transactions. If there are any active
  54836. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  54837. ** there are active writing VMs or active VMs that use shared cache.
  54838. **
  54839. ** This instruction causes the VM to halt.
  54840. */
  54841. case OP_AutoCommit: {
  54842. #if 0 /* local variables moved into u.at */
  54843. int desiredAutoCommit;
  54844. int iRollback;
  54845. int turnOnAC;
  54846. #endif /* local variables moved into u.at */
  54847. u.at.desiredAutoCommit = pOp->p1;
  54848. u.at.iRollback = pOp->p2;
  54849. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  54850. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  54851. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  54852. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  54853. assert( p->bIsReader );
  54854. #if 0
  54855. if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
  54856. /* If this instruction implements a ROLLBACK and other VMs are
  54857. ** still running, and a transaction is active, return an error indicating
  54858. ** that the other VMs must complete first.
  54859. */
  54860. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  54861. "SQL statements in progress");
  54862. rc = SQLITE_BUSY;
  54863. }else
  54864. #endif
  54865. if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
  54866. /* If this instruction implements a COMMIT and other VMs are writing
  54867. ** return an error indicating that the other VMs must complete first.
  54868. */
  54869. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  54870. "SQL statements in progress");
  54871. rc = SQLITE_BUSY;
  54872. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  54873. if( u.at.iRollback ){
  54874. assert( u.at.desiredAutoCommit==1 );
  54875. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  54876. db->autoCommit = 1;
  54877. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  54878. goto vdbe_return;
  54879. }else{
  54880. db->autoCommit = (u8)u.at.desiredAutoCommit;
  54881. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  54882. p->pc = pc;
  54883. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  54884. p->rc = rc = SQLITE_BUSY;
  54885. goto vdbe_return;
  54886. }
  54887. }
  54888. assert( db->nStatement==0 );
  54889. sqlite3CloseSavepoints(db);
  54890. if( p->rc==SQLITE_OK ){
  54891. rc = SQLITE_DONE;
  54892. }else{
  54893. rc = SQLITE_ERROR;
  54894. }
  54895. goto vdbe_return;
  54896. }else{
  54897. sqlite3SetString(&p->zErrMsg, db,
  54898. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  54899. (u.at.iRollback)?"cannot rollback - no transaction is active":
  54900. "cannot commit - no transaction is active"));
  54901. rc = SQLITE_ERROR;
  54902. }
  54903. break;
  54904. }
  54905. /* Opcode: Transaction P1 P2 * * *
  54906. **
  54907. ** Begin a transaction. The transaction ends when a Commit or Rollback
  54908. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  54909. ** transaction might also be rolled back if an error is encountered.
  54910. **
  54911. ** P1 is the index of the database file on which the transaction is
  54912. ** started. Index 0 is the main database file and index 1 is the
  54913. ** file used for temporary tables. Indices of 2 or more are used for
  54914. ** attached databases.
  54915. **
  54916. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  54917. ** obtained on the database file when a write-transaction is started. No
  54918. ** other process can start another write transaction while this transaction is
  54919. ** underway. Starting a write transaction also creates a rollback journal. A
  54920. ** write transaction must be started before any changes can be made to the
  54921. ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  54922. ** also obtained on the file.
  54923. **
  54924. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  54925. ** true (this flag is set if the Vdbe may modify more than one row and may
  54926. ** throw an ABORT exception), a statement transaction may also be opened.
  54927. ** More specifically, a statement transaction is opened iff the database
  54928. ** connection is currently not in autocommit mode, or if there are other
  54929. ** active statements. A statement transaction allows the changes made by this
  54930. ** VDBE to be rolled back after an error without having to roll back the
  54931. ** entire transaction. If no error is encountered, the statement transaction
  54932. ** will automatically commit when the VDBE halts.
  54933. **
  54934. ** If P2 is zero, then a read-lock is obtained on the database file.
  54935. */
  54936. case OP_Transaction: {
  54937. #if 0 /* local variables moved into u.au */
  54938. Btree *pBt;
  54939. #endif /* local variables moved into u.au */
  54940. assert( p->bIsReader );
  54941. assert( p->readOnly==0 || pOp->p2==0 );
  54942. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  54943. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  54944. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  54945. rc = SQLITE_READONLY;
  54946. goto abort_due_to_error;
  54947. }
  54948. u.au.pBt = db->aDb[pOp->p1].pBt;
  54949. if( u.au.pBt ){
  54950. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  54951. if( rc==SQLITE_BUSY ){
  54952. p->pc = pc;
  54953. p->rc = rc = SQLITE_BUSY;
  54954. goto vdbe_return;
  54955. }
  54956. if( rc!=SQLITE_OK ){
  54957. goto abort_due_to_error;
  54958. }
  54959. if( pOp->p2 && p->usesStmtJournal
  54960. && (db->autoCommit==0 || db->nVdbeRead>1)
  54961. ){
  54962. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  54963. if( p->iStatement==0 ){
  54964. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  54965. db->nStatement++;
  54966. p->iStatement = db->nSavepoint + db->nStatement;
  54967. }
  54968. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  54969. if( rc==SQLITE_OK ){
  54970. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  54971. }
  54972. /* Store the current value of the database handles deferred constraint
  54973. ** counter. If the statement transaction needs to be rolled back,
  54974. ** the value of this counter needs to be restored too. */
  54975. p->nStmtDefCons = db->nDeferredCons;
  54976. p->nStmtDefImmCons = db->nDeferredImmCons;
  54977. }
  54978. }
  54979. break;
  54980. }
  54981. /* Opcode: ReadCookie P1 P2 P3 * *
  54982. **
  54983. ** Read cookie number P3 from database P1 and write it into register P2.
  54984. ** P3==1 is the schema version. P3==2 is the database format.
  54985. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  54986. ** the main database file and P1==1 is the database file used to store
  54987. ** temporary tables.
  54988. **
  54989. ** There must be a read-lock on the database (either a transaction
  54990. ** must be started or there must be an open cursor) before
  54991. ** executing this instruction.
  54992. */
  54993. case OP_ReadCookie: { /* out2-prerelease */
  54994. #if 0 /* local variables moved into u.av */
  54995. int iMeta;
  54996. int iDb;
  54997. int iCookie;
  54998. #endif /* local variables moved into u.av */
  54999. assert( p->bIsReader );
  55000. u.av.iDb = pOp->p1;
  55001. u.av.iCookie = pOp->p3;
  55002. assert( pOp->p3<SQLITE_N_BTREE_META );
  55003. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  55004. assert( db->aDb[u.av.iDb].pBt!=0 );
  55005. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  55006. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  55007. pOut->u.i = u.av.iMeta;
  55008. break;
  55009. }
  55010. /* Opcode: SetCookie P1 P2 P3 * *
  55011. **
  55012. ** Write the content of register P3 (interpreted as an integer)
  55013. ** into cookie number P2 of database P1. P2==1 is the schema version.
  55014. ** P2==2 is the database format. P2==3 is the recommended pager cache
  55015. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  55016. ** database file used to store temporary tables.
  55017. **
  55018. ** A transaction must be started before executing this opcode.
  55019. */
  55020. case OP_SetCookie: { /* in3 */
  55021. #if 0 /* local variables moved into u.aw */
  55022. Db *pDb;
  55023. #endif /* local variables moved into u.aw */
  55024. assert( pOp->p2<SQLITE_N_BTREE_META );
  55025. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  55026. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  55027. assert( p->readOnly==0 );
  55028. u.aw.pDb = &db->aDb[pOp->p1];
  55029. assert( u.aw.pDb->pBt!=0 );
  55030. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  55031. pIn3 = &aMem[pOp->p3];
  55032. sqlite3VdbeMemIntegerify(pIn3);
  55033. /* See note about index shifting on OP_ReadCookie */
  55034. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  55035. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  55036. /* When the schema cookie changes, record the new cookie internally */
  55037. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  55038. db->flags |= SQLITE_InternChanges;
  55039. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  55040. /* Record changes in the file format */
  55041. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  55042. }
  55043. if( pOp->p1==1 ){
  55044. /* Invalidate all prepared statements whenever the TEMP database
  55045. ** schema is changed. Ticket #1644 */
  55046. sqlite3ExpirePreparedStatements(db);
  55047. p->expired = 0;
  55048. }
  55049. break;
  55050. }
  55051. /* Opcode: VerifyCookie P1 P2 P3 * *
  55052. **
  55053. ** Check the value of global database parameter number 0 (the
  55054. ** schema version) and make sure it is equal to P2 and that the
  55055. ** generation counter on the local schema parse equals P3.
  55056. **
  55057. ** P1 is the database number which is 0 for the main database file
  55058. ** and 1 for the file holding temporary tables and some higher number
  55059. ** for auxiliary databases.
  55060. **
  55061. ** The cookie changes its value whenever the database schema changes.
  55062. ** This operation is used to detect when that the cookie has changed
  55063. ** and that the current process needs to reread the schema.
  55064. **
  55065. ** Either a transaction needs to have been started or an OP_Open needs
  55066. ** to be executed (to establish a read lock) before this opcode is
  55067. ** invoked.
  55068. */
  55069. case OP_VerifyCookie: {
  55070. #if 0 /* local variables moved into u.ax */
  55071. int iMeta;
  55072. int iGen;
  55073. Btree *pBt;
  55074. #endif /* local variables moved into u.ax */
  55075. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  55076. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  55077. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  55078. assert( p->bIsReader );
  55079. u.ax.pBt = db->aDb[pOp->p1].pBt;
  55080. if( u.ax.pBt ){
  55081. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  55082. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  55083. }else{
  55084. u.ax.iGen = u.ax.iMeta = 0;
  55085. }
  55086. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  55087. sqlite3DbFree(db, p->zErrMsg);
  55088. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  55089. /* If the schema-cookie from the database file matches the cookie
  55090. ** stored with the in-memory representation of the schema, do
  55091. ** not reload the schema from the database file.
  55092. **
  55093. ** If virtual-tables are in use, this is not just an optimization.
  55094. ** Often, v-tables store their data in other SQLite tables, which
  55095. ** are queried from within xNext() and other v-table methods using
  55096. ** prepared queries. If such a query is out-of-date, we do not want to
  55097. ** discard the database schema, as the user code implementing the
  55098. ** v-table would have to be ready for the sqlite3_vtab structure itself
  55099. ** to be invalidated whenever sqlite3_step() is called from within
  55100. ** a v-table method.
  55101. */
  55102. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  55103. sqlite3ResetOneSchema(db, pOp->p1);
  55104. }
  55105. p->expired = 1;
  55106. rc = SQLITE_SCHEMA;
  55107. }
  55108. break;
  55109. }
  55110. /* Opcode: OpenRead P1 P2 P3 P4 P5
  55111. **
  55112. ** Open a read-only cursor for the database table whose root page is
  55113. ** P2 in a database file. The database file is determined by P3.
  55114. ** P3==0 means the main database, P3==1 means the database used for
  55115. ** temporary tables, and P3>1 means used the corresponding attached
  55116. ** database. Give the new cursor an identifier of P1. The P1
  55117. ** values need not be contiguous but all P1 values should be small integers.
  55118. ** It is an error for P1 to be negative.
  55119. **
  55120. ** If P5!=0 then use the content of register P2 as the root page, not
  55121. ** the value of P2 itself.
  55122. **
  55123. ** There will be a read lock on the database whenever there is an
  55124. ** open cursor. If the database was unlocked prior to this instruction
  55125. ** then a read lock is acquired as part of this instruction. A read
  55126. ** lock allows other processes to read the database but prohibits
  55127. ** any other process from modifying the database. The read lock is
  55128. ** released when all cursors are closed. If this instruction attempts
  55129. ** to get a read lock but fails, the script terminates with an
  55130. ** SQLITE_BUSY error code.
  55131. **
  55132. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  55133. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  55134. ** structure, then said structure defines the content and collating
  55135. ** sequence of the index being opened. Otherwise, if P4 is an integer
  55136. ** value, it is set to the number of columns in the table.
  55137. **
  55138. ** See also OpenWrite.
  55139. */
  55140. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  55141. **
  55142. ** Open a read/write cursor named P1 on the table or index whose root
  55143. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  55144. ** root page.
  55145. **
  55146. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  55147. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  55148. ** structure, then said structure defines the content and collating
  55149. ** sequence of the index being opened. Otherwise, if P4 is an integer
  55150. ** value, it is set to the number of columns in the table, or to the
  55151. ** largest index of any column of the table that is actually used.
  55152. **
  55153. ** This instruction works just like OpenRead except that it opens the cursor
  55154. ** in read/write mode. For a given table, there can be one or more read-only
  55155. ** cursors or a single read/write cursor but not both.
  55156. **
  55157. ** See also OpenRead.
  55158. */
  55159. case OP_OpenRead:
  55160. case OP_OpenWrite: {
  55161. #if 0 /* local variables moved into u.ay */
  55162. int nField;
  55163. KeyInfo *pKeyInfo;
  55164. int p2;
  55165. int iDb;
  55166. int wrFlag;
  55167. Btree *pX;
  55168. VdbeCursor *pCur;
  55169. Db *pDb;
  55170. #endif /* local variables moved into u.ay */
  55171. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  55172. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  55173. assert( p->bIsReader );
  55174. assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
  55175. if( p->expired ){
  55176. rc = SQLITE_ABORT;
  55177. break;
  55178. }
  55179. u.ay.nField = 0;
  55180. u.ay.pKeyInfo = 0;
  55181. u.ay.p2 = pOp->p2;
  55182. u.ay.iDb = pOp->p3;
  55183. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  55184. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  55185. u.ay.pDb = &db->aDb[u.ay.iDb];
  55186. u.ay.pX = u.ay.pDb->pBt;
  55187. assert( u.ay.pX!=0 );
  55188. if( pOp->opcode==OP_OpenWrite ){
  55189. u.ay.wrFlag = 1;
  55190. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  55191. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  55192. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  55193. }
  55194. }else{
  55195. u.ay.wrFlag = 0;
  55196. }
  55197. if( pOp->p5 & OPFLAG_P2ISREG ){
  55198. assert( u.ay.p2>0 );
  55199. assert( u.ay.p2<=(p->nMem-p->nCursor) );
  55200. pIn2 = &aMem[u.ay.p2];
  55201. assert( memIsValid(pIn2) );
  55202. assert( (pIn2->flags & MEM_Int)!=0 );
  55203. sqlite3VdbeMemIntegerify(pIn2);
  55204. u.ay.p2 = (int)pIn2->u.i;
  55205. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  55206. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  55207. ** If there were a failure, the prepared statement would have halted
  55208. ** before reaching this instruction. */
  55209. if( NEVER(u.ay.p2<2) ) {
  55210. rc = SQLITE_CORRUPT_BKPT;
  55211. goto abort_due_to_error;
  55212. }
  55213. }
  55214. if( pOp->p4type==P4_KEYINFO ){
  55215. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  55216. u.ay.pKeyInfo->enc = ENC(p->db);
  55217. u.ay.nField = u.ay.pKeyInfo->nField+1;
  55218. }else if( pOp->p4type==P4_INT32 ){
  55219. u.ay.nField = pOp->p4.i;
  55220. }
  55221. assert( pOp->p1>=0 );
  55222. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  55223. if( u.ay.pCur==0 ) goto no_mem;
  55224. u.ay.pCur->nullRow = 1;
  55225. u.ay.pCur->isOrdered = 1;
  55226. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  55227. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  55228. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  55229. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  55230. /* Since it performs no memory allocation or IO, the only value that
  55231. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  55232. assert( rc==SQLITE_OK );
  55233. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  55234. ** SQLite used to check if the root-page flags were sane at this point
  55235. ** and report database corruption if they were not, but this check has
  55236. ** since moved into the btree layer. */
  55237. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  55238. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  55239. break;
  55240. }
  55241. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  55242. **
  55243. ** Open a new cursor P1 to a transient table.
  55244. ** The cursor is always opened read/write even if
  55245. ** the main database is read-only. The ephemeral
  55246. ** table is deleted automatically when the cursor is closed.
  55247. **
  55248. ** P2 is the number of columns in the ephemeral table.
  55249. ** The cursor points to a BTree table if P4==0 and to a BTree index
  55250. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  55251. ** that defines the format of keys in the index.
  55252. **
  55253. ** This opcode was once called OpenTemp. But that created
  55254. ** confusion because the term "temp table", might refer either
  55255. ** to a TEMP table at the SQL level, or to a table opened by
  55256. ** this opcode. Then this opcode was call OpenVirtual. But
  55257. ** that created confusion with the whole virtual-table idea.
  55258. **
  55259. ** The P5 parameter can be a mask of the BTREE_* flags defined
  55260. ** in btree.h. These flags control aspects of the operation of
  55261. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  55262. ** added automatically.
  55263. */
  55264. /* Opcode: OpenAutoindex P1 P2 * P4 *
  55265. **
  55266. ** This opcode works the same as OP_OpenEphemeral. It has a
  55267. ** different name to distinguish its use. Tables created using
  55268. ** by this opcode will be used for automatically created transient
  55269. ** indices in joins.
  55270. */
  55271. case OP_OpenAutoindex:
  55272. case OP_OpenEphemeral: {
  55273. #if 0 /* local variables moved into u.az */
  55274. VdbeCursor *pCx;
  55275. #endif /* local variables moved into u.az */
  55276. static const int vfsFlags =
  55277. SQLITE_OPEN_READWRITE |
  55278. SQLITE_OPEN_CREATE |
  55279. SQLITE_OPEN_EXCLUSIVE |
  55280. SQLITE_OPEN_DELETEONCLOSE |
  55281. SQLITE_OPEN_TRANSIENT_DB;
  55282. assert( pOp->p1>=0 );
  55283. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  55284. if( u.az.pCx==0 ) goto no_mem;
  55285. u.az.pCx->nullRow = 1;
  55286. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  55287. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  55288. if( rc==SQLITE_OK ){
  55289. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  55290. }
  55291. if( rc==SQLITE_OK ){
  55292. /* If a transient index is required, create it by calling
  55293. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  55294. ** opening it. If a transient table is required, just use the
  55295. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  55296. */
  55297. if( pOp->p4.pKeyInfo ){
  55298. int pgno;
  55299. assert( pOp->p4type==P4_KEYINFO );
  55300. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  55301. if( rc==SQLITE_OK ){
  55302. assert( pgno==MASTER_ROOT+1 );
  55303. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  55304. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  55305. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  55306. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  55307. }
  55308. u.az.pCx->isTable = 0;
  55309. }else{
  55310. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  55311. u.az.pCx->isTable = 1;
  55312. }
  55313. }
  55314. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  55315. u.az.pCx->isIndex = !u.az.pCx->isTable;
  55316. break;
  55317. }
  55318. /* Opcode: SorterOpen P1 P2 * P4 *
  55319. **
  55320. ** This opcode works like OP_OpenEphemeral except that it opens
  55321. ** a transient index that is specifically designed to sort large
  55322. ** tables using an external merge-sort algorithm.
  55323. */
  55324. case OP_SorterOpen: {
  55325. #if 0 /* local variables moved into u.ba */
  55326. VdbeCursor *pCx;
  55327. #endif /* local variables moved into u.ba */
  55328. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  55329. if( u.ba.pCx==0 ) goto no_mem;
  55330. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  55331. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  55332. u.ba.pCx->isSorter = 1;
  55333. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  55334. break;
  55335. }
  55336. /* Opcode: OpenPseudo P1 P2 P3 * P5
  55337. **
  55338. ** Open a new cursor that points to a fake table that contains a single
  55339. ** row of data. The content of that one row in the content of memory
  55340. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  55341. ** MEM_Blob content contained in register P2. When P5==1, then the
  55342. ** row is represented by P3 consecutive registers beginning with P2.
  55343. **
  55344. ** A pseudo-table created by this opcode is used to hold a single
  55345. ** row output from the sorter so that the row can be decomposed into
  55346. ** individual columns using the OP_Column opcode. The OP_Column opcode
  55347. ** is the only cursor opcode that works with a pseudo-table.
  55348. **
  55349. ** P3 is the number of fields in the records that will be stored by
  55350. ** the pseudo-table.
  55351. */
  55352. case OP_OpenPseudo: {
  55353. #if 0 /* local variables moved into u.bb */
  55354. VdbeCursor *pCx;
  55355. #endif /* local variables moved into u.bb */
  55356. assert( pOp->p1>=0 );
  55357. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  55358. if( u.bb.pCx==0 ) goto no_mem;
  55359. u.bb.pCx->nullRow = 1;
  55360. u.bb.pCx->pseudoTableReg = pOp->p2;
  55361. u.bb.pCx->isTable = 1;
  55362. u.bb.pCx->isIndex = 0;
  55363. u.bb.pCx->multiPseudo = pOp->p5;
  55364. break;
  55365. }
  55366. /* Opcode: Close P1 * * * *
  55367. **
  55368. ** Close a cursor previously opened as P1. If P1 is not
  55369. ** currently open, this instruction is a no-op.
  55370. */
  55371. case OP_Close: {
  55372. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55373. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  55374. p->apCsr[pOp->p1] = 0;
  55375. break;
  55376. }
  55377. /* Opcode: SeekGe P1 P2 P3 P4 *
  55378. **
  55379. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55380. ** use the value in register P3 as the key. If cursor P1 refers
  55381. ** to an SQL index, then P3 is the first in an array of P4 registers
  55382. ** that are used as an unpacked index key.
  55383. **
  55384. ** Reposition cursor P1 so that it points to the smallest entry that
  55385. ** is greater than or equal to the key value. If there are no records
  55386. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  55387. **
  55388. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  55389. */
  55390. /* Opcode: SeekGt P1 P2 P3 P4 *
  55391. **
  55392. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55393. ** use the value in register P3 as a key. If cursor P1 refers
  55394. ** to an SQL index, then P3 is the first in an array of P4 registers
  55395. ** that are used as an unpacked index key.
  55396. **
  55397. ** Reposition cursor P1 so that it points to the smallest entry that
  55398. ** is greater than the key value. If there are no records greater than
  55399. ** the key and P2 is not zero, then jump to P2.
  55400. **
  55401. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  55402. */
  55403. /* Opcode: SeekLt P1 P2 P3 P4 *
  55404. **
  55405. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55406. ** use the value in register P3 as a key. If cursor P1 refers
  55407. ** to an SQL index, then P3 is the first in an array of P4 registers
  55408. ** that are used as an unpacked index key.
  55409. **
  55410. ** Reposition cursor P1 so that it points to the largest entry that
  55411. ** is less than the key value. If there are no records less than
  55412. ** the key and P2 is not zero, then jump to P2.
  55413. **
  55414. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  55415. */
  55416. /* Opcode: SeekLe P1 P2 P3 P4 *
  55417. **
  55418. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  55419. ** use the value in register P3 as a key. If cursor P1 refers
  55420. ** to an SQL index, then P3 is the first in an array of P4 registers
  55421. ** that are used as an unpacked index key.
  55422. **
  55423. ** Reposition cursor P1 so that it points to the largest entry that
  55424. ** is less than or equal to the key value. If there are no records
  55425. ** less than or equal to the key and P2 is not zero, then jump to P2.
  55426. **
  55427. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  55428. */
  55429. case OP_SeekLt: /* jump, in3 */
  55430. case OP_SeekLe: /* jump, in3 */
  55431. case OP_SeekGe: /* jump, in3 */
  55432. case OP_SeekGt: { /* jump, in3 */
  55433. #if 0 /* local variables moved into u.bc */
  55434. int res;
  55435. int oc;
  55436. VdbeCursor *pC;
  55437. UnpackedRecord r;
  55438. int nField;
  55439. i64 iKey; /* The rowid we are to seek to */
  55440. #endif /* local variables moved into u.bc */
  55441. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55442. assert( pOp->p2!=0 );
  55443. u.bc.pC = p->apCsr[pOp->p1];
  55444. assert( u.bc.pC!=0 );
  55445. assert( u.bc.pC->pseudoTableReg==0 );
  55446. assert( OP_SeekLe == OP_SeekLt+1 );
  55447. assert( OP_SeekGe == OP_SeekLt+2 );
  55448. assert( OP_SeekGt == OP_SeekLt+3 );
  55449. assert( u.bc.pC->isOrdered );
  55450. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  55451. u.bc.oc = pOp->opcode;
  55452. u.bc.pC->nullRow = 0;
  55453. if( u.bc.pC->isTable ){
  55454. /* The input value in P3 might be of any type: integer, real, string,
  55455. ** blob, or NULL. But it needs to be an integer before we can do
  55456. ** the seek, so covert it. */
  55457. pIn3 = &aMem[pOp->p3];
  55458. applyNumericAffinity(pIn3);
  55459. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  55460. u.bc.pC->rowidIsValid = 0;
  55461. /* If the P3 value could not be converted into an integer without
  55462. ** loss of information, then special processing is required... */
  55463. if( (pIn3->flags & MEM_Int)==0 ){
  55464. if( (pIn3->flags & MEM_Real)==0 ){
  55465. /* If the P3 value cannot be converted into any kind of a number,
  55466. ** then the seek is not possible, so jump to P2 */
  55467. pc = pOp->p2 - 1;
  55468. break;
  55469. }
  55470. /* If we reach this point, then the P3 value must be a floating
  55471. ** point number. */
  55472. assert( (pIn3->flags & MEM_Real)!=0 );
  55473. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  55474. /* The P3 value is too large in magnitude to be expressed as an
  55475. ** integer. */
  55476. u.bc.res = 1;
  55477. if( pIn3->r<0 ){
  55478. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  55479. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  55480. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55481. }
  55482. }else{
  55483. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  55484. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  55485. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55486. }
  55487. }
  55488. if( u.bc.res ){
  55489. pc = pOp->p2 - 1;
  55490. }
  55491. break;
  55492. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  55493. /* Use the ceiling() function to convert real->int */
  55494. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  55495. }else{
  55496. /* Use the floor() function to convert real->int */
  55497. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  55498. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  55499. }
  55500. }
  55501. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  55502. if( rc!=SQLITE_OK ){
  55503. goto abort_due_to_error;
  55504. }
  55505. if( u.bc.res==0 ){
  55506. u.bc.pC->rowidIsValid = 1;
  55507. u.bc.pC->lastRowid = u.bc.iKey;
  55508. }
  55509. }else{
  55510. u.bc.nField = pOp->p4.i;
  55511. assert( pOp->p4type==P4_INT32 );
  55512. assert( u.bc.nField>0 );
  55513. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  55514. u.bc.r.nField = (u16)u.bc.nField;
  55515. /* The next line of code computes as follows, only faster:
  55516. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  55517. ** u.bc.r.flags = UNPACKED_INCRKEY;
  55518. ** }else{
  55519. ** u.bc.r.flags = 0;
  55520. ** }
  55521. */
  55522. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  55523. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  55524. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  55525. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  55526. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  55527. u.bc.r.aMem = &aMem[pOp->p3];
  55528. #ifdef SQLITE_DEBUG
  55529. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  55530. #endif
  55531. ExpandBlob(u.bc.r.aMem);
  55532. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  55533. if( rc!=SQLITE_OK ){
  55534. goto abort_due_to_error;
  55535. }
  55536. u.bc.pC->rowidIsValid = 0;
  55537. }
  55538. u.bc.pC->deferredMoveto = 0;
  55539. u.bc.pC->cacheStatus = CACHE_STALE;
  55540. #ifdef SQLITE_TEST
  55541. sqlite3_search_count++;
  55542. #endif
  55543. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  55544. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  55545. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  55546. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55547. u.bc.pC->rowidIsValid = 0;
  55548. }else{
  55549. u.bc.res = 0;
  55550. }
  55551. }else{
  55552. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  55553. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  55554. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  55555. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  55556. u.bc.pC->rowidIsValid = 0;
  55557. }else{
  55558. /* u.bc.res might be negative because the table is empty. Check to
  55559. ** see if this is the case.
  55560. */
  55561. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  55562. }
  55563. }
  55564. assert( pOp->p2>0 );
  55565. if( u.bc.res ){
  55566. pc = pOp->p2 - 1;
  55567. }
  55568. }else{
  55569. /* This happens when attempting to open the sqlite3_master table
  55570. ** for read access returns SQLITE_EMPTY. In this case always
  55571. ** take the jump (since there are no records in the table).
  55572. */
  55573. pc = pOp->p2 - 1;
  55574. }
  55575. break;
  55576. }
  55577. /* Opcode: Seek P1 P2 * * *
  55578. **
  55579. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  55580. ** for P1 to move so that it points to the rowid given by P2.
  55581. **
  55582. ** This is actually a deferred seek. Nothing actually happens until
  55583. ** the cursor is used to read a record. That way, if no reads
  55584. ** occur, no unnecessary I/O happens.
  55585. */
  55586. case OP_Seek: { /* in2 */
  55587. #if 0 /* local variables moved into u.bd */
  55588. VdbeCursor *pC;
  55589. #endif /* local variables moved into u.bd */
  55590. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55591. u.bd.pC = p->apCsr[pOp->p1];
  55592. assert( u.bd.pC!=0 );
  55593. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  55594. assert( u.bd.pC->isTable );
  55595. u.bd.pC->nullRow = 0;
  55596. pIn2 = &aMem[pOp->p2];
  55597. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  55598. u.bd.pC->rowidIsValid = 0;
  55599. u.bd.pC->deferredMoveto = 1;
  55600. }
  55601. break;
  55602. }
  55603. /* Opcode: Found P1 P2 P3 P4 *
  55604. **
  55605. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  55606. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  55607. ** record.
  55608. **
  55609. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  55610. ** is a prefix of any entry in P1 then a jump is made to P2 and
  55611. ** P1 is left pointing at the matching entry.
  55612. */
  55613. /* Opcode: NotFound P1 P2 P3 P4 *
  55614. **
  55615. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  55616. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  55617. ** record.
  55618. **
  55619. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  55620. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  55621. ** does contain an entry whose prefix matches the P3/P4 record then control
  55622. ** falls through to the next instruction and P1 is left pointing at the
  55623. ** matching entry.
  55624. **
  55625. ** See also: Found, NotExists, IsUnique
  55626. */
  55627. case OP_NotFound: /* jump, in3 */
  55628. case OP_Found: { /* jump, in3 */
  55629. #if 0 /* local variables moved into u.be */
  55630. int alreadyExists;
  55631. VdbeCursor *pC;
  55632. int res;
  55633. char *pFree;
  55634. UnpackedRecord *pIdxKey;
  55635. UnpackedRecord r;
  55636. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  55637. #endif /* local variables moved into u.be */
  55638. #ifdef SQLITE_TEST
  55639. sqlite3_found_count++;
  55640. #endif
  55641. u.be.alreadyExists = 0;
  55642. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55643. assert( pOp->p4type==P4_INT32 );
  55644. u.be.pC = p->apCsr[pOp->p1];
  55645. assert( u.be.pC!=0 );
  55646. pIn3 = &aMem[pOp->p3];
  55647. if( ALWAYS(u.be.pC->pCursor!=0) ){
  55648. assert( u.be.pC->isTable==0 );
  55649. if( pOp->p4.i>0 ){
  55650. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  55651. u.be.r.nField = (u16)pOp->p4.i;
  55652. u.be.r.aMem = pIn3;
  55653. #ifdef SQLITE_DEBUG
  55654. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  55655. #endif
  55656. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  55657. u.be.pIdxKey = &u.be.r;
  55658. }else{
  55659. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  55660. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  55661. );
  55662. if( u.be.pIdxKey==0 ) goto no_mem;
  55663. assert( pIn3->flags & MEM_Blob );
  55664. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  55665. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  55666. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  55667. }
  55668. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  55669. if( pOp->p4.i==0 ){
  55670. sqlite3DbFree(db, u.be.pFree);
  55671. }
  55672. if( rc!=SQLITE_OK ){
  55673. break;
  55674. }
  55675. u.be.alreadyExists = (u.be.res==0);
  55676. u.be.pC->deferredMoveto = 0;
  55677. u.be.pC->cacheStatus = CACHE_STALE;
  55678. }
  55679. if( pOp->opcode==OP_Found ){
  55680. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  55681. }else{
  55682. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  55683. }
  55684. break;
  55685. }
  55686. /* Opcode: IsUnique P1 P2 P3 P4 *
  55687. **
  55688. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  55689. ** no data and where the key are records generated by OP_MakeRecord with
  55690. ** the list field being the integer ROWID of the entry that the index
  55691. ** entry refers to.
  55692. **
  55693. ** The P3 register contains an integer record number. Call this record
  55694. ** number R. Register P4 is the first in a set of N contiguous registers
  55695. ** that make up an unpacked index key that can be used with cursor P1.
  55696. ** The value of N can be inferred from the cursor. N includes the rowid
  55697. ** value appended to the end of the index record. This rowid value may
  55698. ** or may not be the same as R.
  55699. **
  55700. ** If any of the N registers beginning with register P4 contains a NULL
  55701. ** value, jump immediately to P2.
  55702. **
  55703. ** Otherwise, this instruction checks if cursor P1 contains an entry
  55704. ** where the first (N-1) fields match but the rowid value at the end
  55705. ** of the index entry is not R. If there is no such entry, control jumps
  55706. ** to instruction P2. Otherwise, the rowid of the conflicting index
  55707. ** entry is copied to register P3 and control falls through to the next
  55708. ** instruction.
  55709. **
  55710. ** See also: NotFound, NotExists, Found
  55711. */
  55712. case OP_IsUnique: { /* jump, in3 */
  55713. #if 0 /* local variables moved into u.bf */
  55714. u16 ii;
  55715. VdbeCursor *pCx;
  55716. BtCursor *pCrsr;
  55717. u16 nField;
  55718. Mem *aMx;
  55719. UnpackedRecord r; /* B-Tree index search key */
  55720. i64 R; /* Rowid stored in register P3 */
  55721. #endif /* local variables moved into u.bf */
  55722. pIn3 = &aMem[pOp->p3];
  55723. u.bf.aMx = &aMem[pOp->p4.i];
  55724. /* Assert that the values of parameters P1 and P4 are in range. */
  55725. assert( pOp->p4type==P4_INT32 );
  55726. assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) );
  55727. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55728. /* Find the index cursor. */
  55729. u.bf.pCx = p->apCsr[pOp->p1];
  55730. assert( u.bf.pCx->deferredMoveto==0 );
  55731. u.bf.pCx->seekResult = 0;
  55732. u.bf.pCx->cacheStatus = CACHE_STALE;
  55733. u.bf.pCrsr = u.bf.pCx->pCursor;
  55734. /* If any of the values are NULL, take the jump. */
  55735. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  55736. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  55737. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  55738. pc = pOp->p2 - 1;
  55739. u.bf.pCrsr = 0;
  55740. break;
  55741. }
  55742. }
  55743. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  55744. if( u.bf.pCrsr!=0 ){
  55745. /* Populate the index search key. */
  55746. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  55747. u.bf.r.nField = u.bf.nField + 1;
  55748. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  55749. u.bf.r.aMem = u.bf.aMx;
  55750. #ifdef SQLITE_DEBUG
  55751. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  55752. #endif
  55753. /* Extract the value of u.bf.R from register P3. */
  55754. sqlite3VdbeMemIntegerify(pIn3);
  55755. u.bf.R = pIn3->u.i;
  55756. /* Search the B-Tree index. If no conflicting record is found, jump
  55757. ** to P2. Otherwise, copy the rowid of the conflicting record to
  55758. ** register P3 and fall through to the next instruction. */
  55759. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  55760. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  55761. pc = pOp->p2 - 1;
  55762. }else{
  55763. pIn3->u.i = u.bf.r.rowid;
  55764. }
  55765. }
  55766. break;
  55767. }
  55768. /* Opcode: NotExists P1 P2 P3 * *
  55769. **
  55770. ** Use the content of register P3 as an integer key. If a record
  55771. ** with that key does not exist in table of P1, then jump to P2.
  55772. ** If the record does exist, then fall through. The cursor is left
  55773. ** pointing to the record if it exists.
  55774. **
  55775. ** The difference between this operation and NotFound is that this
  55776. ** operation assumes the key is an integer and that P1 is a table whereas
  55777. ** NotFound assumes key is a blob constructed from MakeRecord and
  55778. ** P1 is an index.
  55779. **
  55780. ** See also: Found, NotFound, IsUnique
  55781. */
  55782. case OP_NotExists: { /* jump, in3 */
  55783. #if 0 /* local variables moved into u.bg */
  55784. VdbeCursor *pC;
  55785. BtCursor *pCrsr;
  55786. int res;
  55787. u64 iKey;
  55788. #endif /* local variables moved into u.bg */
  55789. pIn3 = &aMem[pOp->p3];
  55790. assert( pIn3->flags & MEM_Int );
  55791. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55792. u.bg.pC = p->apCsr[pOp->p1];
  55793. assert( u.bg.pC!=0 );
  55794. assert( u.bg.pC->isTable );
  55795. assert( u.bg.pC->pseudoTableReg==0 );
  55796. u.bg.pCrsr = u.bg.pC->pCursor;
  55797. if( ALWAYS(u.bg.pCrsr!=0) ){
  55798. u.bg.res = 0;
  55799. u.bg.iKey = pIn3->u.i;
  55800. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  55801. u.bg.pC->lastRowid = pIn3->u.i;
  55802. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  55803. u.bg.pC->nullRow = 0;
  55804. u.bg.pC->cacheStatus = CACHE_STALE;
  55805. u.bg.pC->deferredMoveto = 0;
  55806. if( u.bg.res!=0 ){
  55807. pc = pOp->p2 - 1;
  55808. assert( u.bg.pC->rowidIsValid==0 );
  55809. }
  55810. u.bg.pC->seekResult = u.bg.res;
  55811. }else{
  55812. /* This happens when an attempt to open a read cursor on the
  55813. ** sqlite_master table returns SQLITE_EMPTY.
  55814. */
  55815. pc = pOp->p2 - 1;
  55816. assert( u.bg.pC->rowidIsValid==0 );
  55817. u.bg.pC->seekResult = 0;
  55818. }
  55819. break;
  55820. }
  55821. /* Opcode: Sequence P1 P2 * * *
  55822. **
  55823. ** Find the next available sequence number for cursor P1.
  55824. ** Write the sequence number into register P2.
  55825. ** The sequence number on the cursor is incremented after this
  55826. ** instruction.
  55827. */
  55828. case OP_Sequence: { /* out2-prerelease */
  55829. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55830. assert( p->apCsr[pOp->p1]!=0 );
  55831. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  55832. break;
  55833. }
  55834. /* Opcode: NewRowid P1 P2 P3 * *
  55835. **
  55836. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  55837. ** The record number is not previously used as a key in the database
  55838. ** table that cursor P1 points to. The new record number is written
  55839. ** written to register P2.
  55840. **
  55841. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  55842. ** the largest previously generated record number. No new record numbers are
  55843. ** allowed to be less than this value. When this value reaches its maximum,
  55844. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  55845. ** generated record number. This P3 mechanism is used to help implement the
  55846. ** AUTOINCREMENT feature.
  55847. */
  55848. case OP_NewRowid: { /* out2-prerelease */
  55849. #if 0 /* local variables moved into u.bh */
  55850. i64 v; /* The new rowid */
  55851. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  55852. int res; /* Result of an sqlite3BtreeLast() */
  55853. int cnt; /* Counter to limit the number of searches */
  55854. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  55855. VdbeFrame *pFrame; /* Root frame of VDBE */
  55856. #endif /* local variables moved into u.bh */
  55857. u.bh.v = 0;
  55858. u.bh.res = 0;
  55859. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  55860. u.bh.pC = p->apCsr[pOp->p1];
  55861. assert( u.bh.pC!=0 );
  55862. if( NEVER(u.bh.pC->pCursor==0) ){
  55863. /* The zero initialization above is all that is needed */
  55864. }else{
  55865. /* The next rowid or record number (different terms for the same
  55866. ** thing) is obtained in a two-step algorithm.
  55867. **
  55868. ** First we attempt to find the largest existing rowid and add one
  55869. ** to that. But if the largest existing rowid is already the maximum
  55870. ** positive integer, we have to fall through to the second
  55871. ** probabilistic algorithm
  55872. **
  55873. ** The second algorithm is to select a rowid at random and see if
  55874. ** it already exists in the table. If it does not exist, we have
  55875. ** succeeded. If the random rowid does exist, we select a new one
  55876. ** and try again, up to 100 times.
  55877. */
  55878. assert( u.bh.pC->isTable );
  55879. #ifdef SQLITE_32BIT_ROWID
  55880. # define MAX_ROWID 0x7fffffff
  55881. #else
  55882. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  55883. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  55884. ** to provide the constant while making all compilers happy.
  55885. */
  55886. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  55887. #endif
  55888. if( !u.bh.pC->useRandomRowid ){
  55889. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  55890. if( u.bh.v==0 ){
  55891. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  55892. if( rc!=SQLITE_OK ){
  55893. goto abort_due_to_error;
  55894. }
  55895. if( u.bh.res ){
  55896. u.bh.v = 1; /* IMP: R-61914-48074 */
  55897. }else{
  55898. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  55899. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  55900. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  55901. if( u.bh.v>=MAX_ROWID ){
  55902. u.bh.pC->useRandomRowid = 1;
  55903. }else{
  55904. u.bh.v++; /* IMP: R-29538-34987 */
  55905. }
  55906. }
  55907. }
  55908. #ifndef SQLITE_OMIT_AUTOINCREMENT
  55909. if( pOp->p3 ){
  55910. /* Assert that P3 is a valid memory cell. */
  55911. assert( pOp->p3>0 );
  55912. if( p->pFrame ){
  55913. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  55914. /* Assert that P3 is a valid memory cell. */
  55915. assert( pOp->p3<=u.bh.pFrame->nMem );
  55916. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  55917. }else{
  55918. /* Assert that P3 is a valid memory cell. */
  55919. assert( pOp->p3<=(p->nMem-p->nCursor) );
  55920. u.bh.pMem = &aMem[pOp->p3];
  55921. memAboutToChange(p, u.bh.pMem);
  55922. }
  55923. assert( memIsValid(u.bh.pMem) );
  55924. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  55925. sqlite3VdbeMemIntegerify(u.bh.pMem);
  55926. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  55927. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  55928. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  55929. goto abort_due_to_error;
  55930. }
  55931. if( u.bh.v<u.bh.pMem->u.i+1 ){
  55932. u.bh.v = u.bh.pMem->u.i + 1;
  55933. }
  55934. u.bh.pMem->u.i = u.bh.v;
  55935. }
  55936. #endif
  55937. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  55938. }
  55939. if( u.bh.pC->useRandomRowid ){
  55940. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  55941. ** largest possible integer (9223372036854775807) then the database
  55942. ** engine starts picking positive candidate ROWIDs at random until
  55943. ** it finds one that is not previously used. */
  55944. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  55945. ** an AUTOINCREMENT table. */
  55946. /* on the first attempt, simply do one more than previous */
  55947. u.bh.v = lastRowid;
  55948. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  55949. u.bh.v++; /* ensure non-zero */
  55950. u.bh.cnt = 0;
  55951. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  55952. 0, &u.bh.res))==SQLITE_OK)
  55953. && (u.bh.res==0)
  55954. && (++u.bh.cnt<100)){
  55955. /* collision - try another random rowid */
  55956. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  55957. if( u.bh.cnt<5 ){
  55958. /* try "small" random rowids for the initial attempts */
  55959. u.bh.v &= 0xffffff;
  55960. }else{
  55961. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  55962. }
  55963. u.bh.v++; /* ensure non-zero */
  55964. }
  55965. if( rc==SQLITE_OK && u.bh.res==0 ){
  55966. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  55967. goto abort_due_to_error;
  55968. }
  55969. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  55970. }
  55971. u.bh.pC->rowidIsValid = 0;
  55972. u.bh.pC->deferredMoveto = 0;
  55973. u.bh.pC->cacheStatus = CACHE_STALE;
  55974. }
  55975. pOut->u.i = u.bh.v;
  55976. break;
  55977. }
  55978. /* Opcode: Insert P1 P2 P3 P4 P5
  55979. **
  55980. ** Write an entry into the table of cursor P1. A new entry is
  55981. ** created if it doesn't already exist or the data for an existing
  55982. ** entry is overwritten. The data is the value MEM_Blob stored in register
  55983. ** number P2. The key is stored in register P3. The key must
  55984. ** be a MEM_Int.
  55985. **
  55986. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  55987. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  55988. ** then rowid is stored for subsequent return by the
  55989. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  55990. **
  55991. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  55992. ** the last seek operation (OP_NotExists) was a success, then this
  55993. ** operation will not attempt to find the appropriate row before doing
  55994. ** the insert but will instead overwrite the row that the cursor is
  55995. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  55996. ** has already positioned the cursor correctly. This is an optimization
  55997. ** that boosts performance by avoiding redundant seeks.
  55998. **
  55999. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  56000. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  56001. ** is part of an INSERT operation. The difference is only important to
  56002. ** the update hook.
  56003. **
  56004. ** Parameter P4 may point to a string containing the table-name, or
  56005. ** may be NULL. If it is not NULL, then the update-hook
  56006. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  56007. **
  56008. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  56009. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  56010. ** and register P2 becomes ephemeral. If the cursor is changed, the
  56011. ** value of register P2 will then change. Make sure this does not
  56012. ** cause any problems.)
  56013. **
  56014. ** This instruction only works on tables. The equivalent instruction
  56015. ** for indices is OP_IdxInsert.
  56016. */
  56017. /* Opcode: InsertInt P1 P2 P3 P4 P5
  56018. **
  56019. ** This works exactly like OP_Insert except that the key is the
  56020. ** integer value P3, not the value of the integer stored in register P3.
  56021. */
  56022. case OP_Insert:
  56023. case OP_InsertInt: {
  56024. #if 0 /* local variables moved into u.bi */
  56025. Mem *pData; /* MEM cell holding data for the record to be inserted */
  56026. Mem *pKey; /* MEM cell holding key for the record */
  56027. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  56028. VdbeCursor *pC; /* Cursor to table into which insert is written */
  56029. int nZero; /* Number of zero-bytes to append */
  56030. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  56031. const char *zDb; /* database name - used by the update hook */
  56032. const char *zTbl; /* Table name - used by the opdate hook */
  56033. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  56034. #endif /* local variables moved into u.bi */
  56035. u.bi.pData = &aMem[pOp->p2];
  56036. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56037. assert( memIsValid(u.bi.pData) );
  56038. u.bi.pC = p->apCsr[pOp->p1];
  56039. assert( u.bi.pC!=0 );
  56040. assert( u.bi.pC->pCursor!=0 );
  56041. assert( u.bi.pC->pseudoTableReg==0 );
  56042. assert( u.bi.pC->isTable );
  56043. REGISTER_TRACE(pOp->p2, u.bi.pData);
  56044. if( pOp->opcode==OP_Insert ){
  56045. u.bi.pKey = &aMem[pOp->p3];
  56046. assert( u.bi.pKey->flags & MEM_Int );
  56047. assert( memIsValid(u.bi.pKey) );
  56048. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  56049. u.bi.iKey = u.bi.pKey->u.i;
  56050. }else{
  56051. assert( pOp->opcode==OP_InsertInt );
  56052. u.bi.iKey = pOp->p3;
  56053. }
  56054. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  56055. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  56056. if( u.bi.pData->flags & MEM_Null ){
  56057. u.bi.pData->z = 0;
  56058. u.bi.pData->n = 0;
  56059. }else{
  56060. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  56061. }
  56062. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  56063. if( u.bi.pData->flags & MEM_Zero ){
  56064. u.bi.nZero = u.bi.pData->u.nZero;
  56065. }else{
  56066. u.bi.nZero = 0;
  56067. }
  56068. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  56069. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  56070. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  56071. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  56072. );
  56073. u.bi.pC->rowidIsValid = 0;
  56074. u.bi.pC->deferredMoveto = 0;
  56075. u.bi.pC->cacheStatus = CACHE_STALE;
  56076. /* Invoke the update-hook if required. */
  56077. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  56078. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  56079. u.bi.zTbl = pOp->p4.z;
  56080. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  56081. assert( u.bi.pC->isTable );
  56082. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  56083. assert( u.bi.pC->iDb>=0 );
  56084. }
  56085. break;
  56086. }
  56087. /* Opcode: Delete P1 P2 * P4 *
  56088. **
  56089. ** Delete the record at which the P1 cursor is currently pointing.
  56090. **
  56091. ** The cursor will be left pointing at either the next or the previous
  56092. ** record in the table. If it is left pointing at the next record, then
  56093. ** the next Next instruction will be a no-op. Hence it is OK to delete
  56094. ** a record from within an Next loop.
  56095. **
  56096. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  56097. ** incremented (otherwise not).
  56098. **
  56099. ** P1 must not be pseudo-table. It has to be a real table with
  56100. ** multiple rows.
  56101. **
  56102. ** If P4 is not NULL, then it is the name of the table that P1 is
  56103. ** pointing to. The update hook will be invoked, if it exists.
  56104. ** If P4 is not NULL then the P1 cursor must have been positioned
  56105. ** using OP_NotFound prior to invoking this opcode.
  56106. */
  56107. case OP_Delete: {
  56108. #if 0 /* local variables moved into u.bj */
  56109. i64 iKey;
  56110. VdbeCursor *pC;
  56111. #endif /* local variables moved into u.bj */
  56112. u.bj.iKey = 0;
  56113. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56114. u.bj.pC = p->apCsr[pOp->p1];
  56115. assert( u.bj.pC!=0 );
  56116. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  56117. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  56118. ** row being deleted.
  56119. */
  56120. if( db->xUpdateCallback && pOp->p4.z ){
  56121. assert( u.bj.pC->isTable );
  56122. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  56123. u.bj.iKey = u.bj.pC->lastRowid;
  56124. }
  56125. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  56126. ** OP_Column on the same table without any intervening operations that
  56127. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  56128. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  56129. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  56130. ** to guard against future changes to the code generator.
  56131. **/
  56132. assert( u.bj.pC->deferredMoveto==0 );
  56133. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  56134. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  56135. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  56136. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  56137. u.bj.pC->cacheStatus = CACHE_STALE;
  56138. /* Invoke the update-hook if required. */
  56139. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  56140. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  56141. const char *zTbl = pOp->p4.z;
  56142. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  56143. assert( u.bj.pC->iDb>=0 );
  56144. }
  56145. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  56146. break;
  56147. }
  56148. /* Opcode: ResetCount * * * * *
  56149. **
  56150. ** The value of the change counter is copied to the database handle
  56151. ** change counter (returned by subsequent calls to sqlite3_changes()).
  56152. ** Then the VMs internal change counter resets to 0.
  56153. ** This is used by trigger programs.
  56154. */
  56155. case OP_ResetCount: {
  56156. sqlite3VdbeSetChanges(db, p->nChange);
  56157. p->nChange = 0;
  56158. break;
  56159. }
  56160. /* Opcode: SorterCompare P1 P2 P3
  56161. **
  56162. ** P1 is a sorter cursor. This instruction compares the record blob in
  56163. ** register P3 with the entry that the sorter cursor currently points to.
  56164. ** If, excluding the rowid fields at the end, the two records are a match,
  56165. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  56166. */
  56167. case OP_SorterCompare: {
  56168. #if 0 /* local variables moved into u.bk */
  56169. VdbeCursor *pC;
  56170. int res;
  56171. #endif /* local variables moved into u.bk */
  56172. u.bk.pC = p->apCsr[pOp->p1];
  56173. assert( isSorter(u.bk.pC) );
  56174. pIn3 = &aMem[pOp->p3];
  56175. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  56176. if( u.bk.res ){
  56177. pc = pOp->p2-1;
  56178. }
  56179. break;
  56180. };
  56181. /* Opcode: SorterData P1 P2 * * *
  56182. **
  56183. ** Write into register P2 the current sorter data for sorter cursor P1.
  56184. */
  56185. case OP_SorterData: {
  56186. #if 0 /* local variables moved into u.bl */
  56187. VdbeCursor *pC;
  56188. #endif /* local variables moved into u.bl */
  56189. pOut = &aMem[pOp->p2];
  56190. u.bl.pC = p->apCsr[pOp->p1];
  56191. assert( u.bl.pC->isSorter );
  56192. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  56193. break;
  56194. }
  56195. /* Opcode: RowData P1 P2 * * *
  56196. **
  56197. ** Write into register P2 the complete row data for cursor P1.
  56198. ** There is no interpretation of the data.
  56199. ** It is just copied onto the P2 register exactly as
  56200. ** it is found in the database file.
  56201. **
  56202. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  56203. ** of a real table, not a pseudo-table.
  56204. */
  56205. /* Opcode: RowKey P1 P2 * * *
  56206. **
  56207. ** Write into register P2 the complete row key for cursor P1.
  56208. ** There is no interpretation of the data.
  56209. ** The key is copied onto the P3 register exactly as
  56210. ** it is found in the database file.
  56211. **
  56212. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  56213. ** of a real table, not a pseudo-table.
  56214. */
  56215. case OP_RowKey:
  56216. case OP_RowData: {
  56217. #if 0 /* local variables moved into u.bm */
  56218. VdbeCursor *pC;
  56219. BtCursor *pCrsr;
  56220. u32 n;
  56221. i64 n64;
  56222. #endif /* local variables moved into u.bm */
  56223. pOut = &aMem[pOp->p2];
  56224. memAboutToChange(p, pOut);
  56225. /* Note that RowKey and RowData are really exactly the same instruction */
  56226. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56227. u.bm.pC = p->apCsr[pOp->p1];
  56228. assert( u.bm.pC->isSorter==0 );
  56229. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  56230. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  56231. assert( u.bm.pC!=0 );
  56232. assert( u.bm.pC->nullRow==0 );
  56233. assert( u.bm.pC->pseudoTableReg==0 );
  56234. assert( u.bm.pC->pCursor!=0 );
  56235. u.bm.pCrsr = u.bm.pC->pCursor;
  56236. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  56237. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  56238. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  56239. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  56240. ** a no-op and can never fail. But we leave it in place as a safety.
  56241. */
  56242. assert( u.bm.pC->deferredMoveto==0 );
  56243. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  56244. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  56245. if( u.bm.pC->isIndex ){
  56246. assert( !u.bm.pC->isTable );
  56247. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  56248. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  56249. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  56250. goto too_big;
  56251. }
  56252. u.bm.n = (u32)u.bm.n64;
  56253. }else{
  56254. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  56255. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  56256. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  56257. goto too_big;
  56258. }
  56259. }
  56260. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  56261. goto no_mem;
  56262. }
  56263. pOut->n = u.bm.n;
  56264. MemSetTypeFlag(pOut, MEM_Blob);
  56265. if( u.bm.pC->isIndex ){
  56266. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  56267. }else{
  56268. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  56269. }
  56270. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  56271. UPDATE_MAX_BLOBSIZE(pOut);
  56272. break;
  56273. }
  56274. /* Opcode: Rowid P1 P2 * * *
  56275. **
  56276. ** Store in register P2 an integer which is the key of the table entry that
  56277. ** P1 is currently point to.
  56278. **
  56279. ** P1 can be either an ordinary table or a virtual table. There used to
  56280. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  56281. ** one opcode now works for both table types.
  56282. */
  56283. case OP_Rowid: { /* out2-prerelease */
  56284. #if 0 /* local variables moved into u.bn */
  56285. VdbeCursor *pC;
  56286. i64 v;
  56287. sqlite3_vtab *pVtab;
  56288. const sqlite3_module *pModule;
  56289. #endif /* local variables moved into u.bn */
  56290. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56291. u.bn.pC = p->apCsr[pOp->p1];
  56292. assert( u.bn.pC!=0 );
  56293. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  56294. if( u.bn.pC->nullRow ){
  56295. pOut->flags = MEM_Null;
  56296. break;
  56297. }else if( u.bn.pC->deferredMoveto ){
  56298. u.bn.v = u.bn.pC->movetoTarget;
  56299. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56300. }else if( u.bn.pC->pVtabCursor ){
  56301. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  56302. u.bn.pModule = u.bn.pVtab->pModule;
  56303. assert( u.bn.pModule->xRowid );
  56304. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  56305. sqlite3VtabImportErrmsg(p, u.bn.pVtab);
  56306. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  56307. }else{
  56308. assert( u.bn.pC->pCursor!=0 );
  56309. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  56310. if( rc ) goto abort_due_to_error;
  56311. if( u.bn.pC->rowidIsValid ){
  56312. u.bn.v = u.bn.pC->lastRowid;
  56313. }else{
  56314. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  56315. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  56316. }
  56317. }
  56318. pOut->u.i = u.bn.v;
  56319. break;
  56320. }
  56321. /* Opcode: NullRow P1 * * * *
  56322. **
  56323. ** Move the cursor P1 to a null row. Any OP_Column operations
  56324. ** that occur while the cursor is on the null row will always
  56325. ** write a NULL.
  56326. */
  56327. case OP_NullRow: {
  56328. #if 0 /* local variables moved into u.bo */
  56329. VdbeCursor *pC;
  56330. #endif /* local variables moved into u.bo */
  56331. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56332. u.bo.pC = p->apCsr[pOp->p1];
  56333. assert( u.bo.pC!=0 );
  56334. u.bo.pC->nullRow = 1;
  56335. u.bo.pC->rowidIsValid = 0;
  56336. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  56337. if( u.bo.pC->pCursor ){
  56338. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  56339. }
  56340. break;
  56341. }
  56342. /* Opcode: Last P1 P2 * * *
  56343. **
  56344. ** The next use of the Rowid or Column or Next instruction for P1
  56345. ** will refer to the last entry in the database table or index.
  56346. ** If the table or index is empty and P2>0, then jump immediately to P2.
  56347. ** If P2 is 0 or if the table or index is not empty, fall through
  56348. ** to the following instruction.
  56349. */
  56350. case OP_Last: { /* jump */
  56351. #if 0 /* local variables moved into u.bp */
  56352. VdbeCursor *pC;
  56353. BtCursor *pCrsr;
  56354. int res;
  56355. #endif /* local variables moved into u.bp */
  56356. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56357. u.bp.pC = p->apCsr[pOp->p1];
  56358. assert( u.bp.pC!=0 );
  56359. u.bp.pCrsr = u.bp.pC->pCursor;
  56360. u.bp.res = 0;
  56361. if( ALWAYS(u.bp.pCrsr!=0) ){
  56362. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  56363. }
  56364. u.bp.pC->nullRow = (u8)u.bp.res;
  56365. u.bp.pC->deferredMoveto = 0;
  56366. u.bp.pC->rowidIsValid = 0;
  56367. u.bp.pC->cacheStatus = CACHE_STALE;
  56368. if( pOp->p2>0 && u.bp.res ){
  56369. pc = pOp->p2 - 1;
  56370. }
  56371. break;
  56372. }
  56373. /* Opcode: Sort P1 P2 * * *
  56374. **
  56375. ** This opcode does exactly the same thing as OP_Rewind except that
  56376. ** it increments an undocumented global variable used for testing.
  56377. **
  56378. ** Sorting is accomplished by writing records into a sorting index,
  56379. ** then rewinding that index and playing it back from beginning to
  56380. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  56381. ** rewinding so that the global variable will be incremented and
  56382. ** regression tests can determine whether or not the optimizer is
  56383. ** correctly optimizing out sorts.
  56384. */
  56385. case OP_SorterSort: /* jump */
  56386. case OP_Sort: { /* jump */
  56387. #ifdef SQLITE_TEST
  56388. sqlite3_sort_count++;
  56389. sqlite3_search_count--;
  56390. #endif
  56391. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  56392. /* Fall through into OP_Rewind */
  56393. }
  56394. /* Opcode: Rewind P1 P2 * * *
  56395. **
  56396. ** The next use of the Rowid or Column or Next instruction for P1
  56397. ** will refer to the first entry in the database table or index.
  56398. ** If the table or index is empty and P2>0, then jump immediately to P2.
  56399. ** If P2 is 0 or if the table or index is not empty, fall through
  56400. ** to the following instruction.
  56401. */
  56402. case OP_Rewind: { /* jump */
  56403. #if 0 /* local variables moved into u.bq */
  56404. VdbeCursor *pC;
  56405. BtCursor *pCrsr;
  56406. int res;
  56407. #endif /* local variables moved into u.bq */
  56408. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56409. u.bq.pC = p->apCsr[pOp->p1];
  56410. assert( u.bq.pC!=0 );
  56411. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  56412. u.bq.res = 1;
  56413. if( isSorter(u.bq.pC) ){
  56414. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  56415. }else{
  56416. u.bq.pCrsr = u.bq.pC->pCursor;
  56417. assert( u.bq.pCrsr );
  56418. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  56419. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  56420. u.bq.pC->deferredMoveto = 0;
  56421. u.bq.pC->cacheStatus = CACHE_STALE;
  56422. u.bq.pC->rowidIsValid = 0;
  56423. }
  56424. u.bq.pC->nullRow = (u8)u.bq.res;
  56425. assert( pOp->p2>0 && pOp->p2<p->nOp );
  56426. if( u.bq.res ){
  56427. pc = pOp->p2 - 1;
  56428. }
  56429. break;
  56430. }
  56431. /* Opcode: Next P1 P2 * P4 P5
  56432. **
  56433. ** Advance cursor P1 so that it points to the next key/data pair in its
  56434. ** table or index. If there are no more key/value pairs then fall through
  56435. ** to the following instruction. But if the cursor advance was successful,
  56436. ** jump immediately to P2.
  56437. **
  56438. ** The P1 cursor must be for a real table, not a pseudo-table.
  56439. **
  56440. ** P4 is always of type P4_ADVANCE. The function pointer points to
  56441. ** sqlite3BtreeNext().
  56442. **
  56443. ** If P5 is positive and the jump is taken, then event counter
  56444. ** number P5-1 in the prepared statement is incremented.
  56445. **
  56446. ** See also: Prev
  56447. */
  56448. /* Opcode: Prev P1 P2 * * P5
  56449. **
  56450. ** Back up cursor P1 so that it points to the previous key/data pair in its
  56451. ** table or index. If there is no previous key/value pairs then fall through
  56452. ** to the following instruction. But if the cursor backup was successful,
  56453. ** jump immediately to P2.
  56454. **
  56455. ** The P1 cursor must be for a real table, not a pseudo-table.
  56456. **
  56457. ** P4 is always of type P4_ADVANCE. The function pointer points to
  56458. ** sqlite3BtreePrevious().
  56459. **
  56460. ** If P5 is positive and the jump is taken, then event counter
  56461. ** number P5-1 in the prepared statement is incremented.
  56462. */
  56463. case OP_SorterNext: /* jump */
  56464. case OP_Prev: /* jump */
  56465. case OP_Next: { /* jump */
  56466. #if 0 /* local variables moved into u.br */
  56467. VdbeCursor *pC;
  56468. int res;
  56469. #endif /* local variables moved into u.br */
  56470. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56471. assert( pOp->p5<ArraySize(p->aCounter) );
  56472. u.br.pC = p->apCsr[pOp->p1];
  56473. if( u.br.pC==0 ){
  56474. break; /* See ticket #2273 */
  56475. }
  56476. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  56477. if( isSorter(u.br.pC) ){
  56478. assert( pOp->opcode==OP_SorterNext );
  56479. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  56480. }else{
  56481. /* u.br.res = 1; // Always initialized by the xAdvance() call */
  56482. assert( u.br.pC->deferredMoveto==0 );
  56483. assert( u.br.pC->pCursor );
  56484. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  56485. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  56486. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  56487. }
  56488. u.br.pC->nullRow = (u8)u.br.res;
  56489. u.br.pC->cacheStatus = CACHE_STALE;
  56490. if( u.br.res==0 ){
  56491. pc = pOp->p2 - 1;
  56492. p->aCounter[pOp->p5]++;
  56493. #ifdef SQLITE_TEST
  56494. sqlite3_search_count++;
  56495. #endif
  56496. }
  56497. u.br.pC->rowidIsValid = 0;
  56498. goto check_for_interrupt;
  56499. }
  56500. /* Opcode: IdxInsert P1 P2 P3 * P5
  56501. **
  56502. ** Register P2 holds an SQL index key made using the
  56503. ** MakeRecord instructions. This opcode writes that key
  56504. ** into the index P1. Data for the entry is nil.
  56505. **
  56506. ** P3 is a flag that provides a hint to the b-tree layer that this
  56507. ** insert is likely to be an append.
  56508. **
  56509. ** This instruction only works for indices. The equivalent instruction
  56510. ** for tables is OP_Insert.
  56511. */
  56512. case OP_SorterInsert: /* in2 */
  56513. case OP_IdxInsert: { /* in2 */
  56514. #if 0 /* local variables moved into u.bs */
  56515. VdbeCursor *pC;
  56516. BtCursor *pCrsr;
  56517. int nKey;
  56518. const char *zKey;
  56519. #endif /* local variables moved into u.bs */
  56520. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56521. u.bs.pC = p->apCsr[pOp->p1];
  56522. assert( u.bs.pC!=0 );
  56523. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  56524. pIn2 = &aMem[pOp->p2];
  56525. assert( pIn2->flags & MEM_Blob );
  56526. u.bs.pCrsr = u.bs.pC->pCursor;
  56527. if( ALWAYS(u.bs.pCrsr!=0) ){
  56528. assert( u.bs.pC->isTable==0 );
  56529. rc = ExpandBlob(pIn2);
  56530. if( rc==SQLITE_OK ){
  56531. if( isSorter(u.bs.pC) ){
  56532. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  56533. }else{
  56534. u.bs.nKey = pIn2->n;
  56535. u.bs.zKey = pIn2->z;
  56536. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  56537. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  56538. );
  56539. assert( u.bs.pC->deferredMoveto==0 );
  56540. u.bs.pC->cacheStatus = CACHE_STALE;
  56541. }
  56542. }
  56543. }
  56544. break;
  56545. }
  56546. /* Opcode: IdxDelete P1 P2 P3 * *
  56547. **
  56548. ** The content of P3 registers starting at register P2 form
  56549. ** an unpacked index key. This opcode removes that entry from the
  56550. ** index opened by cursor P1.
  56551. */
  56552. case OP_IdxDelete: {
  56553. #if 0 /* local variables moved into u.bt */
  56554. VdbeCursor *pC;
  56555. BtCursor *pCrsr;
  56556. int res;
  56557. UnpackedRecord r;
  56558. #endif /* local variables moved into u.bt */
  56559. assert( pOp->p3>0 );
  56560. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  56561. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56562. u.bt.pC = p->apCsr[pOp->p1];
  56563. assert( u.bt.pC!=0 );
  56564. u.bt.pCrsr = u.bt.pC->pCursor;
  56565. if( ALWAYS(u.bt.pCrsr!=0) ){
  56566. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  56567. u.bt.r.nField = (u16)pOp->p3;
  56568. u.bt.r.flags = 0;
  56569. u.bt.r.aMem = &aMem[pOp->p2];
  56570. #ifdef SQLITE_DEBUG
  56571. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  56572. #endif
  56573. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  56574. if( rc==SQLITE_OK && u.bt.res==0 ){
  56575. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  56576. }
  56577. assert( u.bt.pC->deferredMoveto==0 );
  56578. u.bt.pC->cacheStatus = CACHE_STALE;
  56579. }
  56580. break;
  56581. }
  56582. /* Opcode: IdxRowid P1 P2 * * *
  56583. **
  56584. ** Write into register P2 an integer which is the last entry in the record at
  56585. ** the end of the index key pointed to by cursor P1. This integer should be
  56586. ** the rowid of the table entry to which this index entry points.
  56587. **
  56588. ** See also: Rowid, MakeRecord.
  56589. */
  56590. case OP_IdxRowid: { /* out2-prerelease */
  56591. #if 0 /* local variables moved into u.bu */
  56592. BtCursor *pCrsr;
  56593. VdbeCursor *pC;
  56594. i64 rowid;
  56595. #endif /* local variables moved into u.bu */
  56596. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56597. u.bu.pC = p->apCsr[pOp->p1];
  56598. assert( u.bu.pC!=0 );
  56599. u.bu.pCrsr = u.bu.pC->pCursor;
  56600. pOut->flags = MEM_Null;
  56601. if( ALWAYS(u.bu.pCrsr!=0) ){
  56602. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  56603. if( NEVER(rc) ) goto abort_due_to_error;
  56604. assert( u.bu.pC->deferredMoveto==0 );
  56605. assert( u.bu.pC->isTable==0 );
  56606. if( !u.bu.pC->nullRow ){
  56607. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  56608. if( rc!=SQLITE_OK ){
  56609. goto abort_due_to_error;
  56610. }
  56611. pOut->u.i = u.bu.rowid;
  56612. pOut->flags = MEM_Int;
  56613. }
  56614. }
  56615. break;
  56616. }
  56617. /* Opcode: IdxGE P1 P2 P3 P4 P5
  56618. **
  56619. ** The P4 register values beginning with P3 form an unpacked index
  56620. ** key that omits the ROWID. Compare this key value against the index
  56621. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  56622. **
  56623. ** If the P1 index entry is greater than or equal to the key value
  56624. ** then jump to P2. Otherwise fall through to the next instruction.
  56625. **
  56626. ** If P5 is non-zero then the key value is increased by an epsilon
  56627. ** prior to the comparison. This make the opcode work like IdxGT except
  56628. ** that if the key from register P3 is a prefix of the key in the cursor,
  56629. ** the result is false whereas it would be true with IdxGT.
  56630. */
  56631. /* Opcode: IdxLT P1 P2 P3 P4 P5
  56632. **
  56633. ** The P4 register values beginning with P3 form an unpacked index
  56634. ** key that omits the ROWID. Compare this key value against the index
  56635. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  56636. **
  56637. ** If the P1 index entry is less than the key value then jump to P2.
  56638. ** Otherwise fall through to the next instruction.
  56639. **
  56640. ** If P5 is non-zero then the key value is increased by an epsilon prior
  56641. ** to the comparison. This makes the opcode work like IdxLE.
  56642. */
  56643. case OP_IdxLT: /* jump */
  56644. case OP_IdxGE: { /* jump */
  56645. #if 0 /* local variables moved into u.bv */
  56646. VdbeCursor *pC;
  56647. int res;
  56648. UnpackedRecord r;
  56649. #endif /* local variables moved into u.bv */
  56650. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  56651. u.bv.pC = p->apCsr[pOp->p1];
  56652. assert( u.bv.pC!=0 );
  56653. assert( u.bv.pC->isOrdered );
  56654. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  56655. assert( u.bv.pC->deferredMoveto==0 );
  56656. assert( pOp->p5==0 || pOp->p5==1 );
  56657. assert( pOp->p4type==P4_INT32 );
  56658. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  56659. u.bv.r.nField = (u16)pOp->p4.i;
  56660. if( pOp->p5 ){
  56661. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  56662. }else{
  56663. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  56664. }
  56665. u.bv.r.aMem = &aMem[pOp->p3];
  56666. #ifdef SQLITE_DEBUG
  56667. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  56668. #endif
  56669. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  56670. if( pOp->opcode==OP_IdxLT ){
  56671. u.bv.res = -u.bv.res;
  56672. }else{
  56673. assert( pOp->opcode==OP_IdxGE );
  56674. u.bv.res++;
  56675. }
  56676. if( u.bv.res>0 ){
  56677. pc = pOp->p2 - 1 ;
  56678. }
  56679. }
  56680. break;
  56681. }
  56682. /* Opcode: Destroy P1 P2 P3 * *
  56683. **
  56684. ** Delete an entire database table or index whose root page in the database
  56685. ** file is given by P1.
  56686. **
  56687. ** The table being destroyed is in the main database file if P3==0. If
  56688. ** P3==1 then the table to be clear is in the auxiliary database file
  56689. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  56690. **
  56691. ** If AUTOVACUUM is enabled then it is possible that another root page
  56692. ** might be moved into the newly deleted root page in order to keep all
  56693. ** root pages contiguous at the beginning of the database. The former
  56694. ** value of the root page that moved - its value before the move occurred -
  56695. ** is stored in register P2. If no page
  56696. ** movement was required (because the table being dropped was already
  56697. ** the last one in the database) then a zero is stored in register P2.
  56698. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  56699. **
  56700. ** See also: Clear
  56701. */
  56702. case OP_Destroy: { /* out2-prerelease */
  56703. #if 0 /* local variables moved into u.bw */
  56704. int iMoved;
  56705. int iCnt;
  56706. Vdbe *pVdbe;
  56707. int iDb;
  56708. #endif /* local variables moved into u.bw */
  56709. assert( p->readOnly==0 );
  56710. #ifndef SQLITE_OMIT_VIRTUALTABLE
  56711. u.bw.iCnt = 0;
  56712. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  56713. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
  56714. && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
  56715. ){
  56716. u.bw.iCnt++;
  56717. }
  56718. }
  56719. #else
  56720. u.bw.iCnt = db->nVdbeRead;
  56721. #endif
  56722. pOut->flags = MEM_Null;
  56723. if( u.bw.iCnt>1 ){
  56724. rc = SQLITE_LOCKED;
  56725. p->errorAction = OE_Abort;
  56726. }else{
  56727. u.bw.iDb = pOp->p3;
  56728. assert( u.bw.iCnt==1 );
  56729. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  56730. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  56731. pOut->flags = MEM_Int;
  56732. pOut->u.i = u.bw.iMoved;
  56733. #ifndef SQLITE_OMIT_AUTOVACUUM
  56734. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  56735. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  56736. /* All OP_Destroy operations occur on the same btree */
  56737. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  56738. resetSchemaOnFault = u.bw.iDb+1;
  56739. }
  56740. #endif
  56741. }
  56742. break;
  56743. }
  56744. /* Opcode: Clear P1 P2 P3
  56745. **
  56746. ** Delete all contents of the database table or index whose root page
  56747. ** in the database file is given by P1. But, unlike Destroy, do not
  56748. ** remove the table or index from the database file.
  56749. **
  56750. ** The table being clear is in the main database file if P2==0. If
  56751. ** P2==1 then the table to be clear is in the auxiliary database file
  56752. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  56753. **
  56754. ** If the P3 value is non-zero, then the table referred to must be an
  56755. ** intkey table (an SQL table, not an index). In this case the row change
  56756. ** count is incremented by the number of rows in the table being cleared.
  56757. ** If P3 is greater than zero, then the value stored in register P3 is
  56758. ** also incremented by the number of rows in the table being cleared.
  56759. **
  56760. ** See also: Destroy
  56761. */
  56762. case OP_Clear: {
  56763. #if 0 /* local variables moved into u.bx */
  56764. int nChange;
  56765. #endif /* local variables moved into u.bx */
  56766. u.bx.nChange = 0;
  56767. assert( p->readOnly==0 );
  56768. assert( pOp->p1!=1 );
  56769. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  56770. rc = sqlite3BtreeClearTable(
  56771. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  56772. );
  56773. if( pOp->p3 ){
  56774. p->nChange += u.bx.nChange;
  56775. if( pOp->p3>0 ){
  56776. assert( memIsValid(&aMem[pOp->p3]) );
  56777. memAboutToChange(p, &aMem[pOp->p3]);
  56778. aMem[pOp->p3].u.i += u.bx.nChange;
  56779. }
  56780. }
  56781. break;
  56782. }
  56783. /* Opcode: CreateTable P1 P2 * * *
  56784. **
  56785. ** Allocate a new table in the main database file if P1==0 or in the
  56786. ** auxiliary database file if P1==1 or in an attached database if
  56787. ** P1>1. Write the root page number of the new table into
  56788. ** register P2
  56789. **
  56790. ** The difference between a table and an index is this: A table must
  56791. ** have a 4-byte integer key and can have arbitrary data. An index
  56792. ** has an arbitrary key but no data.
  56793. **
  56794. ** See also: CreateIndex
  56795. */
  56796. /* Opcode: CreateIndex P1 P2 * * *
  56797. **
  56798. ** Allocate a new index in the main database file if P1==0 or in the
  56799. ** auxiliary database file if P1==1 or in an attached database if
  56800. ** P1>1. Write the root page number of the new table into
  56801. ** register P2.
  56802. **
  56803. ** See documentation on OP_CreateTable for additional information.
  56804. */
  56805. case OP_CreateIndex: /* out2-prerelease */
  56806. case OP_CreateTable: { /* out2-prerelease */
  56807. #if 0 /* local variables moved into u.by */
  56808. int pgno;
  56809. int flags;
  56810. Db *pDb;
  56811. #endif /* local variables moved into u.by */
  56812. u.by.pgno = 0;
  56813. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  56814. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  56815. assert( p->readOnly==0 );
  56816. u.by.pDb = &db->aDb[pOp->p1];
  56817. assert( u.by.pDb->pBt!=0 );
  56818. if( pOp->opcode==OP_CreateTable ){
  56819. /* u.by.flags = BTREE_INTKEY; */
  56820. u.by.flags = BTREE_INTKEY;
  56821. }else{
  56822. u.by.flags = BTREE_BLOBKEY;
  56823. }
  56824. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  56825. pOut->u.i = u.by.pgno;
  56826. break;
  56827. }
  56828. /* Opcode: ParseSchema P1 * * P4 *
  56829. **
  56830. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  56831. ** that match the WHERE clause P4.
  56832. **
  56833. ** This opcode invokes the parser to create a new virtual machine,
  56834. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  56835. */
  56836. case OP_ParseSchema: {
  56837. #if 0 /* local variables moved into u.bz */
  56838. int iDb;
  56839. const char *zMaster;
  56840. char *zSql;
  56841. InitData initData;
  56842. #endif /* local variables moved into u.bz */
  56843. /* Any prepared statement that invokes this opcode will hold mutexes
  56844. ** on every btree. This is a prerequisite for invoking
  56845. ** sqlite3InitCallback().
  56846. */
  56847. #ifdef SQLITE_DEBUG
  56848. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  56849. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  56850. }
  56851. #endif
  56852. u.bz.iDb = pOp->p1;
  56853. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  56854. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  56855. /* Used to be a conditional */ {
  56856. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  56857. u.bz.initData.db = db;
  56858. u.bz.initData.iDb = pOp->p1;
  56859. u.bz.initData.pzErrMsg = &p->zErrMsg;
  56860. u.bz.zSql = sqlite3MPrintf(db,
  56861. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  56862. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  56863. if( u.bz.zSql==0 ){
  56864. rc = SQLITE_NOMEM;
  56865. }else{
  56866. assert( db->init.busy==0 );
  56867. db->init.busy = 1;
  56868. u.bz.initData.rc = SQLITE_OK;
  56869. assert( !db->mallocFailed );
  56870. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  56871. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  56872. sqlite3DbFree(db, u.bz.zSql);
  56873. db->init.busy = 0;
  56874. }
  56875. }
  56876. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  56877. if( rc==SQLITE_NOMEM ){
  56878. goto no_mem;
  56879. }
  56880. break;
  56881. }
  56882. #if !defined(SQLITE_OMIT_ANALYZE)
  56883. /* Opcode: LoadAnalysis P1 * * * *
  56884. **
  56885. ** Read the sqlite_stat1 table for database P1 and load the content
  56886. ** of that table into the internal index hash table. This will cause
  56887. ** the analysis to be used when preparing all subsequent queries.
  56888. */
  56889. case OP_LoadAnalysis: {
  56890. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  56891. rc = sqlite3AnalysisLoad(db, pOp->p1);
  56892. break;
  56893. }
  56894. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  56895. /* Opcode: DropTable P1 * * P4 *
  56896. **
  56897. ** Remove the internal (in-memory) data structures that describe
  56898. ** the table named P4 in database P1. This is called after a table
  56899. ** is dropped in order to keep the internal representation of the
  56900. ** schema consistent with what is on disk.
  56901. */
  56902. case OP_DropTable: {
  56903. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  56904. break;
  56905. }
  56906. /* Opcode: DropIndex P1 * * P4 *
  56907. **
  56908. ** Remove the internal (in-memory) data structures that describe
  56909. ** the index named P4 in database P1. This is called after an index
  56910. ** is dropped in order to keep the internal representation of the
  56911. ** schema consistent with what is on disk.
  56912. */
  56913. case OP_DropIndex: {
  56914. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  56915. break;
  56916. }
  56917. /* Opcode: DropTrigger P1 * * P4 *
  56918. **
  56919. ** Remove the internal (in-memory) data structures that describe
  56920. ** the trigger named P4 in database P1. This is called after a trigger
  56921. ** is dropped in order to keep the internal representation of the
  56922. ** schema consistent with what is on disk.
  56923. */
  56924. case OP_DropTrigger: {
  56925. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  56926. break;
  56927. }
  56928. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56929. /* Opcode: IntegrityCk P1 P2 P3 * P5
  56930. **
  56931. ** Do an analysis of the currently open database. Store in
  56932. ** register P1 the text of an error message describing any problems.
  56933. ** If no problems are found, store a NULL in register P1.
  56934. **
  56935. ** The register P3 contains the maximum number of allowed errors.
  56936. ** At most reg(P3) errors will be reported.
  56937. ** In other words, the analysis stops as soon as reg(P1) errors are
  56938. ** seen. Reg(P1) is updated with the number of errors remaining.
  56939. **
  56940. ** The root page numbers of all tables in the database are integer
  56941. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  56942. ** total.
  56943. **
  56944. ** If P5 is not zero, the check is done on the auxiliary database
  56945. ** file, not the main database file.
  56946. **
  56947. ** This opcode is used to implement the integrity_check pragma.
  56948. */
  56949. case OP_IntegrityCk: {
  56950. #if 0 /* local variables moved into u.ca */
  56951. int nRoot; /* Number of tables to check. (Number of root pages.) */
  56952. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  56953. int j; /* Loop counter */
  56954. int nErr; /* Number of errors reported */
  56955. char *z; /* Text of the error report */
  56956. Mem *pnErr; /* Register keeping track of errors remaining */
  56957. #endif /* local variables moved into u.ca */
  56958. assert( p->bIsReader );
  56959. u.ca.nRoot = pOp->p2;
  56960. assert( u.ca.nRoot>0 );
  56961. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  56962. if( u.ca.aRoot==0 ) goto no_mem;
  56963. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  56964. u.ca.pnErr = &aMem[pOp->p3];
  56965. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  56966. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  56967. pIn1 = &aMem[pOp->p1];
  56968. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  56969. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  56970. }
  56971. u.ca.aRoot[u.ca.j] = 0;
  56972. assert( pOp->p5<db->nDb );
  56973. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  56974. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  56975. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  56976. sqlite3DbFree(db, u.ca.aRoot);
  56977. u.ca.pnErr->u.i -= u.ca.nErr;
  56978. sqlite3VdbeMemSetNull(pIn1);
  56979. if( u.ca.nErr==0 ){
  56980. assert( u.ca.z==0 );
  56981. }else if( u.ca.z==0 ){
  56982. goto no_mem;
  56983. }else{
  56984. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  56985. }
  56986. UPDATE_MAX_BLOBSIZE(pIn1);
  56987. sqlite3VdbeChangeEncoding(pIn1, encoding);
  56988. break;
  56989. }
  56990. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56991. /* Opcode: RowSetAdd P1 P2 * * *
  56992. **
  56993. ** Insert the integer value held by register P2 into a boolean index
  56994. ** held in register P1.
  56995. **
  56996. ** An assertion fails if P2 is not an integer.
  56997. */
  56998. case OP_RowSetAdd: { /* in1, in2 */
  56999. pIn1 = &aMem[pOp->p1];
  57000. pIn2 = &aMem[pOp->p2];
  57001. assert( (pIn2->flags & MEM_Int)!=0 );
  57002. if( (pIn1->flags & MEM_RowSet)==0 ){
  57003. sqlite3VdbeMemSetRowSet(pIn1);
  57004. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  57005. }
  57006. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  57007. break;
  57008. }
  57009. /* Opcode: RowSetRead P1 P2 P3 * *
  57010. **
  57011. ** Extract the smallest value from boolean index P1 and put that value into
  57012. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  57013. ** unchanged and jump to instruction P2.
  57014. */
  57015. case OP_RowSetRead: { /* jump, in1, out3 */
  57016. #if 0 /* local variables moved into u.cb */
  57017. i64 val;
  57018. #endif /* local variables moved into u.cb */
  57019. pIn1 = &aMem[pOp->p1];
  57020. if( (pIn1->flags & MEM_RowSet)==0
  57021. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  57022. ){
  57023. /* The boolean index is empty */
  57024. sqlite3VdbeMemSetNull(pIn1);
  57025. pc = pOp->p2 - 1;
  57026. }else{
  57027. /* A value was pulled from the index */
  57028. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  57029. }
  57030. goto check_for_interrupt;
  57031. }
  57032. /* Opcode: RowSetTest P1 P2 P3 P4
  57033. **
  57034. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  57035. ** contains a RowSet object and that RowSet object contains
  57036. ** the value held in P3, jump to register P2. Otherwise, insert the
  57037. ** integer in P3 into the RowSet and continue on to the
  57038. ** next opcode.
  57039. **
  57040. ** The RowSet object is optimized for the case where successive sets
  57041. ** of integers, where each set contains no duplicates. Each set
  57042. ** of values is identified by a unique P4 value. The first set
  57043. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  57044. ** non-negative. For non-negative values of P4 only the lower 4
  57045. ** bits are significant.
  57046. **
  57047. ** This allows optimizations: (a) when P4==0 there is no need to test
  57048. ** the rowset object for P3, as it is guaranteed not to contain it,
  57049. ** (b) when P4==-1 there is no need to insert the value, as it will
  57050. ** never be tested for, and (c) when a value that is part of set X is
  57051. ** inserted, there is no need to search to see if the same value was
  57052. ** previously inserted as part of set X (only if it was previously
  57053. ** inserted as part of some other set).
  57054. */
  57055. case OP_RowSetTest: { /* jump, in1, in3 */
  57056. #if 0 /* local variables moved into u.cc */
  57057. int iSet;
  57058. int exists;
  57059. #endif /* local variables moved into u.cc */
  57060. pIn1 = &aMem[pOp->p1];
  57061. pIn3 = &aMem[pOp->p3];
  57062. u.cc.iSet = pOp->p4.i;
  57063. assert( pIn3->flags&MEM_Int );
  57064. /* If there is anything other than a rowset object in memory cell P1,
  57065. ** delete it now and initialize P1 with an empty rowset
  57066. */
  57067. if( (pIn1->flags & MEM_RowSet)==0 ){
  57068. sqlite3VdbeMemSetRowSet(pIn1);
  57069. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  57070. }
  57071. assert( pOp->p4type==P4_INT32 );
  57072. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  57073. if( u.cc.iSet ){
  57074. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  57075. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  57076. pIn3->u.i);
  57077. if( u.cc.exists ){
  57078. pc = pOp->p2 - 1;
  57079. break;
  57080. }
  57081. }
  57082. if( u.cc.iSet>=0 ){
  57083. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  57084. }
  57085. break;
  57086. }
  57087. #ifndef SQLITE_OMIT_TRIGGER
  57088. /* Opcode: Program P1 P2 P3 P4 *
  57089. **
  57090. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  57091. **
  57092. ** P1 contains the address of the memory cell that contains the first memory
  57093. ** cell in an array of values used as arguments to the sub-program. P2
  57094. ** contains the address to jump to if the sub-program throws an IGNORE
  57095. ** exception using the RAISE() function. Register P3 contains the address
  57096. ** of a memory cell in this (the parent) VM that is used to allocate the
  57097. ** memory required by the sub-vdbe at runtime.
  57098. **
  57099. ** P4 is a pointer to the VM containing the trigger program.
  57100. */
  57101. case OP_Program: { /* jump */
  57102. #if 0 /* local variables moved into u.cd */
  57103. int nMem; /* Number of memory registers for sub-program */
  57104. int nByte; /* Bytes of runtime space required for sub-program */
  57105. Mem *pRt; /* Register to allocate runtime space */
  57106. Mem *pMem; /* Used to iterate through memory cells */
  57107. Mem *pEnd; /* Last memory cell in new array */
  57108. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  57109. SubProgram *pProgram; /* Sub-program to execute */
  57110. void *t; /* Token identifying trigger */
  57111. #endif /* local variables moved into u.cd */
  57112. u.cd.pProgram = pOp->p4.pProgram;
  57113. u.cd.pRt = &aMem[pOp->p3];
  57114. assert( u.cd.pProgram->nOp>0 );
  57115. /* If the p5 flag is clear, then recursive invocation of triggers is
  57116. ** disabled for backwards compatibility (p5 is set if this sub-program
  57117. ** is really a trigger, not a foreign key action, and the flag set
  57118. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  57119. **
  57120. ** It is recursive invocation of triggers, at the SQL level, that is
  57121. ** disabled. In some cases a single trigger may generate more than one
  57122. ** SubProgram (if the trigger may be executed with more than one different
  57123. ** ON CONFLICT algorithm). SubProgram structures associated with a
  57124. ** single trigger all have the same value for the SubProgram.token
  57125. ** variable. */
  57126. if( pOp->p5 ){
  57127. u.cd.t = u.cd.pProgram->token;
  57128. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  57129. if( u.cd.pFrame ) break;
  57130. }
  57131. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  57132. rc = SQLITE_ERROR;
  57133. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  57134. break;
  57135. }
  57136. /* Register u.cd.pRt is used to store the memory required to save the state
  57137. ** of the current program, and the memory required at runtime to execute
  57138. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  57139. ** is already allocated. Otherwise, it must be initialized. */
  57140. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  57141. /* SubProgram.nMem is set to the number of memory cells used by the
  57142. ** program stored in SubProgram.aOp. As well as these, one memory
  57143. ** cell is required for each cursor used by the program. Set local
  57144. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  57145. */
  57146. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  57147. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  57148. + u.cd.nMem * sizeof(Mem)
  57149. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  57150. + u.cd.pProgram->nOnce * sizeof(u8);
  57151. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  57152. if( !u.cd.pFrame ){
  57153. goto no_mem;
  57154. }
  57155. sqlite3VdbeMemRelease(u.cd.pRt);
  57156. u.cd.pRt->flags = MEM_Frame;
  57157. u.cd.pRt->u.pFrame = u.cd.pFrame;
  57158. u.cd.pFrame->v = p;
  57159. u.cd.pFrame->nChildMem = u.cd.nMem;
  57160. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  57161. u.cd.pFrame->pc = pc;
  57162. u.cd.pFrame->aMem = p->aMem;
  57163. u.cd.pFrame->nMem = p->nMem;
  57164. u.cd.pFrame->apCsr = p->apCsr;
  57165. u.cd.pFrame->nCursor = p->nCursor;
  57166. u.cd.pFrame->aOp = p->aOp;
  57167. u.cd.pFrame->nOp = p->nOp;
  57168. u.cd.pFrame->token = u.cd.pProgram->token;
  57169. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  57170. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  57171. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  57172. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  57173. u.cd.pMem->flags = MEM_Invalid;
  57174. u.cd.pMem->db = db;
  57175. }
  57176. }else{
  57177. u.cd.pFrame = u.cd.pRt->u.pFrame;
  57178. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  57179. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  57180. assert( pc==u.cd.pFrame->pc );
  57181. }
  57182. p->nFrame++;
  57183. u.cd.pFrame->pParent = p->pFrame;
  57184. u.cd.pFrame->lastRowid = lastRowid;
  57185. u.cd.pFrame->nChange = p->nChange;
  57186. p->nChange = 0;
  57187. p->pFrame = u.cd.pFrame;
  57188. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  57189. p->nMem = u.cd.pFrame->nChildMem;
  57190. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  57191. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  57192. p->aOp = aOp = u.cd.pProgram->aOp;
  57193. p->nOp = u.cd.pProgram->nOp;
  57194. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  57195. p->nOnceFlag = u.cd.pProgram->nOnce;
  57196. pc = -1;
  57197. memset(p->aOnceFlag, 0, p->nOnceFlag);
  57198. break;
  57199. }
  57200. /* Opcode: Param P1 P2 * * *
  57201. **
  57202. ** This opcode is only ever present in sub-programs called via the
  57203. ** OP_Program instruction. Copy a value currently stored in a memory
  57204. ** cell of the calling (parent) frame to cell P2 in the current frames
  57205. ** address space. This is used by trigger programs to access the new.*
  57206. ** and old.* values.
  57207. **
  57208. ** The address of the cell in the parent frame is determined by adding
  57209. ** the value of the P1 argument to the value of the P1 argument to the
  57210. ** calling OP_Program instruction.
  57211. */
  57212. case OP_Param: { /* out2-prerelease */
  57213. #if 0 /* local variables moved into u.ce */
  57214. VdbeFrame *pFrame;
  57215. Mem *pIn;
  57216. #endif /* local variables moved into u.ce */
  57217. u.ce.pFrame = p->pFrame;
  57218. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  57219. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  57220. break;
  57221. }
  57222. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  57223. #ifndef SQLITE_OMIT_FOREIGN_KEY
  57224. /* Opcode: FkCounter P1 P2 * * *
  57225. **
  57226. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  57227. ** If P1 is non-zero, the database constraint counter is incremented
  57228. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  57229. ** statement counter is incremented (immediate foreign key constraints).
  57230. */
  57231. case OP_FkCounter: {
  57232. if( db->flags & SQLITE_DeferFKs ){
  57233. db->nDeferredImmCons += pOp->p2;
  57234. }else if( pOp->p1 ){
  57235. db->nDeferredCons += pOp->p2;
  57236. }else{
  57237. p->nFkConstraint += pOp->p2;
  57238. }
  57239. break;
  57240. }
  57241. /* Opcode: FkIfZero P1 P2 * * *
  57242. **
  57243. ** This opcode tests if a foreign key constraint-counter is currently zero.
  57244. ** If so, jump to instruction P2. Otherwise, fall through to the next
  57245. ** instruction.
  57246. **
  57247. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  57248. ** is zero (the one that counts deferred constraint violations). If P1 is
  57249. ** zero, the jump is taken if the statement constraint-counter is zero
  57250. ** (immediate foreign key constraint violations).
  57251. */
  57252. case OP_FkIfZero: { /* jump */
  57253. if( pOp->p1 ){
  57254. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  57255. }else{
  57256. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  57257. }
  57258. break;
  57259. }
  57260. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  57261. #ifndef SQLITE_OMIT_AUTOINCREMENT
  57262. /* Opcode: MemMax P1 P2 * * *
  57263. **
  57264. ** P1 is a register in the root frame of this VM (the root frame is
  57265. ** different from the current frame if this instruction is being executed
  57266. ** within a sub-program). Set the value of register P1 to the maximum of
  57267. ** its current value and the value in register P2.
  57268. **
  57269. ** This instruction throws an error if the memory cell is not initially
  57270. ** an integer.
  57271. */
  57272. case OP_MemMax: { /* in2 */
  57273. #if 0 /* local variables moved into u.cf */
  57274. Mem *pIn1;
  57275. VdbeFrame *pFrame;
  57276. #endif /* local variables moved into u.cf */
  57277. if( p->pFrame ){
  57278. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  57279. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  57280. }else{
  57281. u.cf.pIn1 = &aMem[pOp->p1];
  57282. }
  57283. assert( memIsValid(u.cf.pIn1) );
  57284. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  57285. pIn2 = &aMem[pOp->p2];
  57286. sqlite3VdbeMemIntegerify(pIn2);
  57287. if( u.cf.pIn1->u.i<pIn2->u.i){
  57288. u.cf.pIn1->u.i = pIn2->u.i;
  57289. }
  57290. break;
  57291. }
  57292. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  57293. /* Opcode: IfPos P1 P2 * * *
  57294. **
  57295. ** If the value of register P1 is 1 or greater, jump to P2.
  57296. **
  57297. ** It is illegal to use this instruction on a register that does
  57298. ** not contain an integer. An assertion fault will result if you try.
  57299. */
  57300. case OP_IfPos: { /* jump, in1 */
  57301. pIn1 = &aMem[pOp->p1];
  57302. assert( pIn1->flags&MEM_Int );
  57303. if( pIn1->u.i>0 ){
  57304. pc = pOp->p2 - 1;
  57305. }
  57306. break;
  57307. }
  57308. /* Opcode: IfNeg P1 P2 * * *
  57309. **
  57310. ** If the value of register P1 is less than zero, jump to P2.
  57311. **
  57312. ** It is illegal to use this instruction on a register that does
  57313. ** not contain an integer. An assertion fault will result if you try.
  57314. */
  57315. case OP_IfNeg: { /* jump, in1 */
  57316. pIn1 = &aMem[pOp->p1];
  57317. assert( pIn1->flags&MEM_Int );
  57318. if( pIn1->u.i<0 ){
  57319. pc = pOp->p2 - 1;
  57320. }
  57321. break;
  57322. }
  57323. /* Opcode: IfZero P1 P2 P3 * *
  57324. **
  57325. ** The register P1 must contain an integer. Add literal P3 to the
  57326. ** value in register P1. If the result is exactly 0, jump to P2.
  57327. **
  57328. ** It is illegal to use this instruction on a register that does
  57329. ** not contain an integer. An assertion fault will result if you try.
  57330. */
  57331. case OP_IfZero: { /* jump, in1 */
  57332. pIn1 = &aMem[pOp->p1];
  57333. assert( pIn1->flags&MEM_Int );
  57334. pIn1->u.i += pOp->p3;
  57335. if( pIn1->u.i==0 ){
  57336. pc = pOp->p2 - 1;
  57337. }
  57338. break;
  57339. }
  57340. /* Opcode: AggStep * P2 P3 P4 P5
  57341. **
  57342. ** Execute the step function for an aggregate. The
  57343. ** function has P5 arguments. P4 is a pointer to the FuncDef
  57344. ** structure that specifies the function. Use register
  57345. ** P3 as the accumulator.
  57346. **
  57347. ** The P5 arguments are taken from register P2 and its
  57348. ** successors.
  57349. */
  57350. case OP_AggStep: {
  57351. #if 0 /* local variables moved into u.cg */
  57352. int n;
  57353. int i;
  57354. Mem *pMem;
  57355. Mem *pRec;
  57356. sqlite3_context ctx;
  57357. sqlite3_value **apVal;
  57358. #endif /* local variables moved into u.cg */
  57359. u.cg.n = pOp->p5;
  57360. assert( u.cg.n>=0 );
  57361. u.cg.pRec = &aMem[pOp->p2];
  57362. u.cg.apVal = p->apArg;
  57363. assert( u.cg.apVal || u.cg.n==0 );
  57364. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  57365. assert( memIsValid(u.cg.pRec) );
  57366. u.cg.apVal[u.cg.i] = u.cg.pRec;
  57367. memAboutToChange(p, u.cg.pRec);
  57368. sqlite3VdbeMemStoreType(u.cg.pRec);
  57369. }
  57370. u.cg.ctx.pFunc = pOp->p4.pFunc;
  57371. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  57372. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  57373. u.cg.pMem->n++;
  57374. u.cg.ctx.s.flags = MEM_Null;
  57375. u.cg.ctx.s.z = 0;
  57376. u.cg.ctx.s.zMalloc = 0;
  57377. u.cg.ctx.s.xDel = 0;
  57378. u.cg.ctx.s.db = db;
  57379. u.cg.ctx.isError = 0;
  57380. u.cg.ctx.pColl = 0;
  57381. u.cg.ctx.skipFlag = 0;
  57382. if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  57383. assert( pOp>p->aOp );
  57384. assert( pOp[-1].p4type==P4_COLLSEQ );
  57385. assert( pOp[-1].opcode==OP_CollSeq );
  57386. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  57387. }
  57388. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  57389. if( u.cg.ctx.isError ){
  57390. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  57391. rc = u.cg.ctx.isError;
  57392. }
  57393. if( u.cg.ctx.skipFlag ){
  57394. assert( pOp[-1].opcode==OP_CollSeq );
  57395. u.cg.i = pOp[-1].p1;
  57396. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  57397. }
  57398. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  57399. break;
  57400. }
  57401. /* Opcode: AggFinal P1 P2 * P4 *
  57402. **
  57403. ** Execute the finalizer function for an aggregate. P1 is
  57404. ** the memory location that is the accumulator for the aggregate.
  57405. **
  57406. ** P2 is the number of arguments that the step function takes and
  57407. ** P4 is a pointer to the FuncDef for this function. The P2
  57408. ** argument is not used by this opcode. It is only there to disambiguate
  57409. ** functions that can take varying numbers of arguments. The
  57410. ** P4 argument is only needed for the degenerate case where
  57411. ** the step function was not previously called.
  57412. */
  57413. case OP_AggFinal: {
  57414. #if 0 /* local variables moved into u.ch */
  57415. Mem *pMem;
  57416. #endif /* local variables moved into u.ch */
  57417. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  57418. u.ch.pMem = &aMem[pOp->p1];
  57419. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  57420. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  57421. if( rc ){
  57422. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  57423. }
  57424. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  57425. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  57426. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  57427. goto too_big;
  57428. }
  57429. break;
  57430. }
  57431. #ifndef SQLITE_OMIT_WAL
  57432. /* Opcode: Checkpoint P1 P2 P3 * *
  57433. **
  57434. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  57435. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  57436. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  57437. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  57438. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  57439. ** in the WAL that have been checkpointed after the checkpoint
  57440. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  57441. ** mem[P3+2] are initialized to -1.
  57442. */
  57443. case OP_Checkpoint: {
  57444. #if 0 /* local variables moved into u.ci */
  57445. int i; /* Loop counter */
  57446. int aRes[3]; /* Results */
  57447. Mem *pMem; /* Write results here */
  57448. #endif /* local variables moved into u.ci */
  57449. assert( p->readOnly==0 );
  57450. u.ci.aRes[0] = 0;
  57451. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  57452. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  57453. || pOp->p2==SQLITE_CHECKPOINT_FULL
  57454. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  57455. );
  57456. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  57457. if( rc==SQLITE_BUSY ){
  57458. rc = SQLITE_OK;
  57459. u.ci.aRes[0] = 1;
  57460. }
  57461. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  57462. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  57463. }
  57464. break;
  57465. };
  57466. #endif
  57467. #ifndef SQLITE_OMIT_PRAGMA
  57468. /* Opcode: JournalMode P1 P2 P3 * P5
  57469. **
  57470. ** Change the journal mode of database P1 to P3. P3 must be one of the
  57471. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  57472. ** modes (delete, truncate, persist, off and memory), this is a simple
  57473. ** operation. No IO is required.
  57474. **
  57475. ** If changing into or out of WAL mode the procedure is more complicated.
  57476. **
  57477. ** Write a string containing the final journal-mode to register P2.
  57478. */
  57479. case OP_JournalMode: { /* out2-prerelease */
  57480. #if 0 /* local variables moved into u.cj */
  57481. Btree *pBt; /* Btree to change journal mode of */
  57482. Pager *pPager; /* Pager associated with pBt */
  57483. int eNew; /* New journal mode */
  57484. int eOld; /* The old journal mode */
  57485. #ifndef SQLITE_OMIT_WAL
  57486. const char *zFilename; /* Name of database file for pPager */
  57487. #endif
  57488. #endif /* local variables moved into u.cj */
  57489. u.cj.eNew = pOp->p3;
  57490. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  57491. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  57492. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  57493. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  57494. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  57495. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  57496. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  57497. );
  57498. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  57499. assert( p->readOnly==0 );
  57500. u.cj.pBt = db->aDb[pOp->p1].pBt;
  57501. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  57502. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  57503. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  57504. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  57505. #ifndef SQLITE_OMIT_WAL
  57506. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  57507. /* Do not allow a transition to journal_mode=WAL for a database
  57508. ** in temporary storage or if the VFS does not support shared memory
  57509. */
  57510. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  57511. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  57512. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  57513. ){
  57514. u.cj.eNew = u.cj.eOld;
  57515. }
  57516. if( (u.cj.eNew!=u.cj.eOld)
  57517. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  57518. ){
  57519. if( !db->autoCommit || db->nVdbeRead>1 ){
  57520. rc = SQLITE_ERROR;
  57521. sqlite3SetString(&p->zErrMsg, db,
  57522. "cannot change %s wal mode from within a transaction",
  57523. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  57524. );
  57525. break;
  57526. }else{
  57527. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  57528. /* If leaving WAL mode, close the log file. If successful, the call
  57529. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  57530. ** file. An EXCLUSIVE lock may still be held on the database file
  57531. ** after a successful return.
  57532. */
  57533. rc = sqlite3PagerCloseWal(u.cj.pPager);
  57534. if( rc==SQLITE_OK ){
  57535. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  57536. }
  57537. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  57538. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  57539. ** as an intermediate */
  57540. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  57541. }
  57542. /* Open a transaction on the database file. Regardless of the journal
  57543. ** mode, this transaction always uses a rollback journal.
  57544. */
  57545. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  57546. if( rc==SQLITE_OK ){
  57547. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  57548. }
  57549. }
  57550. }
  57551. #endif /* ifndef SQLITE_OMIT_WAL */
  57552. if( rc ){
  57553. u.cj.eNew = u.cj.eOld;
  57554. }
  57555. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  57556. pOut = &aMem[pOp->p2];
  57557. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  57558. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  57559. pOut->n = sqlite3Strlen30(pOut->z);
  57560. pOut->enc = SQLITE_UTF8;
  57561. sqlite3VdbeChangeEncoding(pOut, encoding);
  57562. break;
  57563. };
  57564. #endif /* SQLITE_OMIT_PRAGMA */
  57565. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  57566. /* Opcode: Vacuum * * * * *
  57567. **
  57568. ** Vacuum the entire database. This opcode will cause other virtual
  57569. ** machines to be created and run. It may not be called from within
  57570. ** a transaction.
  57571. */
  57572. case OP_Vacuum: {
  57573. assert( p->readOnly==0 );
  57574. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  57575. break;
  57576. }
  57577. #endif
  57578. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  57579. /* Opcode: IncrVacuum P1 P2 * * *
  57580. **
  57581. ** Perform a single step of the incremental vacuum procedure on
  57582. ** the P1 database. If the vacuum has finished, jump to instruction
  57583. ** P2. Otherwise, fall through to the next instruction.
  57584. */
  57585. case OP_IncrVacuum: { /* jump */
  57586. #if 0 /* local variables moved into u.ck */
  57587. Btree *pBt;
  57588. #endif /* local variables moved into u.ck */
  57589. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  57590. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  57591. assert( p->readOnly==0 );
  57592. u.ck.pBt = db->aDb[pOp->p1].pBt;
  57593. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  57594. if( rc==SQLITE_DONE ){
  57595. pc = pOp->p2 - 1;
  57596. rc = SQLITE_OK;
  57597. }
  57598. break;
  57599. }
  57600. #endif
  57601. /* Opcode: Expire P1 * * * *
  57602. **
  57603. ** Cause precompiled statements to become expired. An expired statement
  57604. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  57605. ** (via sqlite3_step()).
  57606. **
  57607. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  57608. ** then only the currently executing statement is affected.
  57609. */
  57610. case OP_Expire: {
  57611. if( !pOp->p1 ){
  57612. sqlite3ExpirePreparedStatements(db);
  57613. }else{
  57614. p->expired = 1;
  57615. }
  57616. break;
  57617. }
  57618. #ifndef SQLITE_OMIT_SHARED_CACHE
  57619. /* Opcode: TableLock P1 P2 P3 P4 *
  57620. **
  57621. ** Obtain a lock on a particular table. This instruction is only used when
  57622. ** the shared-cache feature is enabled.
  57623. **
  57624. ** P1 is the index of the database in sqlite3.aDb[] of the database
  57625. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  57626. ** a write lock if P3==1.
  57627. **
  57628. ** P2 contains the root-page of the table to lock.
  57629. **
  57630. ** P4 contains a pointer to the name of the table being locked. This is only
  57631. ** used to generate an error message if the lock cannot be obtained.
  57632. */
  57633. case OP_TableLock: {
  57634. u8 isWriteLock = (u8)pOp->p3;
  57635. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  57636. int p1 = pOp->p1;
  57637. assert( p1>=0 && p1<db->nDb );
  57638. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  57639. assert( isWriteLock==0 || isWriteLock==1 );
  57640. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  57641. if( (rc&0xFF)==SQLITE_LOCKED ){
  57642. const char *z = pOp->p4.z;
  57643. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  57644. }
  57645. }
  57646. break;
  57647. }
  57648. #endif /* SQLITE_OMIT_SHARED_CACHE */
  57649. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57650. /* Opcode: VBegin * * * P4 *
  57651. **
  57652. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  57653. ** xBegin method for that table.
  57654. **
  57655. ** Also, whether or not P4 is set, check that this is not being called from
  57656. ** within a callback to a virtual table xSync() method. If it is, the error
  57657. ** code will be set to SQLITE_LOCKED.
  57658. */
  57659. case OP_VBegin: {
  57660. #if 0 /* local variables moved into u.cl */
  57661. VTable *pVTab;
  57662. #endif /* local variables moved into u.cl */
  57663. u.cl.pVTab = pOp->p4.pVtab;
  57664. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  57665. if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
  57666. break;
  57667. }
  57668. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57669. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57670. /* Opcode: VCreate P1 * * P4 *
  57671. **
  57672. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  57673. ** for that table.
  57674. */
  57675. case OP_VCreate: {
  57676. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  57677. break;
  57678. }
  57679. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57680. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57681. /* Opcode: VDestroy P1 * * P4 *
  57682. **
  57683. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  57684. ** of that table.
  57685. */
  57686. case OP_VDestroy: {
  57687. p->inVtabMethod = 2;
  57688. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  57689. p->inVtabMethod = 0;
  57690. break;
  57691. }
  57692. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57693. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57694. /* Opcode: VOpen P1 * * P4 *
  57695. **
  57696. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57697. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  57698. ** table and stores that cursor in P1.
  57699. */
  57700. case OP_VOpen: {
  57701. #if 0 /* local variables moved into u.cm */
  57702. VdbeCursor *pCur;
  57703. sqlite3_vtab_cursor *pVtabCursor;
  57704. sqlite3_vtab *pVtab;
  57705. sqlite3_module *pModule;
  57706. #endif /* local variables moved into u.cm */
  57707. assert( p->bIsReader );
  57708. u.cm.pCur = 0;
  57709. u.cm.pVtabCursor = 0;
  57710. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  57711. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  57712. assert(u.cm.pVtab && u.cm.pModule);
  57713. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  57714. sqlite3VtabImportErrmsg(p, u.cm.pVtab);
  57715. if( SQLITE_OK==rc ){
  57716. /* Initialize sqlite3_vtab_cursor base class */
  57717. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  57718. /* Initialize vdbe cursor object */
  57719. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  57720. if( u.cm.pCur ){
  57721. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  57722. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  57723. }else{
  57724. db->mallocFailed = 1;
  57725. u.cm.pModule->xClose(u.cm.pVtabCursor);
  57726. }
  57727. }
  57728. break;
  57729. }
  57730. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57731. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57732. /* Opcode: VFilter P1 P2 P3 P4 *
  57733. **
  57734. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  57735. ** the filtered result set is empty.
  57736. **
  57737. ** P4 is either NULL or a string that was generated by the xBestIndex
  57738. ** method of the module. The interpretation of the P4 string is left
  57739. ** to the module implementation.
  57740. **
  57741. ** This opcode invokes the xFilter method on the virtual table specified
  57742. ** by P1. The integer query plan parameter to xFilter is stored in register
  57743. ** P3. Register P3+1 stores the argc parameter to be passed to the
  57744. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  57745. ** additional parameters which are passed to
  57746. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  57747. **
  57748. ** A jump is made to P2 if the result set after filtering would be empty.
  57749. */
  57750. case OP_VFilter: { /* jump */
  57751. #if 0 /* local variables moved into u.cn */
  57752. int nArg;
  57753. int iQuery;
  57754. const sqlite3_module *pModule;
  57755. Mem *pQuery;
  57756. Mem *pArgc;
  57757. sqlite3_vtab_cursor *pVtabCursor;
  57758. sqlite3_vtab *pVtab;
  57759. VdbeCursor *pCur;
  57760. int res;
  57761. int i;
  57762. Mem **apArg;
  57763. #endif /* local variables moved into u.cn */
  57764. u.cn.pQuery = &aMem[pOp->p3];
  57765. u.cn.pArgc = &u.cn.pQuery[1];
  57766. u.cn.pCur = p->apCsr[pOp->p1];
  57767. assert( memIsValid(u.cn.pQuery) );
  57768. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  57769. assert( u.cn.pCur->pVtabCursor );
  57770. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  57771. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  57772. u.cn.pModule = u.cn.pVtab->pModule;
  57773. /* Grab the index number and argc parameters */
  57774. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  57775. u.cn.nArg = (int)u.cn.pArgc->u.i;
  57776. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  57777. /* Invoke the xFilter method */
  57778. {
  57779. u.cn.res = 0;
  57780. u.cn.apArg = p->apArg;
  57781. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  57782. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  57783. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  57784. }
  57785. p->inVtabMethod = 1;
  57786. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  57787. p->inVtabMethod = 0;
  57788. sqlite3VtabImportErrmsg(p, u.cn.pVtab);
  57789. if( rc==SQLITE_OK ){
  57790. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  57791. }
  57792. if( u.cn.res ){
  57793. pc = pOp->p2 - 1;
  57794. }
  57795. }
  57796. u.cn.pCur->nullRow = 0;
  57797. break;
  57798. }
  57799. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57800. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57801. /* Opcode: VColumn P1 P2 P3 * *
  57802. **
  57803. ** Store the value of the P2-th column of
  57804. ** the row of the virtual-table that the
  57805. ** P1 cursor is pointing to into register P3.
  57806. */
  57807. case OP_VColumn: {
  57808. #if 0 /* local variables moved into u.co */
  57809. sqlite3_vtab *pVtab;
  57810. const sqlite3_module *pModule;
  57811. Mem *pDest;
  57812. sqlite3_context sContext;
  57813. #endif /* local variables moved into u.co */
  57814. VdbeCursor *pCur = p->apCsr[pOp->p1];
  57815. assert( pCur->pVtabCursor );
  57816. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  57817. u.co.pDest = &aMem[pOp->p3];
  57818. memAboutToChange(p, u.co.pDest);
  57819. if( pCur->nullRow ){
  57820. sqlite3VdbeMemSetNull(u.co.pDest);
  57821. break;
  57822. }
  57823. u.co.pVtab = pCur->pVtabCursor->pVtab;
  57824. u.co.pModule = u.co.pVtab->pModule;
  57825. assert( u.co.pModule->xColumn );
  57826. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  57827. /* The output cell may already have a buffer allocated. Move
  57828. ** the current contents to u.co.sContext.s so in case the user-function
  57829. ** can use the already allocated buffer instead of allocating a
  57830. ** new one.
  57831. */
  57832. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  57833. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  57834. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  57835. sqlite3VtabImportErrmsg(p, u.co.pVtab);
  57836. if( u.co.sContext.isError ){
  57837. rc = u.co.sContext.isError;
  57838. }
  57839. /* Copy the result of the function to the P3 register. We
  57840. ** do this regardless of whether or not an error occurred to ensure any
  57841. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  57842. */
  57843. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  57844. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  57845. REGISTER_TRACE(pOp->p3, u.co.pDest);
  57846. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  57847. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  57848. goto too_big;
  57849. }
  57850. break;
  57851. }
  57852. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57853. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57854. /* Opcode: VNext P1 P2 * * *
  57855. **
  57856. ** Advance virtual table P1 to the next row in its result set and
  57857. ** jump to instruction P2. Or, if the virtual table has reached
  57858. ** the end of its result set, then fall through to the next instruction.
  57859. */
  57860. case OP_VNext: { /* jump */
  57861. #if 0 /* local variables moved into u.cp */
  57862. sqlite3_vtab *pVtab;
  57863. const sqlite3_module *pModule;
  57864. int res;
  57865. VdbeCursor *pCur;
  57866. #endif /* local variables moved into u.cp */
  57867. u.cp.res = 0;
  57868. u.cp.pCur = p->apCsr[pOp->p1];
  57869. assert( u.cp.pCur->pVtabCursor );
  57870. if( u.cp.pCur->nullRow ){
  57871. break;
  57872. }
  57873. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  57874. u.cp.pModule = u.cp.pVtab->pModule;
  57875. assert( u.cp.pModule->xNext );
  57876. /* Invoke the xNext() method of the module. There is no way for the
  57877. ** underlying implementation to return an error if one occurs during
  57878. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  57879. ** data is available) and the error code returned when xColumn or
  57880. ** some other method is next invoked on the save virtual table cursor.
  57881. */
  57882. p->inVtabMethod = 1;
  57883. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  57884. p->inVtabMethod = 0;
  57885. sqlite3VtabImportErrmsg(p, u.cp.pVtab);
  57886. if( rc==SQLITE_OK ){
  57887. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  57888. }
  57889. if( !u.cp.res ){
  57890. /* If there is data, jump to P2 */
  57891. pc = pOp->p2 - 1;
  57892. }
  57893. goto check_for_interrupt;
  57894. }
  57895. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  57896. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57897. /* Opcode: VRename P1 * * P4 *
  57898. **
  57899. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57900. ** This opcode invokes the corresponding xRename method. The value
  57901. ** in register P1 is passed as the zName argument to the xRename method.
  57902. */
  57903. case OP_VRename: {
  57904. #if 0 /* local variables moved into u.cq */
  57905. sqlite3_vtab *pVtab;
  57906. Mem *pName;
  57907. #endif /* local variables moved into u.cq */
  57908. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  57909. u.cq.pName = &aMem[pOp->p1];
  57910. assert( u.cq.pVtab->pModule->xRename );
  57911. assert( memIsValid(u.cq.pName) );
  57912. assert( p->readOnly==0 );
  57913. REGISTER_TRACE(pOp->p1, u.cq.pName);
  57914. assert( u.cq.pName->flags & MEM_Str );
  57915. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  57916. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  57917. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  57918. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  57919. if( rc==SQLITE_OK ){
  57920. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  57921. sqlite3VtabImportErrmsg(p, u.cq.pVtab);
  57922. p->expired = 0;
  57923. }
  57924. break;
  57925. }
  57926. #endif
  57927. #ifndef SQLITE_OMIT_VIRTUALTABLE
  57928. /* Opcode: VUpdate P1 P2 P3 P4 *
  57929. **
  57930. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  57931. ** This opcode invokes the corresponding xUpdate method. P2 values
  57932. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  57933. ** invocation. The value in register (P3+P2-1) corresponds to the
  57934. ** p2th element of the argv array passed to xUpdate.
  57935. **
  57936. ** The xUpdate method will do a DELETE or an INSERT or both.
  57937. ** The argv[0] element (which corresponds to memory cell P3)
  57938. ** is the rowid of a row to delete. If argv[0] is NULL then no
  57939. ** deletion occurs. The argv[1] element is the rowid of the new
  57940. ** row. This can be NULL to have the virtual table select the new
  57941. ** rowid for itself. The subsequent elements in the array are
  57942. ** the values of columns in the new row.
  57943. **
  57944. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  57945. ** a row to delete.
  57946. **
  57947. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  57948. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  57949. ** is set to the value of the rowid for the row just inserted.
  57950. */
  57951. case OP_VUpdate: {
  57952. #if 0 /* local variables moved into u.cr */
  57953. sqlite3_vtab *pVtab;
  57954. sqlite3_module *pModule;
  57955. int nArg;
  57956. int i;
  57957. sqlite_int64 rowid;
  57958. Mem **apArg;
  57959. Mem *pX;
  57960. #endif /* local variables moved into u.cr */
  57961. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  57962. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  57963. );
  57964. assert( p->readOnly==0 );
  57965. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  57966. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  57967. u.cr.nArg = pOp->p2;
  57968. assert( pOp->p4type==P4_VTAB );
  57969. if( ALWAYS(u.cr.pModule->xUpdate) ){
  57970. u8 vtabOnConflict = db->vtabOnConflict;
  57971. u.cr.apArg = p->apArg;
  57972. u.cr.pX = &aMem[pOp->p3];
  57973. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  57974. assert( memIsValid(u.cr.pX) );
  57975. memAboutToChange(p, u.cr.pX);
  57976. sqlite3VdbeMemStoreType(u.cr.pX);
  57977. u.cr.apArg[u.cr.i] = u.cr.pX;
  57978. u.cr.pX++;
  57979. }
  57980. db->vtabOnConflict = pOp->p5;
  57981. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  57982. db->vtabOnConflict = vtabOnConflict;
  57983. sqlite3VtabImportErrmsg(p, u.cr.pVtab);
  57984. if( rc==SQLITE_OK && pOp->p1 ){
  57985. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  57986. db->lastRowid = lastRowid = u.cr.rowid;
  57987. }
  57988. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  57989. if( pOp->p5==OE_Ignore ){
  57990. rc = SQLITE_OK;
  57991. }else{
  57992. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  57993. }
  57994. }else{
  57995. p->nChange++;
  57996. }
  57997. }
  57998. break;
  57999. }
  58000. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  58001. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  58002. /* Opcode: Pagecount P1 P2 * * *
  58003. **
  58004. ** Write the current number of pages in database P1 to memory cell P2.
  58005. */
  58006. case OP_Pagecount: { /* out2-prerelease */
  58007. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  58008. break;
  58009. }
  58010. #endif
  58011. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  58012. /* Opcode: MaxPgcnt P1 P2 P3 * *
  58013. **
  58014. ** Try to set the maximum page count for database P1 to the value in P3.
  58015. ** Do not let the maximum page count fall below the current page count and
  58016. ** do not change the maximum page count value if P3==0.
  58017. **
  58018. ** Store the maximum page count after the change in register P2.
  58019. */
  58020. case OP_MaxPgcnt: { /* out2-prerelease */
  58021. unsigned int newMax;
  58022. Btree *pBt;
  58023. pBt = db->aDb[pOp->p1].pBt;
  58024. newMax = 0;
  58025. if( pOp->p3 ){
  58026. newMax = sqlite3BtreeLastPage(pBt);
  58027. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  58028. }
  58029. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  58030. break;
  58031. }
  58032. #endif
  58033. #ifndef SQLITE_OMIT_TRACE
  58034. /* Opcode: Trace * * * P4 *
  58035. **
  58036. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  58037. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  58038. */
  58039. case OP_Trace: {
  58040. #if 0 /* local variables moved into u.cs */
  58041. char *zTrace;
  58042. char *z;
  58043. #endif /* local variables moved into u.cs */
  58044. if( db->xTrace
  58045. && !p->doingRerun
  58046. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  58047. ){
  58048. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  58049. db->xTrace(db->pTraceArg, u.cs.z);
  58050. sqlite3DbFree(db, u.cs.z);
  58051. }
  58052. #ifdef SQLITE_DEBUG
  58053. if( (db->flags & SQLITE_SqlTrace)!=0
  58054. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  58055. ){
  58056. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  58057. }
  58058. #endif /* SQLITE_DEBUG */
  58059. break;
  58060. }
  58061. #endif
  58062. /* Opcode: Noop * * * * *
  58063. **
  58064. ** Do nothing. This instruction is often useful as a jump
  58065. ** destination.
  58066. */
  58067. /*
  58068. ** The magic Explain opcode are only inserted when explain==2 (which
  58069. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  58070. ** This opcode records information from the optimizer. It is the
  58071. ** the same as a no-op. This opcodesnever appears in a real VM program.
  58072. */
  58073. default: { /* This is really OP_Noop and OP_Explain */
  58074. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  58075. break;
  58076. }
  58077. /*****************************************************************************
  58078. ** The cases of the switch statement above this line should all be indented
  58079. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  58080. ** readability. From this point on down, the normal indentation rules are
  58081. ** restored.
  58082. *****************************************************************************/
  58083. }
  58084. #ifdef VDBE_PROFILE
  58085. {
  58086. u64 elapsed = sqlite3Hwtime() - start;
  58087. pOp->cycles += elapsed;
  58088. pOp->cnt++;
  58089. #if 0
  58090. fprintf(stdout, "%10llu ", elapsed);
  58091. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  58092. #endif
  58093. }
  58094. #endif
  58095. /* The following code adds nothing to the actual functionality
  58096. ** of the program. It is only here for testing and debugging.
  58097. ** On the other hand, it does burn CPU cycles every time through
  58098. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  58099. */
  58100. #ifndef NDEBUG
  58101. assert( pc>=-1 && pc<p->nOp );
  58102. #ifdef SQLITE_DEBUG
  58103. if( p->trace ){
  58104. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  58105. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  58106. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  58107. }
  58108. if( pOp->opflags & OPFLG_OUT3 ){
  58109. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  58110. }
  58111. }
  58112. #endif /* SQLITE_DEBUG */
  58113. #endif /* NDEBUG */
  58114. } /* The end of the for(;;) loop the loops through opcodes */
  58115. /* If we reach this point, it means that execution is finished with
  58116. ** an error of some kind.
  58117. */
  58118. vdbe_error_halt:
  58119. assert( rc );
  58120. p->rc = rc;
  58121. testcase( sqlite3GlobalConfig.xLog!=0 );
  58122. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  58123. pc, p->zSql, p->zErrMsg);
  58124. sqlite3VdbeHalt(p);
  58125. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  58126. rc = SQLITE_ERROR;
  58127. if( resetSchemaOnFault>0 ){
  58128. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  58129. }
  58130. /* This is the only way out of this procedure. We have to
  58131. ** release the mutexes on btrees that were acquired at the
  58132. ** top. */
  58133. vdbe_return:
  58134. db->lastRowid = lastRowid;
  58135. testcase( nVmStep>0 );
  58136. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  58137. sqlite3VdbeLeave(p);
  58138. return rc;
  58139. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  58140. ** is encountered.
  58141. */
  58142. too_big:
  58143. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  58144. rc = SQLITE_TOOBIG;
  58145. goto vdbe_error_halt;
  58146. /* Jump to here if a malloc() fails.
  58147. */
  58148. no_mem:
  58149. db->mallocFailed = 1;
  58150. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  58151. rc = SQLITE_NOMEM;
  58152. goto vdbe_error_halt;
  58153. /* Jump to here for any other kind of fatal error. The "rc" variable
  58154. ** should hold the error number.
  58155. */
  58156. abort_due_to_error:
  58157. assert( p->zErrMsg==0 );
  58158. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  58159. if( rc!=SQLITE_IOERR_NOMEM ){
  58160. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  58161. }
  58162. goto vdbe_error_halt;
  58163. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  58164. ** flag.
  58165. */
  58166. abort_due_to_interrupt:
  58167. assert( db->u1.isInterrupted );
  58168. rc = SQLITE_INTERRUPT;
  58169. p->rc = rc;
  58170. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  58171. goto vdbe_error_halt;
  58172. }
  58173. /************** End of vdbe.c ************************************************/
  58174. /************** Begin file vdbeblob.c ****************************************/
  58175. /*
  58176. ** 2007 May 1
  58177. **
  58178. ** The author disclaims copyright to this source code. In place of
  58179. ** a legal notice, here is a blessing:
  58180. **
  58181. ** May you do good and not evil.
  58182. ** May you find forgiveness for yourself and forgive others.
  58183. ** May you share freely, never taking more than you give.
  58184. **
  58185. *************************************************************************
  58186. **
  58187. ** This file contains code used to implement incremental BLOB I/O.
  58188. */
  58189. #ifndef SQLITE_OMIT_INCRBLOB
  58190. /*
  58191. ** Valid sqlite3_blob* handles point to Incrblob structures.
  58192. */
  58193. typedef struct Incrblob Incrblob;
  58194. struct Incrblob {
  58195. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  58196. int nByte; /* Size of open blob, in bytes */
  58197. int iOffset; /* Byte offset of blob in cursor data */
  58198. int iCol; /* Table column this handle is open on */
  58199. BtCursor *pCsr; /* Cursor pointing at blob row */
  58200. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  58201. sqlite3 *db; /* The associated database */
  58202. };
  58203. /*
  58204. ** This function is used by both blob_open() and blob_reopen(). It seeks
  58205. ** the b-tree cursor associated with blob handle p to point to row iRow.
  58206. ** If successful, SQLITE_OK is returned and subsequent calls to
  58207. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  58208. **
  58209. ** If an error occurs, or if the specified row does not exist or does not
  58210. ** contain a value of type TEXT or BLOB in the column nominated when the
  58211. ** blob handle was opened, then an error code is returned and *pzErr may
  58212. ** be set to point to a buffer containing an error message. It is the
  58213. ** responsibility of the caller to free the error message buffer using
  58214. ** sqlite3DbFree().
  58215. **
  58216. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  58217. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  58218. ** immediately return SQLITE_ABORT.
  58219. */
  58220. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  58221. int rc; /* Error code */
  58222. char *zErr = 0; /* Error message */
  58223. Vdbe *v = (Vdbe *)p->pStmt;
  58224. /* Set the value of the SQL statements only variable to integer iRow.
  58225. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  58226. ** triggering asserts related to mutexes.
  58227. */
  58228. assert( v->aVar[0].flags&MEM_Int );
  58229. v->aVar[0].u.i = iRow;
  58230. rc = sqlite3_step(p->pStmt);
  58231. if( rc==SQLITE_ROW ){
  58232. u32 type = v->apCsr[0]->aType[p->iCol];
  58233. if( type<12 ){
  58234. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  58235. type==0?"null": type==7?"real": "integer"
  58236. );
  58237. rc = SQLITE_ERROR;
  58238. sqlite3_finalize(p->pStmt);
  58239. p->pStmt = 0;
  58240. }else{
  58241. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  58242. p->nByte = sqlite3VdbeSerialTypeLen(type);
  58243. p->pCsr = v->apCsr[0]->pCursor;
  58244. sqlite3BtreeEnterCursor(p->pCsr);
  58245. sqlite3BtreeCacheOverflow(p->pCsr);
  58246. sqlite3BtreeLeaveCursor(p->pCsr);
  58247. }
  58248. }
  58249. if( rc==SQLITE_ROW ){
  58250. rc = SQLITE_OK;
  58251. }else if( p->pStmt ){
  58252. rc = sqlite3_finalize(p->pStmt);
  58253. p->pStmt = 0;
  58254. if( rc==SQLITE_OK ){
  58255. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  58256. rc = SQLITE_ERROR;
  58257. }else{
  58258. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  58259. }
  58260. }
  58261. assert( rc!=SQLITE_OK || zErr==0 );
  58262. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  58263. *pzErr = zErr;
  58264. return rc;
  58265. }
  58266. /*
  58267. ** Open a blob handle.
  58268. */
  58269. SQLITE_API int sqlite3_blob_open(
  58270. sqlite3* db, /* The database connection */
  58271. const char *zDb, /* The attached database containing the blob */
  58272. const char *zTable, /* The table containing the blob */
  58273. const char *zColumn, /* The column containing the blob */
  58274. sqlite_int64 iRow, /* The row containing the glob */
  58275. int flags, /* True -> read/write access, false -> read-only */
  58276. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  58277. ){
  58278. int nAttempt = 0;
  58279. int iCol; /* Index of zColumn in row-record */
  58280. /* This VDBE program seeks a btree cursor to the identified
  58281. ** db/table/row entry. The reason for using a vdbe program instead
  58282. ** of writing code to use the b-tree layer directly is that the
  58283. ** vdbe program will take advantage of the various transaction,
  58284. ** locking and error handling infrastructure built into the vdbe.
  58285. **
  58286. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  58287. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  58288. ** uses it to implement the blob_read(), blob_write() and
  58289. ** blob_bytes() functions.
  58290. **
  58291. ** The sqlite3_blob_close() function finalizes the vdbe program,
  58292. ** which closes the b-tree cursor and (possibly) commits the
  58293. ** transaction.
  58294. */
  58295. static const VdbeOpList openBlob[] = {
  58296. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  58297. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  58298. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  58299. /* One of the following two instructions is replaced by an OP_Noop. */
  58300. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  58301. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  58302. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  58303. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  58304. {OP_Column, 0, 0, 1}, /* 7 */
  58305. {OP_ResultRow, 1, 0, 0}, /* 8 */
  58306. {OP_Goto, 0, 5, 0}, /* 9 */
  58307. {OP_Close, 0, 0, 0}, /* 10 */
  58308. {OP_Halt, 0, 0, 0}, /* 11 */
  58309. };
  58310. int rc = SQLITE_OK;
  58311. char *zErr = 0;
  58312. Table *pTab;
  58313. Parse *pParse = 0;
  58314. Incrblob *pBlob = 0;
  58315. flags = !!flags; /* flags = (flags ? 1 : 0); */
  58316. *ppBlob = 0;
  58317. sqlite3_mutex_enter(db->mutex);
  58318. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  58319. if( !pBlob ) goto blob_open_out;
  58320. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  58321. if( !pParse ) goto blob_open_out;
  58322. do {
  58323. memset(pParse, 0, sizeof(Parse));
  58324. pParse->db = db;
  58325. sqlite3DbFree(db, zErr);
  58326. zErr = 0;
  58327. sqlite3BtreeEnterAll(db);
  58328. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  58329. if( pTab && IsVirtual(pTab) ){
  58330. pTab = 0;
  58331. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  58332. }
  58333. #ifndef SQLITE_OMIT_VIEW
  58334. if( pTab && pTab->pSelect ){
  58335. pTab = 0;
  58336. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  58337. }
  58338. #endif
  58339. if( !pTab ){
  58340. if( pParse->zErrMsg ){
  58341. sqlite3DbFree(db, zErr);
  58342. zErr = pParse->zErrMsg;
  58343. pParse->zErrMsg = 0;
  58344. }
  58345. rc = SQLITE_ERROR;
  58346. sqlite3BtreeLeaveAll(db);
  58347. goto blob_open_out;
  58348. }
  58349. /* Now search pTab for the exact column. */
  58350. for(iCol=0; iCol<pTab->nCol; iCol++) {
  58351. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  58352. break;
  58353. }
  58354. }
  58355. if( iCol==pTab->nCol ){
  58356. sqlite3DbFree(db, zErr);
  58357. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  58358. rc = SQLITE_ERROR;
  58359. sqlite3BtreeLeaveAll(db);
  58360. goto blob_open_out;
  58361. }
  58362. /* If the value is being opened for writing, check that the
  58363. ** column is not indexed, and that it is not part of a foreign key.
  58364. ** It is against the rules to open a column to which either of these
  58365. ** descriptions applies for writing. */
  58366. if( flags ){
  58367. const char *zFault = 0;
  58368. Index *pIdx;
  58369. #ifndef SQLITE_OMIT_FOREIGN_KEY
  58370. if( db->flags&SQLITE_ForeignKeys ){
  58371. /* Check that the column is not part of an FK child key definition. It
  58372. ** is not necessary to check if it is part of a parent key, as parent
  58373. ** key columns must be indexed. The check below will pick up this
  58374. ** case. */
  58375. FKey *pFKey;
  58376. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  58377. int j;
  58378. for(j=0; j<pFKey->nCol; j++){
  58379. if( pFKey->aCol[j].iFrom==iCol ){
  58380. zFault = "foreign key";
  58381. }
  58382. }
  58383. }
  58384. }
  58385. #endif
  58386. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  58387. int j;
  58388. for(j=0; j<pIdx->nColumn; j++){
  58389. if( pIdx->aiColumn[j]==iCol ){
  58390. zFault = "indexed";
  58391. }
  58392. }
  58393. }
  58394. if( zFault ){
  58395. sqlite3DbFree(db, zErr);
  58396. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  58397. rc = SQLITE_ERROR;
  58398. sqlite3BtreeLeaveAll(db);
  58399. goto blob_open_out;
  58400. }
  58401. }
  58402. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  58403. assert( pBlob->pStmt || db->mallocFailed );
  58404. if( pBlob->pStmt ){
  58405. Vdbe *v = (Vdbe *)pBlob->pStmt;
  58406. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  58407. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  58408. /* Configure the OP_Transaction */
  58409. sqlite3VdbeChangeP1(v, 0, iDb);
  58410. sqlite3VdbeChangeP2(v, 0, flags);
  58411. /* Configure the OP_VerifyCookie */
  58412. sqlite3VdbeChangeP1(v, 1, iDb);
  58413. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  58414. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  58415. /* Make sure a mutex is held on the table to be accessed */
  58416. sqlite3VdbeUsesBtree(v, iDb);
  58417. /* Configure the OP_TableLock instruction */
  58418. #ifdef SQLITE_OMIT_SHARED_CACHE
  58419. sqlite3VdbeChangeToNoop(v, 2);
  58420. #else
  58421. sqlite3VdbeChangeP1(v, 2, iDb);
  58422. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  58423. sqlite3VdbeChangeP3(v, 2, flags);
  58424. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  58425. #endif
  58426. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  58427. ** parameter of the other to pTab->tnum. */
  58428. sqlite3VdbeChangeToNoop(v, 4 - flags);
  58429. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  58430. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  58431. /* Configure the number of columns. Configure the cursor to
  58432. ** think that the table has one more column than it really
  58433. ** does. An OP_Column to retrieve this imaginary column will
  58434. ** always return an SQL NULL. This is useful because it means
  58435. ** we can invoke OP_Column to fill in the vdbe cursors type
  58436. ** and offset cache without causing any IO.
  58437. */
  58438. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  58439. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  58440. if( !db->mallocFailed ){
  58441. pParse->nVar = 1;
  58442. pParse->nMem = 1;
  58443. pParse->nTab = 1;
  58444. sqlite3VdbeMakeReady(v, pParse);
  58445. }
  58446. }
  58447. pBlob->flags = flags;
  58448. pBlob->iCol = iCol;
  58449. pBlob->db = db;
  58450. sqlite3BtreeLeaveAll(db);
  58451. if( db->mallocFailed ){
  58452. goto blob_open_out;
  58453. }
  58454. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  58455. rc = blobSeekToRow(pBlob, iRow, &zErr);
  58456. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  58457. blob_open_out:
  58458. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  58459. *ppBlob = (sqlite3_blob *)pBlob;
  58460. }else{
  58461. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  58462. sqlite3DbFree(db, pBlob);
  58463. }
  58464. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  58465. sqlite3DbFree(db, zErr);
  58466. sqlite3StackFree(db, pParse);
  58467. rc = sqlite3ApiExit(db, rc);
  58468. sqlite3_mutex_leave(db->mutex);
  58469. return rc;
  58470. }
  58471. /*
  58472. ** Close a blob handle that was previously created using
  58473. ** sqlite3_blob_open().
  58474. */
  58475. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  58476. Incrblob *p = (Incrblob *)pBlob;
  58477. int rc;
  58478. sqlite3 *db;
  58479. if( p ){
  58480. db = p->db;
  58481. sqlite3_mutex_enter(db->mutex);
  58482. rc = sqlite3_finalize(p->pStmt);
  58483. sqlite3DbFree(db, p);
  58484. sqlite3_mutex_leave(db->mutex);
  58485. }else{
  58486. rc = SQLITE_OK;
  58487. }
  58488. return rc;
  58489. }
  58490. /*
  58491. ** Perform a read or write operation on a blob
  58492. */
  58493. static int blobReadWrite(
  58494. sqlite3_blob *pBlob,
  58495. void *z,
  58496. int n,
  58497. int iOffset,
  58498. int (*xCall)(BtCursor*, u32, u32, void*)
  58499. ){
  58500. int rc;
  58501. Incrblob *p = (Incrblob *)pBlob;
  58502. Vdbe *v;
  58503. sqlite3 *db;
  58504. if( p==0 ) return SQLITE_MISUSE_BKPT;
  58505. db = p->db;
  58506. sqlite3_mutex_enter(db->mutex);
  58507. v = (Vdbe*)p->pStmt;
  58508. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  58509. /* Request is out of range. Return a transient error. */
  58510. rc = SQLITE_ERROR;
  58511. sqlite3Error(db, SQLITE_ERROR, 0);
  58512. }else if( v==0 ){
  58513. /* If there is no statement handle, then the blob-handle has
  58514. ** already been invalidated. Return SQLITE_ABORT in this case.
  58515. */
  58516. rc = SQLITE_ABORT;
  58517. }else{
  58518. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  58519. ** returned, clean-up the statement handle.
  58520. */
  58521. assert( db == v->db );
  58522. sqlite3BtreeEnterCursor(p->pCsr);
  58523. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  58524. sqlite3BtreeLeaveCursor(p->pCsr);
  58525. if( rc==SQLITE_ABORT ){
  58526. sqlite3VdbeFinalize(v);
  58527. p->pStmt = 0;
  58528. }else{
  58529. db->errCode = rc;
  58530. v->rc = rc;
  58531. }
  58532. }
  58533. rc = sqlite3ApiExit(db, rc);
  58534. sqlite3_mutex_leave(db->mutex);
  58535. return rc;
  58536. }
  58537. /*
  58538. ** Read data from a blob handle.
  58539. */
  58540. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  58541. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  58542. }
  58543. /*
  58544. ** Write data to a blob handle.
  58545. */
  58546. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  58547. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  58548. }
  58549. /*
  58550. ** Query a blob handle for the size of the data.
  58551. **
  58552. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  58553. ** so no mutex is required for access.
  58554. */
  58555. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  58556. Incrblob *p = (Incrblob *)pBlob;
  58557. return (p && p->pStmt) ? p->nByte : 0;
  58558. }
  58559. /*
  58560. ** Move an existing blob handle to point to a different row of the same
  58561. ** database table.
  58562. **
  58563. ** If an error occurs, or if the specified row does not exist or does not
  58564. ** contain a blob or text value, then an error code is returned and the
  58565. ** database handle error code and message set. If this happens, then all
  58566. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  58567. ** immediately return SQLITE_ABORT.
  58568. */
  58569. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  58570. int rc;
  58571. Incrblob *p = (Incrblob *)pBlob;
  58572. sqlite3 *db;
  58573. if( p==0 ) return SQLITE_MISUSE_BKPT;
  58574. db = p->db;
  58575. sqlite3_mutex_enter(db->mutex);
  58576. if( p->pStmt==0 ){
  58577. /* If there is no statement handle, then the blob-handle has
  58578. ** already been invalidated. Return SQLITE_ABORT in this case.
  58579. */
  58580. rc = SQLITE_ABORT;
  58581. }else{
  58582. char *zErr;
  58583. rc = blobSeekToRow(p, iRow, &zErr);
  58584. if( rc!=SQLITE_OK ){
  58585. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  58586. sqlite3DbFree(db, zErr);
  58587. }
  58588. assert( rc!=SQLITE_SCHEMA );
  58589. }
  58590. rc = sqlite3ApiExit(db, rc);
  58591. assert( rc==SQLITE_OK || p->pStmt==0 );
  58592. sqlite3_mutex_leave(db->mutex);
  58593. return rc;
  58594. }
  58595. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  58596. /************** End of vdbeblob.c ********************************************/
  58597. /************** Begin file vdbesort.c ****************************************/
  58598. /*
  58599. ** 2011 July 9
  58600. **
  58601. ** The author disclaims copyright to this source code. In place of
  58602. ** a legal notice, here is a blessing:
  58603. **
  58604. ** May you do good and not evil.
  58605. ** May you find forgiveness for yourself and forgive others.
  58606. ** May you share freely, never taking more than you give.
  58607. **
  58608. *************************************************************************
  58609. ** This file contains code for the VdbeSorter object, used in concert with
  58610. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  58611. ** example, by CREATE INDEX statements on tables too large to fit in main
  58612. ** memory).
  58613. */
  58614. typedef struct VdbeSorterIter VdbeSorterIter;
  58615. typedef struct SorterRecord SorterRecord;
  58616. typedef struct FileWriter FileWriter;
  58617. /*
  58618. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  58619. **
  58620. ** As keys are added to the sorter, they are written to disk in a series
  58621. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  58622. ** the same as the cache-size allowed for temporary databases. In order
  58623. ** to allow the caller to extract keys from the sorter in sorted order,
  58624. ** all PMAs currently stored on disk must be merged together. This comment
  58625. ** describes the data structure used to do so. The structure supports
  58626. ** merging any number of arrays in a single pass with no redundant comparison
  58627. ** operations.
  58628. **
  58629. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  58630. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  58631. ** the purposes of the paragraphs below, we assume that the array is actually
  58632. ** N elements in size, where N is the smallest power of 2 greater to or equal
  58633. ** to the number of iterators being merged. The extra aIter[] elements are
  58634. ** treated as if they are empty (always at EOF).
  58635. **
  58636. ** The aTree[] array is also N elements in size. The value of N is stored in
  58637. ** the VdbeSorter.nTree variable.
  58638. **
  58639. ** The final (N/2) elements of aTree[] contain the results of comparing
  58640. ** pairs of iterator keys together. Element i contains the result of
  58641. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  58642. ** aTree element is set to the index of it.
  58643. **
  58644. ** For the purposes of this comparison, EOF is considered greater than any
  58645. ** other key value. If the keys are equal (only possible with two EOF
  58646. ** values), it doesn't matter which index is stored.
  58647. **
  58648. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  58649. ** above contains the index of the smallest of each block of 4 iterators.
  58650. ** And so on. So that aTree[1] contains the index of the iterator that
  58651. ** currently points to the smallest key value. aTree[0] is unused.
  58652. **
  58653. ** Example:
  58654. **
  58655. ** aIter[0] -> Banana
  58656. ** aIter[1] -> Feijoa
  58657. ** aIter[2] -> Elderberry
  58658. ** aIter[3] -> Currant
  58659. ** aIter[4] -> Grapefruit
  58660. ** aIter[5] -> Apple
  58661. ** aIter[6] -> Durian
  58662. ** aIter[7] -> EOF
  58663. **
  58664. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  58665. **
  58666. ** The current element is "Apple" (the value of the key indicated by
  58667. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  58668. ** be advanced to the next key in its segment. Say the next key is
  58669. ** "Eggplant":
  58670. **
  58671. ** aIter[5] -> Eggplant
  58672. **
  58673. ** The contents of aTree[] are updated first by comparing the new iterator
  58674. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  58675. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  58676. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  58677. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  58678. ** so the value written into element 1 of the array is 0. As follows:
  58679. **
  58680. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  58681. **
  58682. ** In other words, each time we advance to the next sorter element, log2(N)
  58683. ** key comparison operations are required, where N is the number of segments
  58684. ** being merged (rounded up to the next power of 2).
  58685. */
  58686. struct VdbeSorter {
  58687. i64 iWriteOff; /* Current write offset within file pTemp1 */
  58688. i64 iReadOff; /* Current read offset within file pTemp1 */
  58689. int nInMemory; /* Current size of pRecord list as PMA */
  58690. int nTree; /* Used size of aTree/aIter (power of 2) */
  58691. int nPMA; /* Number of PMAs stored in pTemp1 */
  58692. int mnPmaSize; /* Minimum PMA size, in bytes */
  58693. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  58694. VdbeSorterIter *aIter; /* Array of iterators to merge */
  58695. int *aTree; /* Current state of incremental merge */
  58696. sqlite3_file *pTemp1; /* PMA file 1 */
  58697. SorterRecord *pRecord; /* Head of in-memory record list */
  58698. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  58699. };
  58700. /*
  58701. ** The following type is an iterator for a PMA. It caches the current key in
  58702. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  58703. */
  58704. struct VdbeSorterIter {
  58705. i64 iReadOff; /* Current read offset */
  58706. i64 iEof; /* 1 byte past EOF for this iterator */
  58707. int nAlloc; /* Bytes of space at aAlloc */
  58708. int nKey; /* Number of bytes in key */
  58709. sqlite3_file *pFile; /* File iterator is reading from */
  58710. u8 *aAlloc; /* Allocated space */
  58711. u8 *aKey; /* Pointer to current key */
  58712. u8 *aBuffer; /* Current read buffer */
  58713. int nBuffer; /* Size of read buffer in bytes */
  58714. };
  58715. /*
  58716. ** An instance of this structure is used to organize the stream of records
  58717. ** being written to files by the merge-sort code into aligned, page-sized
  58718. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  58719. ** faster on many operating systems.
  58720. */
  58721. struct FileWriter {
  58722. int eFWErr; /* Non-zero if in an error state */
  58723. u8 *aBuffer; /* Pointer to write buffer */
  58724. int nBuffer; /* Size of write buffer in bytes */
  58725. int iBufStart; /* First byte of buffer to write */
  58726. int iBufEnd; /* Last byte of buffer to write */
  58727. i64 iWriteOff; /* Offset of start of buffer in file */
  58728. sqlite3_file *pFile; /* File to write to */
  58729. };
  58730. /*
  58731. ** A structure to store a single record. All in-memory records are connected
  58732. ** together into a linked list headed at VdbeSorter.pRecord using the
  58733. ** SorterRecord.pNext pointer.
  58734. */
  58735. struct SorterRecord {
  58736. void *pVal;
  58737. int nVal;
  58738. SorterRecord *pNext;
  58739. };
  58740. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  58741. #define SORTER_MIN_WORKING 10
  58742. /* Maximum number of segments to merge in a single pass. */
  58743. #define SORTER_MAX_MERGE_COUNT 16
  58744. /*
  58745. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  58746. ** argument. All structure fields are set to zero before returning.
  58747. */
  58748. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  58749. sqlite3DbFree(db, pIter->aAlloc);
  58750. sqlite3DbFree(db, pIter->aBuffer);
  58751. memset(pIter, 0, sizeof(VdbeSorterIter));
  58752. }
  58753. /*
  58754. ** Read nByte bytes of data from the stream of data iterated by object p.
  58755. ** If successful, set *ppOut to point to a buffer containing the data
  58756. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  58757. ** error code.
  58758. **
  58759. ** The buffer indicated by *ppOut may only be considered valid until the
  58760. ** next call to this function.
  58761. */
  58762. static int vdbeSorterIterRead(
  58763. sqlite3 *db, /* Database handle (for malloc) */
  58764. VdbeSorterIter *p, /* Iterator */
  58765. int nByte, /* Bytes of data to read */
  58766. u8 **ppOut /* OUT: Pointer to buffer containing data */
  58767. ){
  58768. int iBuf; /* Offset within buffer to read from */
  58769. int nAvail; /* Bytes of data available in buffer */
  58770. assert( p->aBuffer );
  58771. /* If there is no more data to be read from the buffer, read the next
  58772. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  58773. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  58774. iBuf = p->iReadOff % p->nBuffer;
  58775. if( iBuf==0 ){
  58776. int nRead; /* Bytes to read from disk */
  58777. int rc; /* sqlite3OsRead() return code */
  58778. /* Determine how many bytes of data to read. */
  58779. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  58780. nRead = p->nBuffer;
  58781. }else{
  58782. nRead = (int)(p->iEof - p->iReadOff);
  58783. }
  58784. assert( nRead>0 );
  58785. /* Read data from the file. Return early if an error occurs. */
  58786. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  58787. assert( rc!=SQLITE_IOERR_SHORT_READ );
  58788. if( rc!=SQLITE_OK ) return rc;
  58789. }
  58790. nAvail = p->nBuffer - iBuf;
  58791. if( nByte<=nAvail ){
  58792. /* The requested data is available in the in-memory buffer. In this
  58793. ** case there is no need to make a copy of the data, just return a
  58794. ** pointer into the buffer to the caller. */
  58795. *ppOut = &p->aBuffer[iBuf];
  58796. p->iReadOff += nByte;
  58797. }else{
  58798. /* The requested data is not all available in the in-memory buffer.
  58799. ** In this case, allocate space at p->aAlloc[] to copy the requested
  58800. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  58801. int nRem; /* Bytes remaining to copy */
  58802. /* Extend the p->aAlloc[] allocation if required. */
  58803. if( p->nAlloc<nByte ){
  58804. int nNew = p->nAlloc*2;
  58805. while( nByte>nNew ) nNew = nNew*2;
  58806. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  58807. if( !p->aAlloc ) return SQLITE_NOMEM;
  58808. p->nAlloc = nNew;
  58809. }
  58810. /* Copy as much data as is available in the buffer into the start of
  58811. ** p->aAlloc[]. */
  58812. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  58813. p->iReadOff += nAvail;
  58814. nRem = nByte - nAvail;
  58815. /* The following loop copies up to p->nBuffer bytes per iteration into
  58816. ** the p->aAlloc[] buffer. */
  58817. while( nRem>0 ){
  58818. int rc; /* vdbeSorterIterRead() return code */
  58819. int nCopy; /* Number of bytes to copy */
  58820. u8 *aNext; /* Pointer to buffer to copy data from */
  58821. nCopy = nRem;
  58822. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  58823. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  58824. if( rc!=SQLITE_OK ) return rc;
  58825. assert( aNext!=p->aAlloc );
  58826. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  58827. nRem -= nCopy;
  58828. }
  58829. *ppOut = p->aAlloc;
  58830. }
  58831. return SQLITE_OK;
  58832. }
  58833. /*
  58834. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  58835. ** the value read.
  58836. */
  58837. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  58838. int iBuf;
  58839. iBuf = p->iReadOff % p->nBuffer;
  58840. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  58841. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  58842. }else{
  58843. u8 aVarint[16], *a;
  58844. int i = 0, rc;
  58845. do{
  58846. rc = vdbeSorterIterRead(db, p, 1, &a);
  58847. if( rc ) return rc;
  58848. aVarint[(i++)&0xf] = a[0];
  58849. }while( (a[0]&0x80)!=0 );
  58850. sqlite3GetVarint(aVarint, pnOut);
  58851. }
  58852. return SQLITE_OK;
  58853. }
  58854. /*
  58855. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  58856. ** no error occurs, or an SQLite error code if one does.
  58857. */
  58858. static int vdbeSorterIterNext(
  58859. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  58860. VdbeSorterIter *pIter /* Iterator to advance */
  58861. ){
  58862. int rc; /* Return Code */
  58863. u64 nRec = 0; /* Size of record in bytes */
  58864. if( pIter->iReadOff>=pIter->iEof ){
  58865. /* This is an EOF condition */
  58866. vdbeSorterIterZero(db, pIter);
  58867. return SQLITE_OK;
  58868. }
  58869. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  58870. if( rc==SQLITE_OK ){
  58871. pIter->nKey = (int)nRec;
  58872. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  58873. }
  58874. return rc;
  58875. }
  58876. /*
  58877. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  58878. ** starting at offset iStart and ending at offset iEof-1. This function
  58879. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  58880. ** PMA is empty).
  58881. */
  58882. static int vdbeSorterIterInit(
  58883. sqlite3 *db, /* Database handle */
  58884. const VdbeSorter *pSorter, /* Sorter object */
  58885. i64 iStart, /* Start offset in pFile */
  58886. VdbeSorterIter *pIter, /* Iterator to populate */
  58887. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  58888. ){
  58889. int rc = SQLITE_OK;
  58890. int nBuf;
  58891. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  58892. assert( pSorter->iWriteOff>iStart );
  58893. assert( pIter->aAlloc==0 );
  58894. assert( pIter->aBuffer==0 );
  58895. pIter->pFile = pSorter->pTemp1;
  58896. pIter->iReadOff = iStart;
  58897. pIter->nAlloc = 128;
  58898. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  58899. pIter->nBuffer = nBuf;
  58900. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  58901. if( !pIter->aBuffer ){
  58902. rc = SQLITE_NOMEM;
  58903. }else{
  58904. int iBuf;
  58905. iBuf = iStart % nBuf;
  58906. if( iBuf ){
  58907. int nRead = nBuf - iBuf;
  58908. if( (iStart + nRead) > pSorter->iWriteOff ){
  58909. nRead = (int)(pSorter->iWriteOff - iStart);
  58910. }
  58911. rc = sqlite3OsRead(
  58912. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  58913. );
  58914. assert( rc!=SQLITE_IOERR_SHORT_READ );
  58915. }
  58916. if( rc==SQLITE_OK ){
  58917. u64 nByte; /* Size of PMA in bytes */
  58918. pIter->iEof = pSorter->iWriteOff;
  58919. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  58920. pIter->iEof = pIter->iReadOff + nByte;
  58921. *pnByte += nByte;
  58922. }
  58923. }
  58924. if( rc==SQLITE_OK ){
  58925. rc = vdbeSorterIterNext(db, pIter);
  58926. }
  58927. return rc;
  58928. }
  58929. /*
  58930. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  58931. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  58932. ** used by the comparison. If an error occurs, return an SQLite error code.
  58933. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  58934. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  58935. **
  58936. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  58937. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  58938. ** is true and key1 contains even a single NULL value, it is considered to
  58939. ** be less than key2. Even if key2 also contains NULL values.
  58940. **
  58941. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  58942. ** has been allocated and contains an unpacked record that is used as key2.
  58943. */
  58944. static void vdbeSorterCompare(
  58945. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  58946. int bOmitRowid, /* Ignore rowid field at end of keys */
  58947. const void *pKey1, int nKey1, /* Left side of comparison */
  58948. const void *pKey2, int nKey2, /* Right side of comparison */
  58949. int *pRes /* OUT: Result of comparison */
  58950. ){
  58951. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  58952. VdbeSorter *pSorter = pCsr->pSorter;
  58953. UnpackedRecord *r2 = pSorter->pUnpacked;
  58954. int i;
  58955. if( pKey2 ){
  58956. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  58957. }
  58958. if( bOmitRowid ){
  58959. r2->nField = pKeyInfo->nField;
  58960. assert( r2->nField>0 );
  58961. for(i=0; i<r2->nField; i++){
  58962. if( r2->aMem[i].flags & MEM_Null ){
  58963. *pRes = -1;
  58964. return;
  58965. }
  58966. }
  58967. r2->flags |= UNPACKED_PREFIX_MATCH;
  58968. }
  58969. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  58970. }
  58971. /*
  58972. ** This function is called to compare two iterator keys when merging
  58973. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  58974. ** value to recalculate.
  58975. */
  58976. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  58977. VdbeSorter *pSorter = pCsr->pSorter;
  58978. int i1;
  58979. int i2;
  58980. int iRes;
  58981. VdbeSorterIter *p1;
  58982. VdbeSorterIter *p2;
  58983. assert( iOut<pSorter->nTree && iOut>0 );
  58984. if( iOut>=(pSorter->nTree/2) ){
  58985. i1 = (iOut - pSorter->nTree/2) * 2;
  58986. i2 = i1 + 1;
  58987. }else{
  58988. i1 = pSorter->aTree[iOut*2];
  58989. i2 = pSorter->aTree[iOut*2+1];
  58990. }
  58991. p1 = &pSorter->aIter[i1];
  58992. p2 = &pSorter->aIter[i2];
  58993. if( p1->pFile==0 ){
  58994. iRes = i2;
  58995. }else if( p2->pFile==0 ){
  58996. iRes = i1;
  58997. }else{
  58998. int res;
  58999. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  59000. vdbeSorterCompare(
  59001. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  59002. );
  59003. if( res<=0 ){
  59004. iRes = i1;
  59005. }else{
  59006. iRes = i2;
  59007. }
  59008. }
  59009. pSorter->aTree[iOut] = iRes;
  59010. return SQLITE_OK;
  59011. }
  59012. /*
  59013. ** Initialize the temporary index cursor just opened as a sorter cursor.
  59014. */
  59015. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  59016. int pgsz; /* Page size of main database */
  59017. int mxCache; /* Cache size */
  59018. VdbeSorter *pSorter; /* The new sorter */
  59019. char *d; /* Dummy */
  59020. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  59021. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  59022. if( pSorter==0 ){
  59023. return SQLITE_NOMEM;
  59024. }
  59025. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  59026. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  59027. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  59028. if( !sqlite3TempInMemory(db) ){
  59029. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  59030. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  59031. mxCache = db->aDb[0].pSchema->cache_size;
  59032. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  59033. pSorter->mxPmaSize = mxCache * pgsz;
  59034. }
  59035. return SQLITE_OK;
  59036. }
  59037. /*
  59038. ** Free the list of sorted records starting at pRecord.
  59039. */
  59040. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  59041. SorterRecord *p;
  59042. SorterRecord *pNext;
  59043. for(p=pRecord; p; p=pNext){
  59044. pNext = p->pNext;
  59045. sqlite3DbFree(db, p);
  59046. }
  59047. }
  59048. /*
  59049. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  59050. */
  59051. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  59052. VdbeSorter *pSorter = pCsr->pSorter;
  59053. if( pSorter ){
  59054. if( pSorter->aIter ){
  59055. int i;
  59056. for(i=0; i<pSorter->nTree; i++){
  59057. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  59058. }
  59059. sqlite3DbFree(db, pSorter->aIter);
  59060. }
  59061. if( pSorter->pTemp1 ){
  59062. sqlite3OsCloseFree(pSorter->pTemp1);
  59063. }
  59064. vdbeSorterRecordFree(db, pSorter->pRecord);
  59065. sqlite3DbFree(db, pSorter->pUnpacked);
  59066. sqlite3DbFree(db, pSorter);
  59067. pCsr->pSorter = 0;
  59068. }
  59069. }
  59070. /*
  59071. ** Allocate space for a file-handle and open a temporary file. If successful,
  59072. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  59073. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  59074. */
  59075. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  59076. int dummy;
  59077. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  59078. SQLITE_OPEN_TEMP_JOURNAL |
  59079. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  59080. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  59081. );
  59082. }
  59083. /*
  59084. ** Merge the two sorted lists p1 and p2 into a single list.
  59085. ** Set *ppOut to the head of the new list.
  59086. */
  59087. static void vdbeSorterMerge(
  59088. const VdbeCursor *pCsr, /* For pKeyInfo */
  59089. SorterRecord *p1, /* First list to merge */
  59090. SorterRecord *p2, /* Second list to merge */
  59091. SorterRecord **ppOut /* OUT: Head of merged list */
  59092. ){
  59093. SorterRecord *pFinal = 0;
  59094. SorterRecord **pp = &pFinal;
  59095. void *pVal2 = p2 ? p2->pVal : 0;
  59096. while( p1 && p2 ){
  59097. int res;
  59098. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  59099. if( res<=0 ){
  59100. *pp = p1;
  59101. pp = &p1->pNext;
  59102. p1 = p1->pNext;
  59103. pVal2 = 0;
  59104. }else{
  59105. *pp = p2;
  59106. pp = &p2->pNext;
  59107. p2 = p2->pNext;
  59108. if( p2==0 ) break;
  59109. pVal2 = p2->pVal;
  59110. }
  59111. }
  59112. *pp = p1 ? p1 : p2;
  59113. *ppOut = pFinal;
  59114. }
  59115. /*
  59116. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  59117. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  59118. ** occurs.
  59119. */
  59120. static int vdbeSorterSort(const VdbeCursor *pCsr){
  59121. int i;
  59122. SorterRecord **aSlot;
  59123. SorterRecord *p;
  59124. VdbeSorter *pSorter = pCsr->pSorter;
  59125. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  59126. if( !aSlot ){
  59127. return SQLITE_NOMEM;
  59128. }
  59129. p = pSorter->pRecord;
  59130. while( p ){
  59131. SorterRecord *pNext = p->pNext;
  59132. p->pNext = 0;
  59133. for(i=0; aSlot[i]; i++){
  59134. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  59135. aSlot[i] = 0;
  59136. }
  59137. aSlot[i] = p;
  59138. p = pNext;
  59139. }
  59140. p = 0;
  59141. for(i=0; i<64; i++){
  59142. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  59143. }
  59144. pSorter->pRecord = p;
  59145. sqlite3_free(aSlot);
  59146. return SQLITE_OK;
  59147. }
  59148. /*
  59149. ** Initialize a file-writer object.
  59150. */
  59151. static void fileWriterInit(
  59152. sqlite3 *db, /* Database (for malloc) */
  59153. sqlite3_file *pFile, /* File to write to */
  59154. FileWriter *p, /* Object to populate */
  59155. i64 iStart /* Offset of pFile to begin writing at */
  59156. ){
  59157. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  59158. memset(p, 0, sizeof(FileWriter));
  59159. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  59160. if( !p->aBuffer ){
  59161. p->eFWErr = SQLITE_NOMEM;
  59162. }else{
  59163. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  59164. p->iWriteOff = iStart - p->iBufStart;
  59165. p->nBuffer = nBuf;
  59166. p->pFile = pFile;
  59167. }
  59168. }
  59169. /*
  59170. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  59171. ** if successful, or an SQLite error code if an error occurs.
  59172. */
  59173. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  59174. int nRem = nData;
  59175. while( nRem>0 && p->eFWErr==0 ){
  59176. int nCopy = nRem;
  59177. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  59178. nCopy = p->nBuffer - p->iBufEnd;
  59179. }
  59180. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  59181. p->iBufEnd += nCopy;
  59182. if( p->iBufEnd==p->nBuffer ){
  59183. p->eFWErr = sqlite3OsWrite(p->pFile,
  59184. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  59185. p->iWriteOff + p->iBufStart
  59186. );
  59187. p->iBufStart = p->iBufEnd = 0;
  59188. p->iWriteOff += p->nBuffer;
  59189. }
  59190. assert( p->iBufEnd<p->nBuffer );
  59191. nRem -= nCopy;
  59192. }
  59193. }
  59194. /*
  59195. ** Flush any buffered data to disk and clean up the file-writer object.
  59196. ** The results of using the file-writer after this call are undefined.
  59197. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  59198. ** required. Otherwise, return an SQLite error code.
  59199. **
  59200. ** Before returning, set *piEof to the offset immediately following the
  59201. ** last byte written to the file.
  59202. */
  59203. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  59204. int rc;
  59205. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  59206. p->eFWErr = sqlite3OsWrite(p->pFile,
  59207. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  59208. p->iWriteOff + p->iBufStart
  59209. );
  59210. }
  59211. *piEof = (p->iWriteOff + p->iBufEnd);
  59212. sqlite3DbFree(db, p->aBuffer);
  59213. rc = p->eFWErr;
  59214. memset(p, 0, sizeof(FileWriter));
  59215. return rc;
  59216. }
  59217. /*
  59218. ** Write value iVal encoded as a varint to the file-write object. Return
  59219. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  59220. */
  59221. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  59222. int nByte;
  59223. u8 aByte[10];
  59224. nByte = sqlite3PutVarint(aByte, iVal);
  59225. fileWriterWrite(p, aByte, nByte);
  59226. }
  59227. /*
  59228. ** Write the current contents of the in-memory linked-list to a PMA. Return
  59229. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  59230. **
  59231. ** The format of a PMA is:
  59232. **
  59233. ** * A varint. This varint contains the total number of bytes of content
  59234. ** in the PMA (not including the varint itself).
  59235. **
  59236. ** * One or more records packed end-to-end in order of ascending keys.
  59237. ** Each record consists of a varint followed by a blob of data (the
  59238. ** key). The varint is the number of bytes in the blob of data.
  59239. */
  59240. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  59241. int rc = SQLITE_OK; /* Return code */
  59242. VdbeSorter *pSorter = pCsr->pSorter;
  59243. FileWriter writer;
  59244. memset(&writer, 0, sizeof(FileWriter));
  59245. if( pSorter->nInMemory==0 ){
  59246. assert( pSorter->pRecord==0 );
  59247. return rc;
  59248. }
  59249. rc = vdbeSorterSort(pCsr);
  59250. /* If the first temporary PMA file has not been opened, open it now. */
  59251. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  59252. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  59253. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  59254. assert( pSorter->iWriteOff==0 );
  59255. assert( pSorter->nPMA==0 );
  59256. }
  59257. if( rc==SQLITE_OK ){
  59258. SorterRecord *p;
  59259. SorterRecord *pNext = 0;
  59260. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  59261. pSorter->nPMA++;
  59262. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  59263. for(p=pSorter->pRecord; p; p=pNext){
  59264. pNext = p->pNext;
  59265. fileWriterWriteVarint(&writer, p->nVal);
  59266. fileWriterWrite(&writer, p->pVal, p->nVal);
  59267. sqlite3DbFree(db, p);
  59268. }
  59269. pSorter->pRecord = p;
  59270. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  59271. }
  59272. return rc;
  59273. }
  59274. /*
  59275. ** Add a record to the sorter.
  59276. */
  59277. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  59278. sqlite3 *db, /* Database handle */
  59279. const VdbeCursor *pCsr, /* Sorter cursor */
  59280. Mem *pVal /* Memory cell containing record */
  59281. ){
  59282. VdbeSorter *pSorter = pCsr->pSorter;
  59283. int rc = SQLITE_OK; /* Return Code */
  59284. SorterRecord *pNew; /* New list element */
  59285. assert( pSorter );
  59286. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  59287. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  59288. if( pNew==0 ){
  59289. rc = SQLITE_NOMEM;
  59290. }else{
  59291. pNew->pVal = (void *)&pNew[1];
  59292. memcpy(pNew->pVal, pVal->z, pVal->n);
  59293. pNew->nVal = pVal->n;
  59294. pNew->pNext = pSorter->pRecord;
  59295. pSorter->pRecord = pNew;
  59296. }
  59297. /* See if the contents of the sorter should now be written out. They
  59298. ** are written out when either of the following are true:
  59299. **
  59300. ** * The total memory allocated for the in-memory list is greater
  59301. ** than (page-size * cache-size), or
  59302. **
  59303. ** * The total memory allocated for the in-memory list is greater
  59304. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  59305. */
  59306. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  59307. (pSorter->nInMemory>pSorter->mxPmaSize)
  59308. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  59309. )){
  59310. #ifdef SQLITE_DEBUG
  59311. i64 nExpect = pSorter->iWriteOff
  59312. + sqlite3VarintLen(pSorter->nInMemory)
  59313. + pSorter->nInMemory;
  59314. #endif
  59315. rc = vdbeSorterListToPMA(db, pCsr);
  59316. pSorter->nInMemory = 0;
  59317. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  59318. }
  59319. return rc;
  59320. }
  59321. /*
  59322. ** Helper function for sqlite3VdbeSorterRewind().
  59323. */
  59324. static int vdbeSorterInitMerge(
  59325. sqlite3 *db, /* Database handle */
  59326. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  59327. i64 *pnByte /* Sum of bytes in all opened PMAs */
  59328. ){
  59329. VdbeSorter *pSorter = pCsr->pSorter;
  59330. int rc = SQLITE_OK; /* Return code */
  59331. int i; /* Used to iterator through aIter[] */
  59332. i64 nByte = 0; /* Total bytes in all opened PMAs */
  59333. /* Initialize the iterators. */
  59334. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  59335. VdbeSorterIter *pIter = &pSorter->aIter[i];
  59336. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  59337. pSorter->iReadOff = pIter->iEof;
  59338. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  59339. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  59340. }
  59341. /* Initialize the aTree[] array. */
  59342. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  59343. rc = vdbeSorterDoCompare(pCsr, i);
  59344. }
  59345. *pnByte = nByte;
  59346. return rc;
  59347. }
  59348. /*
  59349. ** Once the sorter has been populated, this function is called to prepare
  59350. ** for iterating through its contents in sorted order.
  59351. */
  59352. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  59353. VdbeSorter *pSorter = pCsr->pSorter;
  59354. int rc; /* Return code */
  59355. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  59356. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  59357. int nIter; /* Number of iterators used */
  59358. int nByte; /* Bytes of space required for aIter/aTree */
  59359. int N = 2; /* Power of 2 >= nIter */
  59360. assert( pSorter );
  59361. /* If no data has been written to disk, then do not do so now. Instead,
  59362. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  59363. ** from the in-memory list. */
  59364. if( pSorter->nPMA==0 ){
  59365. *pbEof = !pSorter->pRecord;
  59366. assert( pSorter->aTree==0 );
  59367. return vdbeSorterSort(pCsr);
  59368. }
  59369. /* Write the current in-memory list to a PMA. */
  59370. rc = vdbeSorterListToPMA(db, pCsr);
  59371. if( rc!=SQLITE_OK ) return rc;
  59372. /* Allocate space for aIter[] and aTree[]. */
  59373. nIter = pSorter->nPMA;
  59374. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  59375. assert( nIter>0 );
  59376. while( N<nIter ) N += N;
  59377. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  59378. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  59379. if( !pSorter->aIter ) return SQLITE_NOMEM;
  59380. pSorter->aTree = (int *)&pSorter->aIter[N];
  59381. pSorter->nTree = N;
  59382. do {
  59383. int iNew; /* Index of new, merged, PMA */
  59384. for(iNew=0;
  59385. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  59386. iNew++
  59387. ){
  59388. int rc2; /* Return code from fileWriterFinish() */
  59389. FileWriter writer; /* Object used to write to disk */
  59390. i64 nWrite; /* Number of bytes in new PMA */
  59391. memset(&writer, 0, sizeof(FileWriter));
  59392. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  59393. ** initialize an iterator for each of them and break out of the loop.
  59394. ** These iterators will be incrementally merged as the VDBE layer calls
  59395. ** sqlite3VdbeSorterNext().
  59396. **
  59397. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  59398. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  59399. ** are merged into a single PMA that is written to file pTemp2.
  59400. */
  59401. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  59402. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  59403. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  59404. break;
  59405. }
  59406. /* Open the second temp file, if it is not already open. */
  59407. if( pTemp2==0 ){
  59408. assert( iWrite2==0 );
  59409. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  59410. }
  59411. if( rc==SQLITE_OK ){
  59412. int bEof = 0;
  59413. fileWriterInit(db, pTemp2, &writer, iWrite2);
  59414. fileWriterWriteVarint(&writer, nWrite);
  59415. while( rc==SQLITE_OK && bEof==0 ){
  59416. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  59417. assert( pIter->pFile );
  59418. fileWriterWriteVarint(&writer, pIter->nKey);
  59419. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  59420. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  59421. }
  59422. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  59423. if( rc==SQLITE_OK ) rc = rc2;
  59424. }
  59425. }
  59426. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  59427. break;
  59428. }else{
  59429. sqlite3_file *pTmp = pSorter->pTemp1;
  59430. pSorter->nPMA = iNew;
  59431. pSorter->pTemp1 = pTemp2;
  59432. pTemp2 = pTmp;
  59433. pSorter->iWriteOff = iWrite2;
  59434. pSorter->iReadOff = 0;
  59435. iWrite2 = 0;
  59436. }
  59437. }while( rc==SQLITE_OK );
  59438. if( pTemp2 ){
  59439. sqlite3OsCloseFree(pTemp2);
  59440. }
  59441. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  59442. return rc;
  59443. }
  59444. /*
  59445. ** Advance to the next element in the sorter.
  59446. */
  59447. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  59448. VdbeSorter *pSorter = pCsr->pSorter;
  59449. int rc; /* Return code */
  59450. if( pSorter->aTree ){
  59451. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  59452. int i; /* Index of aTree[] to recalculate */
  59453. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  59454. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  59455. rc = vdbeSorterDoCompare(pCsr, i);
  59456. }
  59457. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  59458. }else{
  59459. SorterRecord *pFree = pSorter->pRecord;
  59460. pSorter->pRecord = pFree->pNext;
  59461. pFree->pNext = 0;
  59462. vdbeSorterRecordFree(db, pFree);
  59463. *pbEof = !pSorter->pRecord;
  59464. rc = SQLITE_OK;
  59465. }
  59466. return rc;
  59467. }
  59468. /*
  59469. ** Return a pointer to a buffer owned by the sorter that contains the
  59470. ** current key.
  59471. */
  59472. static void *vdbeSorterRowkey(
  59473. const VdbeSorter *pSorter, /* Sorter object */
  59474. int *pnKey /* OUT: Size of current key in bytes */
  59475. ){
  59476. void *pKey;
  59477. if( pSorter->aTree ){
  59478. VdbeSorterIter *pIter;
  59479. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  59480. *pnKey = pIter->nKey;
  59481. pKey = pIter->aKey;
  59482. }else{
  59483. *pnKey = pSorter->pRecord->nVal;
  59484. pKey = pSorter->pRecord->pVal;
  59485. }
  59486. return pKey;
  59487. }
  59488. /*
  59489. ** Copy the current sorter key into the memory cell pOut.
  59490. */
  59491. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  59492. VdbeSorter *pSorter = pCsr->pSorter;
  59493. void *pKey; int nKey; /* Sorter key to copy into pOut */
  59494. pKey = vdbeSorterRowkey(pSorter, &nKey);
  59495. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  59496. return SQLITE_NOMEM;
  59497. }
  59498. pOut->n = nKey;
  59499. MemSetTypeFlag(pOut, MEM_Blob);
  59500. memcpy(pOut->z, pKey, nKey);
  59501. return SQLITE_OK;
  59502. }
  59503. /*
  59504. ** Compare the key in memory cell pVal with the key that the sorter cursor
  59505. ** passed as the first argument currently points to. For the purposes of
  59506. ** the comparison, ignore the rowid field at the end of each record.
  59507. **
  59508. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  59509. ** Otherwise, set *pRes to a negative, zero or positive value if the
  59510. ** key in pVal is smaller than, equal to or larger than the current sorter
  59511. ** key.
  59512. */
  59513. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  59514. const VdbeCursor *pCsr, /* Sorter cursor */
  59515. Mem *pVal, /* Value to compare to current sorter key */
  59516. int *pRes /* OUT: Result of comparison */
  59517. ){
  59518. VdbeSorter *pSorter = pCsr->pSorter;
  59519. void *pKey; int nKey; /* Sorter key to compare pVal with */
  59520. pKey = vdbeSorterRowkey(pSorter, &nKey);
  59521. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  59522. return SQLITE_OK;
  59523. }
  59524. /************** End of vdbesort.c ********************************************/
  59525. /************** Begin file journal.c *****************************************/
  59526. /*
  59527. ** 2007 August 22
  59528. **
  59529. ** The author disclaims copyright to this source code. In place of
  59530. ** a legal notice, here is a blessing:
  59531. **
  59532. ** May you do good and not evil.
  59533. ** May you find forgiveness for yourself and forgive others.
  59534. ** May you share freely, never taking more than you give.
  59535. **
  59536. *************************************************************************
  59537. **
  59538. ** This file implements a special kind of sqlite3_file object used
  59539. ** by SQLite to create journal files if the atomic-write optimization
  59540. ** is enabled.
  59541. **
  59542. ** The distinctive characteristic of this sqlite3_file is that the
  59543. ** actual on disk file is created lazily. When the file is created,
  59544. ** the caller specifies a buffer size for an in-memory buffer to
  59545. ** be used to service read() and write() requests. The actual file
  59546. ** on disk is not created or populated until either:
  59547. **
  59548. ** 1) The in-memory representation grows too large for the allocated
  59549. ** buffer, or
  59550. ** 2) The sqlite3JournalCreate() function is called.
  59551. */
  59552. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  59553. /*
  59554. ** A JournalFile object is a subclass of sqlite3_file used by
  59555. ** as an open file handle for journal files.
  59556. */
  59557. struct JournalFile {
  59558. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  59559. int nBuf; /* Size of zBuf[] in bytes */
  59560. char *zBuf; /* Space to buffer journal writes */
  59561. int iSize; /* Amount of zBuf[] currently used */
  59562. int flags; /* xOpen flags */
  59563. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  59564. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  59565. const char *zJournal; /* Name of the journal file */
  59566. };
  59567. typedef struct JournalFile JournalFile;
  59568. /*
  59569. ** If it does not already exists, create and populate the on-disk file
  59570. ** for JournalFile p.
  59571. */
  59572. static int createFile(JournalFile *p){
  59573. int rc = SQLITE_OK;
  59574. if( !p->pReal ){
  59575. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  59576. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  59577. if( rc==SQLITE_OK ){
  59578. p->pReal = pReal;
  59579. if( p->iSize>0 ){
  59580. assert(p->iSize<=p->nBuf);
  59581. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  59582. }
  59583. if( rc!=SQLITE_OK ){
  59584. /* If an error occurred while writing to the file, close it before
  59585. ** returning. This way, SQLite uses the in-memory journal data to
  59586. ** roll back changes made to the internal page-cache before this
  59587. ** function was called. */
  59588. sqlite3OsClose(pReal);
  59589. p->pReal = 0;
  59590. }
  59591. }
  59592. }
  59593. return rc;
  59594. }
  59595. /*
  59596. ** Close the file.
  59597. */
  59598. static int jrnlClose(sqlite3_file *pJfd){
  59599. JournalFile *p = (JournalFile *)pJfd;
  59600. if( p->pReal ){
  59601. sqlite3OsClose(p->pReal);
  59602. }
  59603. sqlite3_free(p->zBuf);
  59604. return SQLITE_OK;
  59605. }
  59606. /*
  59607. ** Read data from the file.
  59608. */
  59609. static int jrnlRead(
  59610. sqlite3_file *pJfd, /* The journal file from which to read */
  59611. void *zBuf, /* Put the results here */
  59612. int iAmt, /* Number of bytes to read */
  59613. sqlite_int64 iOfst /* Begin reading at this offset */
  59614. ){
  59615. int rc = SQLITE_OK;
  59616. JournalFile *p = (JournalFile *)pJfd;
  59617. if( p->pReal ){
  59618. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  59619. }else if( (iAmt+iOfst)>p->iSize ){
  59620. rc = SQLITE_IOERR_SHORT_READ;
  59621. }else{
  59622. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  59623. }
  59624. return rc;
  59625. }
  59626. /*
  59627. ** Write data to the file.
  59628. */
  59629. static int jrnlWrite(
  59630. sqlite3_file *pJfd, /* The journal file into which to write */
  59631. const void *zBuf, /* Take data to be written from here */
  59632. int iAmt, /* Number of bytes to write */
  59633. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  59634. ){
  59635. int rc = SQLITE_OK;
  59636. JournalFile *p = (JournalFile *)pJfd;
  59637. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  59638. rc = createFile(p);
  59639. }
  59640. if( rc==SQLITE_OK ){
  59641. if( p->pReal ){
  59642. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  59643. }else{
  59644. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  59645. if( p->iSize<(iOfst+iAmt) ){
  59646. p->iSize = (iOfst+iAmt);
  59647. }
  59648. }
  59649. }
  59650. return rc;
  59651. }
  59652. /*
  59653. ** Truncate the file.
  59654. */
  59655. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  59656. int rc = SQLITE_OK;
  59657. JournalFile *p = (JournalFile *)pJfd;
  59658. if( p->pReal ){
  59659. rc = sqlite3OsTruncate(p->pReal, size);
  59660. }else if( size<p->iSize ){
  59661. p->iSize = size;
  59662. }
  59663. return rc;
  59664. }
  59665. /*
  59666. ** Sync the file.
  59667. */
  59668. static int jrnlSync(sqlite3_file *pJfd, int flags){
  59669. int rc;
  59670. JournalFile *p = (JournalFile *)pJfd;
  59671. if( p->pReal ){
  59672. rc = sqlite3OsSync(p->pReal, flags);
  59673. }else{
  59674. rc = SQLITE_OK;
  59675. }
  59676. return rc;
  59677. }
  59678. /*
  59679. ** Query the size of the file in bytes.
  59680. */
  59681. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  59682. int rc = SQLITE_OK;
  59683. JournalFile *p = (JournalFile *)pJfd;
  59684. if( p->pReal ){
  59685. rc = sqlite3OsFileSize(p->pReal, pSize);
  59686. }else{
  59687. *pSize = (sqlite_int64) p->iSize;
  59688. }
  59689. return rc;
  59690. }
  59691. /*
  59692. ** Table of methods for JournalFile sqlite3_file object.
  59693. */
  59694. static struct sqlite3_io_methods JournalFileMethods = {
  59695. 1, /* iVersion */
  59696. jrnlClose, /* xClose */
  59697. jrnlRead, /* xRead */
  59698. jrnlWrite, /* xWrite */
  59699. jrnlTruncate, /* xTruncate */
  59700. jrnlSync, /* xSync */
  59701. jrnlFileSize, /* xFileSize */
  59702. 0, /* xLock */
  59703. 0, /* xUnlock */
  59704. 0, /* xCheckReservedLock */
  59705. 0, /* xFileControl */
  59706. 0, /* xSectorSize */
  59707. 0, /* xDeviceCharacteristics */
  59708. 0, /* xShmMap */
  59709. 0, /* xShmLock */
  59710. 0, /* xShmBarrier */
  59711. 0 /* xShmUnmap */
  59712. };
  59713. /*
  59714. ** Open a journal file.
  59715. */
  59716. SQLITE_PRIVATE int sqlite3JournalOpen(
  59717. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  59718. const char *zName, /* Name of the journal file */
  59719. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  59720. int flags, /* Opening flags */
  59721. int nBuf /* Bytes buffered before opening the file */
  59722. ){
  59723. JournalFile *p = (JournalFile *)pJfd;
  59724. memset(p, 0, sqlite3JournalSize(pVfs));
  59725. if( nBuf>0 ){
  59726. p->zBuf = sqlite3MallocZero(nBuf);
  59727. if( !p->zBuf ){
  59728. return SQLITE_NOMEM;
  59729. }
  59730. }else{
  59731. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  59732. }
  59733. p->pMethod = &JournalFileMethods;
  59734. p->nBuf = nBuf;
  59735. p->flags = flags;
  59736. p->zJournal = zName;
  59737. p->pVfs = pVfs;
  59738. return SQLITE_OK;
  59739. }
  59740. /*
  59741. ** If the argument p points to a JournalFile structure, and the underlying
  59742. ** file has not yet been created, create it now.
  59743. */
  59744. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  59745. if( p->pMethods!=&JournalFileMethods ){
  59746. return SQLITE_OK;
  59747. }
  59748. return createFile((JournalFile *)p);
  59749. }
  59750. /*
  59751. ** The file-handle passed as the only argument is guaranteed to be an open
  59752. ** file. It may or may not be of class JournalFile. If the file is a
  59753. ** JournalFile, and the underlying file on disk has not yet been opened,
  59754. ** return 0. Otherwise, return 1.
  59755. */
  59756. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  59757. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  59758. }
  59759. /*
  59760. ** Return the number of bytes required to store a JournalFile that uses vfs
  59761. ** pVfs to create the underlying on-disk files.
  59762. */
  59763. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  59764. return (pVfs->szOsFile+sizeof(JournalFile));
  59765. }
  59766. #endif
  59767. /************** End of journal.c *********************************************/
  59768. /************** Begin file memjournal.c **************************************/
  59769. /*
  59770. ** 2008 October 7
  59771. **
  59772. ** The author disclaims copyright to this source code. In place of
  59773. ** a legal notice, here is a blessing:
  59774. **
  59775. ** May you do good and not evil.
  59776. ** May you find forgiveness for yourself and forgive others.
  59777. ** May you share freely, never taking more than you give.
  59778. **
  59779. *************************************************************************
  59780. **
  59781. ** This file contains code use to implement an in-memory rollback journal.
  59782. ** The in-memory rollback journal is used to journal transactions for
  59783. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  59784. */
  59785. /* Forward references to internal structures */
  59786. typedef struct MemJournal MemJournal;
  59787. typedef struct FilePoint FilePoint;
  59788. typedef struct FileChunk FileChunk;
  59789. /* Space to hold the rollback journal is allocated in increments of
  59790. ** this many bytes.
  59791. **
  59792. ** The size chosen is a little less than a power of two. That way,
  59793. ** the FileChunk object will have a size that almost exactly fills
  59794. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  59795. ** memory allocators.
  59796. */
  59797. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  59798. /*
  59799. ** The rollback journal is composed of a linked list of these structures.
  59800. */
  59801. struct FileChunk {
  59802. FileChunk *pNext; /* Next chunk in the journal */
  59803. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  59804. };
  59805. /*
  59806. ** An instance of this object serves as a cursor into the rollback journal.
  59807. ** The cursor can be either for reading or writing.
  59808. */
  59809. struct FilePoint {
  59810. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  59811. FileChunk *pChunk; /* Specific chunk into which cursor points */
  59812. };
  59813. /*
  59814. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  59815. ** is an instance of this class.
  59816. */
  59817. struct MemJournal {
  59818. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  59819. FileChunk *pFirst; /* Head of in-memory chunk-list */
  59820. FilePoint endpoint; /* Pointer to the end of the file */
  59821. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  59822. };
  59823. /*
  59824. ** Read data from the in-memory journal file. This is the implementation
  59825. ** of the sqlite3_vfs.xRead method.
  59826. */
  59827. static int memjrnlRead(
  59828. sqlite3_file *pJfd, /* The journal file from which to read */
  59829. void *zBuf, /* Put the results here */
  59830. int iAmt, /* Number of bytes to read */
  59831. sqlite_int64 iOfst /* Begin reading at this offset */
  59832. ){
  59833. MemJournal *p = (MemJournal *)pJfd;
  59834. u8 *zOut = zBuf;
  59835. int nRead = iAmt;
  59836. int iChunkOffset;
  59837. FileChunk *pChunk;
  59838. /* SQLite never tries to read past the end of a rollback journal file */
  59839. assert( iOfst+iAmt<=p->endpoint.iOffset );
  59840. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  59841. sqlite3_int64 iOff = 0;
  59842. for(pChunk=p->pFirst;
  59843. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  59844. pChunk=pChunk->pNext
  59845. ){
  59846. iOff += JOURNAL_CHUNKSIZE;
  59847. }
  59848. }else{
  59849. pChunk = p->readpoint.pChunk;
  59850. }
  59851. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  59852. do {
  59853. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  59854. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  59855. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  59856. zOut += nCopy;
  59857. nRead -= iSpace;
  59858. iChunkOffset = 0;
  59859. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  59860. p->readpoint.iOffset = iOfst+iAmt;
  59861. p->readpoint.pChunk = pChunk;
  59862. return SQLITE_OK;
  59863. }
  59864. /*
  59865. ** Write data to the file.
  59866. */
  59867. static int memjrnlWrite(
  59868. sqlite3_file *pJfd, /* The journal file into which to write */
  59869. const void *zBuf, /* Take data to be written from here */
  59870. int iAmt, /* Number of bytes to write */
  59871. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  59872. ){
  59873. MemJournal *p = (MemJournal *)pJfd;
  59874. int nWrite = iAmt;
  59875. u8 *zWrite = (u8 *)zBuf;
  59876. /* An in-memory journal file should only ever be appended to. Random
  59877. ** access writes are not required by sqlite.
  59878. */
  59879. assert( iOfst==p->endpoint.iOffset );
  59880. UNUSED_PARAMETER(iOfst);
  59881. while( nWrite>0 ){
  59882. FileChunk *pChunk = p->endpoint.pChunk;
  59883. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  59884. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  59885. if( iChunkOffset==0 ){
  59886. /* New chunk is required to extend the file. */
  59887. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  59888. if( !pNew ){
  59889. return SQLITE_IOERR_NOMEM;
  59890. }
  59891. pNew->pNext = 0;
  59892. if( pChunk ){
  59893. assert( p->pFirst );
  59894. pChunk->pNext = pNew;
  59895. }else{
  59896. assert( !p->pFirst );
  59897. p->pFirst = pNew;
  59898. }
  59899. p->endpoint.pChunk = pNew;
  59900. }
  59901. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  59902. zWrite += iSpace;
  59903. nWrite -= iSpace;
  59904. p->endpoint.iOffset += iSpace;
  59905. }
  59906. return SQLITE_OK;
  59907. }
  59908. /*
  59909. ** Truncate the file.
  59910. */
  59911. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  59912. MemJournal *p = (MemJournal *)pJfd;
  59913. FileChunk *pChunk;
  59914. assert(size==0);
  59915. UNUSED_PARAMETER(size);
  59916. pChunk = p->pFirst;
  59917. while( pChunk ){
  59918. FileChunk *pTmp = pChunk;
  59919. pChunk = pChunk->pNext;
  59920. sqlite3_free(pTmp);
  59921. }
  59922. sqlite3MemJournalOpen(pJfd);
  59923. return SQLITE_OK;
  59924. }
  59925. /*
  59926. ** Close the file.
  59927. */
  59928. static int memjrnlClose(sqlite3_file *pJfd){
  59929. memjrnlTruncate(pJfd, 0);
  59930. return SQLITE_OK;
  59931. }
  59932. /*
  59933. ** Sync the file.
  59934. **
  59935. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  59936. ** is never called in a working implementation. This implementation
  59937. ** exists purely as a contingency, in case some malfunction in some other
  59938. ** part of SQLite causes Sync to be called by mistake.
  59939. */
  59940. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  59941. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  59942. return SQLITE_OK;
  59943. }
  59944. /*
  59945. ** Query the size of the file in bytes.
  59946. */
  59947. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  59948. MemJournal *p = (MemJournal *)pJfd;
  59949. *pSize = (sqlite_int64) p->endpoint.iOffset;
  59950. return SQLITE_OK;
  59951. }
  59952. /*
  59953. ** Table of methods for MemJournal sqlite3_file object.
  59954. */
  59955. static const struct sqlite3_io_methods MemJournalMethods = {
  59956. 1, /* iVersion */
  59957. memjrnlClose, /* xClose */
  59958. memjrnlRead, /* xRead */
  59959. memjrnlWrite, /* xWrite */
  59960. memjrnlTruncate, /* xTruncate */
  59961. memjrnlSync, /* xSync */
  59962. memjrnlFileSize, /* xFileSize */
  59963. 0, /* xLock */
  59964. 0, /* xUnlock */
  59965. 0, /* xCheckReservedLock */
  59966. 0, /* xFileControl */
  59967. 0, /* xSectorSize */
  59968. 0, /* xDeviceCharacteristics */
  59969. 0, /* xShmMap */
  59970. 0, /* xShmLock */
  59971. 0, /* xShmBarrier */
  59972. 0, /* xShmUnmap */
  59973. 0, /* xFetch */
  59974. 0 /* xUnfetch */
  59975. };
  59976. /*
  59977. ** Open a journal file.
  59978. */
  59979. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  59980. MemJournal *p = (MemJournal *)pJfd;
  59981. assert( EIGHT_BYTE_ALIGNMENT(p) );
  59982. memset(p, 0, sqlite3MemJournalSize());
  59983. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  59984. }
  59985. /*
  59986. ** Return true if the file-handle passed as an argument is
  59987. ** an in-memory journal
  59988. */
  59989. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  59990. return pJfd->pMethods==&MemJournalMethods;
  59991. }
  59992. /*
  59993. ** Return the number of bytes required to store a MemJournal file descriptor.
  59994. */
  59995. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  59996. return sizeof(MemJournal);
  59997. }
  59998. /************** End of memjournal.c ******************************************/
  59999. /************** Begin file walker.c ******************************************/
  60000. /*
  60001. ** 2008 August 16
  60002. **
  60003. ** The author disclaims copyright to this source code. In place of
  60004. ** a legal notice, here is a blessing:
  60005. **
  60006. ** May you do good and not evil.
  60007. ** May you find forgiveness for yourself and forgive others.
  60008. ** May you share freely, never taking more than you give.
  60009. **
  60010. *************************************************************************
  60011. ** This file contains routines used for walking the parser tree for
  60012. ** an SQL statement.
  60013. */
  60014. /* #include <stdlib.h> */
  60015. /* #include <string.h> */
  60016. /*
  60017. ** Walk an expression tree. Invoke the callback once for each node
  60018. ** of the expression, while decending. (In other words, the callback
  60019. ** is invoked before visiting children.)
  60020. **
  60021. ** The return value from the callback should be one of the WRC_*
  60022. ** constants to specify how to proceed with the walk.
  60023. **
  60024. ** WRC_Continue Continue descending down the tree.
  60025. **
  60026. ** WRC_Prune Do not descend into child nodes. But allow
  60027. ** the walk to continue with sibling nodes.
  60028. **
  60029. ** WRC_Abort Do no more callbacks. Unwind the stack and
  60030. ** return the top-level walk call.
  60031. **
  60032. ** The return value from this routine is WRC_Abort to abandon the tree walk
  60033. ** and WRC_Continue to continue.
  60034. */
  60035. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  60036. int rc;
  60037. if( pExpr==0 ) return WRC_Continue;
  60038. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  60039. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  60040. rc = pWalker->xExprCallback(pWalker, pExpr);
  60041. if( rc==WRC_Continue
  60042. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  60043. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  60044. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  60045. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  60046. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  60047. }else{
  60048. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  60049. }
  60050. }
  60051. return rc & WRC_Abort;
  60052. }
  60053. /*
  60054. ** Call sqlite3WalkExpr() for every expression in list p or until
  60055. ** an abort request is seen.
  60056. */
  60057. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  60058. int i;
  60059. struct ExprList_item *pItem;
  60060. if( p ){
  60061. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  60062. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  60063. }
  60064. }
  60065. return WRC_Continue;
  60066. }
  60067. /*
  60068. ** Walk all expressions associated with SELECT statement p. Do
  60069. ** not invoke the SELECT callback on p, but do (of course) invoke
  60070. ** any expr callbacks and SELECT callbacks that come from subqueries.
  60071. ** Return WRC_Abort or WRC_Continue.
  60072. */
  60073. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  60074. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  60075. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  60076. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  60077. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  60078. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  60079. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  60080. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  60081. return WRC_Continue;
  60082. }
  60083. /*
  60084. ** Walk the parse trees associated with all subqueries in the
  60085. ** FROM clause of SELECT statement p. Do not invoke the select
  60086. ** callback on p, but do invoke it on each FROM clause subquery
  60087. ** and on any subqueries further down in the tree. Return
  60088. ** WRC_Abort or WRC_Continue;
  60089. */
  60090. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  60091. SrcList *pSrc;
  60092. int i;
  60093. struct SrcList_item *pItem;
  60094. pSrc = p->pSrc;
  60095. if( ALWAYS(pSrc) ){
  60096. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  60097. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  60098. return WRC_Abort;
  60099. }
  60100. }
  60101. }
  60102. return WRC_Continue;
  60103. }
  60104. /*
  60105. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  60106. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  60107. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  60108. ** either before or after the walk of expressions and FROM clause, depending
  60109. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  60110. **
  60111. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  60112. ** there is an abort request.
  60113. **
  60114. ** If the Walker does not have an xSelectCallback() then this routine
  60115. ** is a no-op returning WRC_Continue.
  60116. */
  60117. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  60118. int rc;
  60119. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  60120. rc = WRC_Continue;
  60121. pWalker->walkerDepth++;
  60122. while( p ){
  60123. if( !pWalker->bSelectDepthFirst ){
  60124. rc = pWalker->xSelectCallback(pWalker, p);
  60125. if( rc ) break;
  60126. }
  60127. if( sqlite3WalkSelectExpr(pWalker, p)
  60128. || sqlite3WalkSelectFrom(pWalker, p)
  60129. ){
  60130. pWalker->walkerDepth--;
  60131. return WRC_Abort;
  60132. }
  60133. if( pWalker->bSelectDepthFirst ){
  60134. rc = pWalker->xSelectCallback(pWalker, p);
  60135. /* Depth-first search is currently only used for
  60136. ** selectAddSubqueryTypeInfo() and that routine always returns
  60137. ** WRC_Continue (0). So the following branch is never taken. */
  60138. if( NEVER(rc) ) break;
  60139. }
  60140. p = p->pPrior;
  60141. }
  60142. pWalker->walkerDepth--;
  60143. return rc & WRC_Abort;
  60144. }
  60145. /************** End of walker.c **********************************************/
  60146. /************** Begin file resolve.c *****************************************/
  60147. /*
  60148. ** 2008 August 18
  60149. **
  60150. ** The author disclaims copyright to this source code. In place of
  60151. ** a legal notice, here is a blessing:
  60152. **
  60153. ** May you do good and not evil.
  60154. ** May you find forgiveness for yourself and forgive others.
  60155. ** May you share freely, never taking more than you give.
  60156. **
  60157. *************************************************************************
  60158. **
  60159. ** This file contains routines used for walking the parser tree and
  60160. ** resolve all identifiers by associating them with a particular
  60161. ** table and column.
  60162. */
  60163. /* #include <stdlib.h> */
  60164. /* #include <string.h> */
  60165. /*
  60166. ** Walk the expression tree pExpr and increase the aggregate function
  60167. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  60168. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  60169. ** outer query into an inner subquery.
  60170. **
  60171. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  60172. ** is a helper function - a callback for the tree walker.
  60173. */
  60174. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  60175. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  60176. return WRC_Continue;
  60177. }
  60178. static void incrAggFunctionDepth(Expr *pExpr, int N){
  60179. if( N>0 ){
  60180. Walker w;
  60181. memset(&w, 0, sizeof(w));
  60182. w.xExprCallback = incrAggDepth;
  60183. w.u.i = N;
  60184. sqlite3WalkExpr(&w, pExpr);
  60185. }
  60186. }
  60187. /*
  60188. ** Turn the pExpr expression into an alias for the iCol-th column of the
  60189. ** result set in pEList.
  60190. **
  60191. ** If the result set column is a simple column reference, then this routine
  60192. ** makes an exact copy. But for any other kind of expression, this
  60193. ** routine make a copy of the result set column as the argument to the
  60194. ** TK_AS operator. The TK_AS operator causes the expression to be
  60195. ** evaluated just once and then reused for each alias.
  60196. **
  60197. ** The reason for suppressing the TK_AS term when the expression is a simple
  60198. ** column reference is so that the column reference will be recognized as
  60199. ** usable by indices within the WHERE clause processing logic.
  60200. **
  60201. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  60202. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  60203. **
  60204. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  60205. **
  60206. ** Is equivalent to:
  60207. **
  60208. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  60209. **
  60210. ** The result of random()%5 in the GROUP BY clause is probably different
  60211. ** from the result in the result-set. On the other hand Standard SQL does
  60212. ** not allow the GROUP BY clause to contain references to result-set columns.
  60213. ** So this should never come up in well-formed queries.
  60214. **
  60215. ** If the reference is followed by a COLLATE operator, then make sure
  60216. ** the COLLATE operator is preserved. For example:
  60217. **
  60218. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  60219. **
  60220. ** Should be transformed into:
  60221. **
  60222. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  60223. **
  60224. ** The nSubquery parameter specifies how many levels of subquery the
  60225. ** alias is removed from the original expression. The usually value is
  60226. ** zero but it might be more if the alias is contained within a subquery
  60227. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  60228. ** structures must be increased by the nSubquery amount.
  60229. */
  60230. static void resolveAlias(
  60231. Parse *pParse, /* Parsing context */
  60232. ExprList *pEList, /* A result set */
  60233. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  60234. Expr *pExpr, /* Transform this into an alias to the result set */
  60235. const char *zType, /* "GROUP" or "ORDER" or "" */
  60236. int nSubquery /* Number of subqueries that the label is moving */
  60237. ){
  60238. Expr *pOrig; /* The iCol-th column of the result set */
  60239. Expr *pDup; /* Copy of pOrig */
  60240. sqlite3 *db; /* The database connection */
  60241. assert( iCol>=0 && iCol<pEList->nExpr );
  60242. pOrig = pEList->a[iCol].pExpr;
  60243. assert( pOrig!=0 );
  60244. assert( pOrig->flags & EP_Resolved );
  60245. db = pParse->db;
  60246. pDup = sqlite3ExprDup(db, pOrig, 0);
  60247. if( pDup==0 ) return;
  60248. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  60249. incrAggFunctionDepth(pDup, nSubquery);
  60250. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  60251. if( pDup==0 ) return;
  60252. ExprSetProperty(pDup, EP_Skip);
  60253. if( pEList->a[iCol].iAlias==0 ){
  60254. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  60255. }
  60256. pDup->iTable = pEList->a[iCol].iAlias;
  60257. }
  60258. if( pExpr->op==TK_COLLATE ){
  60259. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  60260. }
  60261. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  60262. ** prevents ExprDelete() from deleting the Expr structure itself,
  60263. ** allowing it to be repopulated by the memcpy() on the following line.
  60264. ** The pExpr->u.zToken might point into memory that will be freed by the
  60265. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  60266. ** make a copy of the token before doing the sqlite3DbFree().
  60267. */
  60268. ExprSetProperty(pExpr, EP_Static);
  60269. sqlite3ExprDelete(db, pExpr);
  60270. memcpy(pExpr, pDup, sizeof(*pExpr));
  60271. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  60272. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  60273. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  60274. pExpr->flags |= EP_MemToken;
  60275. }
  60276. sqlite3DbFree(db, pDup);
  60277. }
  60278. /*
  60279. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  60280. **
  60281. ** Return FALSE if the USING clause is NULL or if it does not contain
  60282. ** zCol.
  60283. */
  60284. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  60285. if( pUsing ){
  60286. int k;
  60287. for(k=0; k<pUsing->nId; k++){
  60288. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  60289. }
  60290. }
  60291. return 0;
  60292. }
  60293. /*
  60294. ** Subqueries stores the original database, table and column names for their
  60295. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  60296. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  60297. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  60298. ** match anything.
  60299. */
  60300. SQLITE_PRIVATE int sqlite3MatchSpanName(
  60301. const char *zSpan,
  60302. const char *zCol,
  60303. const char *zTab,
  60304. const char *zDb
  60305. ){
  60306. int n;
  60307. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  60308. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  60309. return 0;
  60310. }
  60311. zSpan += n+1;
  60312. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  60313. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  60314. return 0;
  60315. }
  60316. zSpan += n+1;
  60317. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  60318. return 0;
  60319. }
  60320. return 1;
  60321. }
  60322. /*
  60323. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  60324. ** that name in the set of source tables in pSrcList and make the pExpr
  60325. ** expression node refer back to that source column. The following changes
  60326. ** are made to pExpr:
  60327. **
  60328. ** pExpr->iDb Set the index in db->aDb[] of the database X
  60329. ** (even if X is implied).
  60330. ** pExpr->iTable Set to the cursor number for the table obtained
  60331. ** from pSrcList.
  60332. ** pExpr->pTab Points to the Table structure of X.Y (even if
  60333. ** X and/or Y are implied.)
  60334. ** pExpr->iColumn Set to the column number within the table.
  60335. ** pExpr->op Set to TK_COLUMN.
  60336. ** pExpr->pLeft Any expression this points to is deleted
  60337. ** pExpr->pRight Any expression this points to is deleted.
  60338. **
  60339. ** The zDb variable is the name of the database (the "X"). This value may be
  60340. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  60341. ** can be used. The zTable variable is the name of the table (the "Y"). This
  60342. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  60343. ** means that the form of the name is Z and that columns from any table
  60344. ** can be used.
  60345. **
  60346. ** If the name cannot be resolved unambiguously, leave an error message
  60347. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  60348. */
  60349. static int lookupName(
  60350. Parse *pParse, /* The parsing context */
  60351. const char *zDb, /* Name of the database containing table, or NULL */
  60352. const char *zTab, /* Name of table containing column, or NULL */
  60353. const char *zCol, /* Name of the column. */
  60354. NameContext *pNC, /* The name context used to resolve the name */
  60355. Expr *pExpr /* Make this EXPR node point to the selected column */
  60356. ){
  60357. int i, j; /* Loop counters */
  60358. int cnt = 0; /* Number of matching column names */
  60359. int cntTab = 0; /* Number of matching table names */
  60360. int nSubquery = 0; /* How many levels of subquery */
  60361. sqlite3 *db = pParse->db; /* The database connection */
  60362. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  60363. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  60364. NameContext *pTopNC = pNC; /* First namecontext in the list */
  60365. Schema *pSchema = 0; /* Schema of the expression */
  60366. int isTrigger = 0;
  60367. assert( pNC ); /* the name context cannot be NULL. */
  60368. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  60369. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  60370. /* Initialize the node to no-match */
  60371. pExpr->iTable = -1;
  60372. pExpr->pTab = 0;
  60373. ExprSetVVAProperty(pExpr, EP_NoReduce);
  60374. /* Translate the schema name in zDb into a pointer to the corresponding
  60375. ** schema. If not found, pSchema will remain NULL and nothing will match
  60376. ** resulting in an appropriate error message toward the end of this routine
  60377. */
  60378. if( zDb ){
  60379. testcase( pNC->ncFlags & NC_PartIdx );
  60380. testcase( pNC->ncFlags & NC_IsCheck );
  60381. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  60382. /* Silently ignore database qualifiers inside CHECK constraints and partial
  60383. ** indices. Do not raise errors because that might break legacy and
  60384. ** because it does not hurt anything to just ignore the database name. */
  60385. zDb = 0;
  60386. }else{
  60387. for(i=0; i<db->nDb; i++){
  60388. assert( db->aDb[i].zName );
  60389. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  60390. pSchema = db->aDb[i].pSchema;
  60391. break;
  60392. }
  60393. }
  60394. }
  60395. }
  60396. /* Start at the inner-most context and move outward until a match is found */
  60397. while( pNC && cnt==0 ){
  60398. ExprList *pEList;
  60399. SrcList *pSrcList = pNC->pSrcList;
  60400. if( pSrcList ){
  60401. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  60402. Table *pTab;
  60403. Column *pCol;
  60404. pTab = pItem->pTab;
  60405. assert( pTab!=0 && pTab->zName!=0 );
  60406. assert( pTab->nCol>0 );
  60407. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  60408. int hit = 0;
  60409. pEList = pItem->pSelect->pEList;
  60410. for(j=0; j<pEList->nExpr; j++){
  60411. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  60412. cnt++;
  60413. cntTab = 2;
  60414. pMatch = pItem;
  60415. pExpr->iColumn = j;
  60416. hit = 1;
  60417. }
  60418. }
  60419. if( hit || zTab==0 ) continue;
  60420. }
  60421. if( zDb && pTab->pSchema!=pSchema ){
  60422. continue;
  60423. }
  60424. if( zTab ){
  60425. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  60426. assert( zTabName!=0 );
  60427. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  60428. continue;
  60429. }
  60430. }
  60431. if( 0==(cntTab++) ){
  60432. pMatch = pItem;
  60433. }
  60434. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  60435. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  60436. /* If there has been exactly one prior match and this match
  60437. ** is for the right-hand table of a NATURAL JOIN or is in a
  60438. ** USING clause, then skip this match.
  60439. */
  60440. if( cnt==1 ){
  60441. if( pItem->jointype & JT_NATURAL ) continue;
  60442. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  60443. }
  60444. cnt++;
  60445. pMatch = pItem;
  60446. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  60447. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  60448. break;
  60449. }
  60450. }
  60451. }
  60452. if( pMatch ){
  60453. pExpr->iTable = pMatch->iCursor;
  60454. pExpr->pTab = pMatch->pTab;
  60455. pSchema = pExpr->pTab->pSchema;
  60456. }
  60457. } /* if( pSrcList ) */
  60458. #ifndef SQLITE_OMIT_TRIGGER
  60459. /* If we have not already resolved the name, then maybe
  60460. ** it is a new.* or old.* trigger argument reference
  60461. */
  60462. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  60463. int op = pParse->eTriggerOp;
  60464. Table *pTab = 0;
  60465. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  60466. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  60467. pExpr->iTable = 1;
  60468. pTab = pParse->pTriggerTab;
  60469. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  60470. pExpr->iTable = 0;
  60471. pTab = pParse->pTriggerTab;
  60472. }
  60473. if( pTab ){
  60474. int iCol;
  60475. pSchema = pTab->pSchema;
  60476. cntTab++;
  60477. for(iCol=0; iCol<pTab->nCol; iCol++){
  60478. Column *pCol = &pTab->aCol[iCol];
  60479. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  60480. if( iCol==pTab->iPKey ){
  60481. iCol = -1;
  60482. }
  60483. break;
  60484. }
  60485. }
  60486. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  60487. iCol = -1; /* IMP: R-44911-55124 */
  60488. }
  60489. if( iCol<pTab->nCol ){
  60490. cnt++;
  60491. if( iCol<0 ){
  60492. pExpr->affinity = SQLITE_AFF_INTEGER;
  60493. }else if( pExpr->iTable==0 ){
  60494. testcase( iCol==31 );
  60495. testcase( iCol==32 );
  60496. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  60497. }else{
  60498. testcase( iCol==31 );
  60499. testcase( iCol==32 );
  60500. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  60501. }
  60502. pExpr->iColumn = (i16)iCol;
  60503. pExpr->pTab = pTab;
  60504. isTrigger = 1;
  60505. }
  60506. }
  60507. }
  60508. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  60509. /*
  60510. ** Perhaps the name is a reference to the ROWID
  60511. */
  60512. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  60513. cnt = 1;
  60514. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  60515. pExpr->affinity = SQLITE_AFF_INTEGER;
  60516. }
  60517. /*
  60518. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  60519. ** might refer to an result-set alias. This happens, for example, when
  60520. ** we are resolving names in the WHERE clause of the following command:
  60521. **
  60522. ** SELECT a+b AS x FROM table WHERE x<10;
  60523. **
  60524. ** In cases like this, replace pExpr with a copy of the expression that
  60525. ** forms the result set entry ("a+b" in the example) and return immediately.
  60526. ** Note that the expression in the result set should have already been
  60527. ** resolved by the time the WHERE clause is resolved.
  60528. **
  60529. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  60530. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  60531. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  60532. ** is supported for backwards compatibility only. TO DO: Issue a warning
  60533. ** on sqlite3_log() whenever the capability is used.
  60534. */
  60535. if( (pEList = pNC->pEList)!=0
  60536. && zTab==0
  60537. && cnt==0
  60538. ){
  60539. for(j=0; j<pEList->nExpr; j++){
  60540. char *zAs = pEList->a[j].zName;
  60541. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  60542. Expr *pOrig;
  60543. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  60544. assert( pExpr->x.pList==0 );
  60545. assert( pExpr->x.pSelect==0 );
  60546. pOrig = pEList->a[j].pExpr;
  60547. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  60548. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  60549. return WRC_Abort;
  60550. }
  60551. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  60552. cnt = 1;
  60553. pMatch = 0;
  60554. assert( zTab==0 && zDb==0 );
  60555. goto lookupname_end;
  60556. }
  60557. }
  60558. }
  60559. /* Advance to the next name context. The loop will exit when either
  60560. ** we have a match (cnt>0) or when we run out of name contexts.
  60561. */
  60562. if( cnt==0 ){
  60563. pNC = pNC->pNext;
  60564. nSubquery++;
  60565. }
  60566. }
  60567. /*
  60568. ** If X and Y are NULL (in other words if only the column name Z is
  60569. ** supplied) and the value of Z is enclosed in double-quotes, then
  60570. ** Z is a string literal if it doesn't match any column names. In that
  60571. ** case, we need to return right away and not make any changes to
  60572. ** pExpr.
  60573. **
  60574. ** Because no reference was made to outer contexts, the pNC->nRef
  60575. ** fields are not changed in any context.
  60576. */
  60577. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  60578. pExpr->op = TK_STRING;
  60579. pExpr->pTab = 0;
  60580. return WRC_Prune;
  60581. }
  60582. /*
  60583. ** cnt==0 means there was not match. cnt>1 means there were two or
  60584. ** more matches. Either way, we have an error.
  60585. */
  60586. if( cnt!=1 ){
  60587. const char *zErr;
  60588. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  60589. if( zDb ){
  60590. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  60591. }else if( zTab ){
  60592. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  60593. }else{
  60594. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  60595. }
  60596. pParse->checkSchema = 1;
  60597. pTopNC->nErr++;
  60598. }
  60599. /* If a column from a table in pSrcList is referenced, then record
  60600. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  60601. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  60602. ** column number is greater than the number of bits in the bitmask
  60603. ** then set the high-order bit of the bitmask.
  60604. */
  60605. if( pExpr->iColumn>=0 && pMatch!=0 ){
  60606. int n = pExpr->iColumn;
  60607. testcase( n==BMS-1 );
  60608. if( n>=BMS ){
  60609. n = BMS-1;
  60610. }
  60611. assert( pMatch->iCursor==pExpr->iTable );
  60612. pMatch->colUsed |= ((Bitmask)1)<<n;
  60613. }
  60614. /* Clean up and return
  60615. */
  60616. sqlite3ExprDelete(db, pExpr->pLeft);
  60617. pExpr->pLeft = 0;
  60618. sqlite3ExprDelete(db, pExpr->pRight);
  60619. pExpr->pRight = 0;
  60620. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  60621. lookupname_end:
  60622. if( cnt==1 ){
  60623. assert( pNC!=0 );
  60624. if( pExpr->op!=TK_AS ){
  60625. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  60626. }
  60627. /* Increment the nRef value on all name contexts from TopNC up to
  60628. ** the point where the name matched. */
  60629. for(;;){
  60630. assert( pTopNC!=0 );
  60631. pTopNC->nRef++;
  60632. if( pTopNC==pNC ) break;
  60633. pTopNC = pTopNC->pNext;
  60634. }
  60635. return WRC_Prune;
  60636. } else {
  60637. return WRC_Abort;
  60638. }
  60639. }
  60640. /*
  60641. ** Allocate and return a pointer to an expression to load the column iCol
  60642. ** from datasource iSrc in SrcList pSrc.
  60643. */
  60644. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  60645. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  60646. if( p ){
  60647. struct SrcList_item *pItem = &pSrc->a[iSrc];
  60648. p->pTab = pItem->pTab;
  60649. p->iTable = pItem->iCursor;
  60650. if( p->pTab->iPKey==iCol ){
  60651. p->iColumn = -1;
  60652. }else{
  60653. p->iColumn = (ynVar)iCol;
  60654. testcase( iCol==BMS );
  60655. testcase( iCol==BMS-1 );
  60656. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  60657. }
  60658. ExprSetProperty(p, EP_Resolved);
  60659. }
  60660. return p;
  60661. }
  60662. /*
  60663. ** Report an error that an expression is not valid for a partial index WHERE
  60664. ** clause.
  60665. */
  60666. static void notValidPartIdxWhere(
  60667. Parse *pParse, /* Leave error message here */
  60668. NameContext *pNC, /* The name context */
  60669. const char *zMsg /* Type of error */
  60670. ){
  60671. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  60672. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  60673. zMsg);
  60674. }
  60675. }
  60676. #ifndef SQLITE_OMIT_CHECK
  60677. /*
  60678. ** Report an error that an expression is not valid for a CHECK constraint.
  60679. */
  60680. static void notValidCheckConstraint(
  60681. Parse *pParse, /* Leave error message here */
  60682. NameContext *pNC, /* The name context */
  60683. const char *zMsg /* Type of error */
  60684. ){
  60685. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  60686. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  60687. }
  60688. }
  60689. #else
  60690. # define notValidCheckConstraint(P,N,M)
  60691. #endif
  60692. /*
  60693. ** Expression p should encode a floating point value between 1.0 and 0.0.
  60694. ** Return 1024 times this value. Or return -1 if p is not a floating point
  60695. ** value between 1.0 and 0.0.
  60696. */
  60697. static int exprProbability(Expr *p){
  60698. double r = -1.0;
  60699. if( p->op!=TK_FLOAT ) return -1;
  60700. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  60701. assert( r>=0.0 );
  60702. if( r>1.0 ) return -1;
  60703. return (int)(r*1000.0);
  60704. }
  60705. /*
  60706. ** This routine is callback for sqlite3WalkExpr().
  60707. **
  60708. ** Resolve symbolic names into TK_COLUMN operators for the current
  60709. ** node in the expression tree. Return 0 to continue the search down
  60710. ** the tree or 2 to abort the tree walk.
  60711. **
  60712. ** This routine also does error checking and name resolution for
  60713. ** function names. The operator for aggregate functions is changed
  60714. ** to TK_AGG_FUNCTION.
  60715. */
  60716. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  60717. NameContext *pNC;
  60718. Parse *pParse;
  60719. pNC = pWalker->u.pNC;
  60720. assert( pNC!=0 );
  60721. pParse = pNC->pParse;
  60722. assert( pParse==pWalker->pParse );
  60723. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  60724. ExprSetProperty(pExpr, EP_Resolved);
  60725. #ifndef NDEBUG
  60726. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  60727. SrcList *pSrcList = pNC->pSrcList;
  60728. int i;
  60729. for(i=0; i<pNC->pSrcList->nSrc; i++){
  60730. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  60731. }
  60732. }
  60733. #endif
  60734. switch( pExpr->op ){
  60735. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  60736. /* The special operator TK_ROW means use the rowid for the first
  60737. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  60738. ** clause processing on UPDATE and DELETE statements.
  60739. */
  60740. case TK_ROW: {
  60741. SrcList *pSrcList = pNC->pSrcList;
  60742. struct SrcList_item *pItem;
  60743. assert( pSrcList && pSrcList->nSrc==1 );
  60744. pItem = pSrcList->a;
  60745. pExpr->op = TK_COLUMN;
  60746. pExpr->pTab = pItem->pTab;
  60747. pExpr->iTable = pItem->iCursor;
  60748. pExpr->iColumn = -1;
  60749. pExpr->affinity = SQLITE_AFF_INTEGER;
  60750. break;
  60751. }
  60752. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  60753. /* A lone identifier is the name of a column.
  60754. */
  60755. case TK_ID: {
  60756. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  60757. }
  60758. /* A table name and column name: ID.ID
  60759. ** Or a database, table and column: ID.ID.ID
  60760. */
  60761. case TK_DOT: {
  60762. const char *zColumn;
  60763. const char *zTable;
  60764. const char *zDb;
  60765. Expr *pRight;
  60766. /* if( pSrcList==0 ) break; */
  60767. pRight = pExpr->pRight;
  60768. if( pRight->op==TK_ID ){
  60769. zDb = 0;
  60770. zTable = pExpr->pLeft->u.zToken;
  60771. zColumn = pRight->u.zToken;
  60772. }else{
  60773. assert( pRight->op==TK_DOT );
  60774. zDb = pExpr->pLeft->u.zToken;
  60775. zTable = pRight->pLeft->u.zToken;
  60776. zColumn = pRight->pRight->u.zToken;
  60777. }
  60778. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  60779. }
  60780. /* Resolve function names
  60781. */
  60782. case TK_CONST_FUNC:
  60783. case TK_FUNCTION: {
  60784. ExprList *pList = pExpr->x.pList; /* The argument list */
  60785. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  60786. int no_such_func = 0; /* True if no such function exists */
  60787. int wrong_num_args = 0; /* True if wrong number of arguments */
  60788. int is_agg = 0; /* True if is an aggregate function */
  60789. int auth; /* Authorization to use the function */
  60790. int nId; /* Number of characters in function name */
  60791. const char *zId; /* The function name. */
  60792. FuncDef *pDef; /* Information about the function */
  60793. u8 enc = ENC(pParse->db); /* The database encoding */
  60794. testcase( pExpr->op==TK_CONST_FUNC );
  60795. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  60796. notValidPartIdxWhere(pParse, pNC, "functions");
  60797. zId = pExpr->u.zToken;
  60798. nId = sqlite3Strlen30(zId);
  60799. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  60800. if( pDef==0 ){
  60801. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  60802. if( pDef==0 ){
  60803. no_such_func = 1;
  60804. }else{
  60805. wrong_num_args = 1;
  60806. }
  60807. }else{
  60808. is_agg = pDef->xFunc==0;
  60809. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  60810. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  60811. if( n==2 ){
  60812. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  60813. if( pExpr->iTable<0 ){
  60814. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  60815. "constant between 0.0 and 1.0");
  60816. pNC->nErr++;
  60817. }
  60818. }else{
  60819. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  60820. ** likelihood(X, 0.0625).
  60821. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  60822. ** likelihood(X,0.0625). */
  60823. pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
  60824. }
  60825. }
  60826. }
  60827. #ifndef SQLITE_OMIT_AUTHORIZATION
  60828. if( pDef ){
  60829. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  60830. if( auth!=SQLITE_OK ){
  60831. if( auth==SQLITE_DENY ){
  60832. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  60833. pDef->zName);
  60834. pNC->nErr++;
  60835. }
  60836. pExpr->op = TK_NULL;
  60837. return WRC_Prune;
  60838. }
  60839. }
  60840. #endif
  60841. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  60842. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  60843. pNC->nErr++;
  60844. is_agg = 0;
  60845. }else if( no_such_func && pParse->db->init.busy==0 ){
  60846. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  60847. pNC->nErr++;
  60848. }else if( wrong_num_args ){
  60849. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  60850. nId, zId);
  60851. pNC->nErr++;
  60852. }
  60853. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  60854. sqlite3WalkExprList(pWalker, pList);
  60855. if( is_agg ){
  60856. NameContext *pNC2 = pNC;
  60857. pExpr->op = TK_AGG_FUNCTION;
  60858. pExpr->op2 = 0;
  60859. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  60860. pExpr->op2++;
  60861. pNC2 = pNC2->pNext;
  60862. }
  60863. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  60864. pNC->ncFlags |= NC_AllowAgg;
  60865. }
  60866. /* FIX ME: Compute pExpr->affinity based on the expected return
  60867. ** type of the function
  60868. */
  60869. return WRC_Prune;
  60870. }
  60871. #ifndef SQLITE_OMIT_SUBQUERY
  60872. case TK_SELECT:
  60873. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  60874. #endif
  60875. case TK_IN: {
  60876. testcase( pExpr->op==TK_IN );
  60877. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  60878. int nRef = pNC->nRef;
  60879. notValidCheckConstraint(pParse, pNC, "subqueries");
  60880. notValidPartIdxWhere(pParse, pNC, "subqueries");
  60881. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  60882. assert( pNC->nRef>=nRef );
  60883. if( nRef!=pNC->nRef ){
  60884. ExprSetProperty(pExpr, EP_VarSelect);
  60885. }
  60886. }
  60887. break;
  60888. }
  60889. case TK_VARIABLE: {
  60890. notValidCheckConstraint(pParse, pNC, "parameters");
  60891. notValidPartIdxWhere(pParse, pNC, "parameters");
  60892. break;
  60893. }
  60894. }
  60895. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  60896. }
  60897. /*
  60898. ** pEList is a list of expressions which are really the result set of the
  60899. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  60900. ** This routine checks to see if pE is a simple identifier which corresponds
  60901. ** to the AS-name of one of the terms of the expression list. If it is,
  60902. ** this routine return an integer between 1 and N where N is the number of
  60903. ** elements in pEList, corresponding to the matching entry. If there is
  60904. ** no match, or if pE is not a simple identifier, then this routine
  60905. ** return 0.
  60906. **
  60907. ** pEList has been resolved. pE has not.
  60908. */
  60909. static int resolveAsName(
  60910. Parse *pParse, /* Parsing context for error messages */
  60911. ExprList *pEList, /* List of expressions to scan */
  60912. Expr *pE /* Expression we are trying to match */
  60913. ){
  60914. int i; /* Loop counter */
  60915. UNUSED_PARAMETER(pParse);
  60916. if( pE->op==TK_ID ){
  60917. char *zCol = pE->u.zToken;
  60918. for(i=0; i<pEList->nExpr; i++){
  60919. char *zAs = pEList->a[i].zName;
  60920. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  60921. return i+1;
  60922. }
  60923. }
  60924. }
  60925. return 0;
  60926. }
  60927. /*
  60928. ** pE is a pointer to an expression which is a single term in the
  60929. ** ORDER BY of a compound SELECT. The expression has not been
  60930. ** name resolved.
  60931. **
  60932. ** At the point this routine is called, we already know that the
  60933. ** ORDER BY term is not an integer index into the result set. That
  60934. ** case is handled by the calling routine.
  60935. **
  60936. ** Attempt to match pE against result set columns in the left-most
  60937. ** SELECT statement. Return the index i of the matching column,
  60938. ** as an indication to the caller that it should sort by the i-th column.
  60939. ** The left-most column is 1. In other words, the value returned is the
  60940. ** same integer value that would be used in the SQL statement to indicate
  60941. ** the column.
  60942. **
  60943. ** If there is no match, return 0. Return -1 if an error occurs.
  60944. */
  60945. static int resolveOrderByTermToExprList(
  60946. Parse *pParse, /* Parsing context for error messages */
  60947. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  60948. Expr *pE /* The specific ORDER BY term */
  60949. ){
  60950. int i; /* Loop counter */
  60951. ExprList *pEList; /* The columns of the result set */
  60952. NameContext nc; /* Name context for resolving pE */
  60953. sqlite3 *db; /* Database connection */
  60954. int rc; /* Return code from subprocedures */
  60955. u8 savedSuppErr; /* Saved value of db->suppressErr */
  60956. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  60957. pEList = pSelect->pEList;
  60958. /* Resolve all names in the ORDER BY term expression
  60959. */
  60960. memset(&nc, 0, sizeof(nc));
  60961. nc.pParse = pParse;
  60962. nc.pSrcList = pSelect->pSrc;
  60963. nc.pEList = pEList;
  60964. nc.ncFlags = NC_AllowAgg;
  60965. nc.nErr = 0;
  60966. db = pParse->db;
  60967. savedSuppErr = db->suppressErr;
  60968. db->suppressErr = 1;
  60969. rc = sqlite3ResolveExprNames(&nc, pE);
  60970. db->suppressErr = savedSuppErr;
  60971. if( rc ) return 0;
  60972. /* Try to match the ORDER BY expression against an expression
  60973. ** in the result set. Return an 1-based index of the matching
  60974. ** result-set entry.
  60975. */
  60976. for(i=0; i<pEList->nExpr; i++){
  60977. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  60978. return i+1;
  60979. }
  60980. }
  60981. /* If no match, return 0. */
  60982. return 0;
  60983. }
  60984. /*
  60985. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  60986. */
  60987. static void resolveOutOfRangeError(
  60988. Parse *pParse, /* The error context into which to write the error */
  60989. const char *zType, /* "ORDER" or "GROUP" */
  60990. int i, /* The index (1-based) of the term out of range */
  60991. int mx /* Largest permissible value of i */
  60992. ){
  60993. sqlite3ErrorMsg(pParse,
  60994. "%r %s BY term out of range - should be "
  60995. "between 1 and %d", i, zType, mx);
  60996. }
  60997. /*
  60998. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  60999. ** each term of the ORDER BY clause is a constant integer between 1
  61000. ** and N where N is the number of columns in the compound SELECT.
  61001. **
  61002. ** ORDER BY terms that are already an integer between 1 and N are
  61003. ** unmodified. ORDER BY terms that are integers outside the range of
  61004. ** 1 through N generate an error. ORDER BY terms that are expressions
  61005. ** are matched against result set expressions of compound SELECT
  61006. ** beginning with the left-most SELECT and working toward the right.
  61007. ** At the first match, the ORDER BY expression is transformed into
  61008. ** the integer column number.
  61009. **
  61010. ** Return the number of errors seen.
  61011. */
  61012. static int resolveCompoundOrderBy(
  61013. Parse *pParse, /* Parsing context. Leave error messages here */
  61014. Select *pSelect /* The SELECT statement containing the ORDER BY */
  61015. ){
  61016. int i;
  61017. ExprList *pOrderBy;
  61018. ExprList *pEList;
  61019. sqlite3 *db;
  61020. int moreToDo = 1;
  61021. pOrderBy = pSelect->pOrderBy;
  61022. if( pOrderBy==0 ) return 0;
  61023. db = pParse->db;
  61024. #if SQLITE_MAX_COLUMN
  61025. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  61026. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  61027. return 1;
  61028. }
  61029. #endif
  61030. for(i=0; i<pOrderBy->nExpr; i++){
  61031. pOrderBy->a[i].done = 0;
  61032. }
  61033. pSelect->pNext = 0;
  61034. while( pSelect->pPrior ){
  61035. pSelect->pPrior->pNext = pSelect;
  61036. pSelect = pSelect->pPrior;
  61037. }
  61038. while( pSelect && moreToDo ){
  61039. struct ExprList_item *pItem;
  61040. moreToDo = 0;
  61041. pEList = pSelect->pEList;
  61042. assert( pEList!=0 );
  61043. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61044. int iCol = -1;
  61045. Expr *pE, *pDup;
  61046. if( pItem->done ) continue;
  61047. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  61048. if( sqlite3ExprIsInteger(pE, &iCol) ){
  61049. if( iCol<=0 || iCol>pEList->nExpr ){
  61050. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  61051. return 1;
  61052. }
  61053. }else{
  61054. iCol = resolveAsName(pParse, pEList, pE);
  61055. if( iCol==0 ){
  61056. pDup = sqlite3ExprDup(db, pE, 0);
  61057. if( !db->mallocFailed ){
  61058. assert(pDup);
  61059. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  61060. }
  61061. sqlite3ExprDelete(db, pDup);
  61062. }
  61063. }
  61064. if( iCol>0 ){
  61065. /* Convert the ORDER BY term into an integer column number iCol,
  61066. ** taking care to preserve the COLLATE clause if it exists */
  61067. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  61068. if( pNew==0 ) return 1;
  61069. pNew->flags |= EP_IntValue;
  61070. pNew->u.iValue = iCol;
  61071. if( pItem->pExpr==pE ){
  61072. pItem->pExpr = pNew;
  61073. }else{
  61074. assert( pItem->pExpr->op==TK_COLLATE );
  61075. assert( pItem->pExpr->pLeft==pE );
  61076. pItem->pExpr->pLeft = pNew;
  61077. }
  61078. sqlite3ExprDelete(db, pE);
  61079. pItem->iOrderByCol = (u16)iCol;
  61080. pItem->done = 1;
  61081. }else{
  61082. moreToDo = 1;
  61083. }
  61084. }
  61085. pSelect = pSelect->pNext;
  61086. }
  61087. for(i=0; i<pOrderBy->nExpr; i++){
  61088. if( pOrderBy->a[i].done==0 ){
  61089. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  61090. "column in the result set", i+1);
  61091. return 1;
  61092. }
  61093. }
  61094. return 0;
  61095. }
  61096. /*
  61097. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  61098. ** the SELECT statement pSelect. If any term is reference to a
  61099. ** result set expression (as determined by the ExprList.a.iOrderByCol field)
  61100. ** then convert that term into a copy of the corresponding result set
  61101. ** column.
  61102. **
  61103. ** If any errors are detected, add an error message to pParse and
  61104. ** return non-zero. Return zero if no errors are seen.
  61105. */
  61106. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  61107. Parse *pParse, /* Parsing context. Leave error messages here */
  61108. Select *pSelect, /* The SELECT statement containing the clause */
  61109. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  61110. const char *zType /* "ORDER" or "GROUP" */
  61111. ){
  61112. int i;
  61113. sqlite3 *db = pParse->db;
  61114. ExprList *pEList;
  61115. struct ExprList_item *pItem;
  61116. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  61117. #if SQLITE_MAX_COLUMN
  61118. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  61119. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  61120. return 1;
  61121. }
  61122. #endif
  61123. pEList = pSelect->pEList;
  61124. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  61125. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61126. if( pItem->iOrderByCol ){
  61127. if( pItem->iOrderByCol>pEList->nExpr ){
  61128. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  61129. return 1;
  61130. }
  61131. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  61132. }
  61133. }
  61134. return 0;
  61135. }
  61136. /*
  61137. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  61138. ** The Name context of the SELECT statement is pNC. zType is either
  61139. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  61140. **
  61141. ** This routine resolves each term of the clause into an expression.
  61142. ** If the order-by term is an integer I between 1 and N (where N is the
  61143. ** number of columns in the result set of the SELECT) then the expression
  61144. ** in the resolution is a copy of the I-th result-set expression. If
  61145. ** the order-by term is an identifier that corresponds to the AS-name of
  61146. ** a result-set expression, then the term resolves to a copy of the
  61147. ** result-set expression. Otherwise, the expression is resolved in
  61148. ** the usual way - using sqlite3ResolveExprNames().
  61149. **
  61150. ** This routine returns the number of errors. If errors occur, then
  61151. ** an appropriate error message might be left in pParse. (OOM errors
  61152. ** excepted.)
  61153. */
  61154. static int resolveOrderGroupBy(
  61155. NameContext *pNC, /* The name context of the SELECT statement */
  61156. Select *pSelect, /* The SELECT statement holding pOrderBy */
  61157. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  61158. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  61159. ){
  61160. int i, j; /* Loop counters */
  61161. int iCol; /* Column number */
  61162. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  61163. Parse *pParse; /* Parsing context */
  61164. int nResult; /* Number of terms in the result set */
  61165. if( pOrderBy==0 ) return 0;
  61166. nResult = pSelect->pEList->nExpr;
  61167. pParse = pNC->pParse;
  61168. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  61169. Expr *pE = pItem->pExpr;
  61170. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  61171. if( zType[0]!='G' ){
  61172. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  61173. if( iCol>0 ){
  61174. /* If an AS-name match is found, mark this ORDER BY column as being
  61175. ** a copy of the iCol-th result-set column. The subsequent call to
  61176. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  61177. ** copy of the iCol-th result-set expression. */
  61178. pItem->iOrderByCol = (u16)iCol;
  61179. continue;
  61180. }
  61181. }
  61182. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  61183. /* The ORDER BY term is an integer constant. Again, set the column
  61184. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  61185. ** order-by term to a copy of the result-set expression */
  61186. if( iCol<1 || iCol>0xffff ){
  61187. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  61188. return 1;
  61189. }
  61190. pItem->iOrderByCol = (u16)iCol;
  61191. continue;
  61192. }
  61193. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  61194. pItem->iOrderByCol = 0;
  61195. if( sqlite3ResolveExprNames(pNC, pE) ){
  61196. return 1;
  61197. }
  61198. for(j=0; j<pSelect->pEList->nExpr; j++){
  61199. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  61200. pItem->iOrderByCol = j+1;
  61201. }
  61202. }
  61203. }
  61204. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  61205. }
  61206. /*
  61207. ** Resolve names in the SELECT statement p and all of its descendents.
  61208. */
  61209. static int resolveSelectStep(Walker *pWalker, Select *p){
  61210. NameContext *pOuterNC; /* Context that contains this SELECT */
  61211. NameContext sNC; /* Name context of this SELECT */
  61212. int isCompound; /* True if p is a compound select */
  61213. int nCompound; /* Number of compound terms processed so far */
  61214. Parse *pParse; /* Parsing context */
  61215. ExprList *pEList; /* Result set expression list */
  61216. int i; /* Loop counter */
  61217. ExprList *pGroupBy; /* The GROUP BY clause */
  61218. Select *pLeftmost; /* Left-most of SELECT of a compound */
  61219. sqlite3 *db; /* Database connection */
  61220. assert( p!=0 );
  61221. if( p->selFlags & SF_Resolved ){
  61222. return WRC_Prune;
  61223. }
  61224. pOuterNC = pWalker->u.pNC;
  61225. pParse = pWalker->pParse;
  61226. db = pParse->db;
  61227. /* Normally sqlite3SelectExpand() will be called first and will have
  61228. ** already expanded this SELECT. However, if this is a subquery within
  61229. ** an expression, sqlite3ResolveExprNames() will be called without a
  61230. ** prior call to sqlite3SelectExpand(). When that happens, let
  61231. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  61232. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  61233. ** this routine in the correct order.
  61234. */
  61235. if( (p->selFlags & SF_Expanded)==0 ){
  61236. sqlite3SelectPrep(pParse, p, pOuterNC);
  61237. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  61238. }
  61239. isCompound = p->pPrior!=0;
  61240. nCompound = 0;
  61241. pLeftmost = p;
  61242. while( p ){
  61243. assert( (p->selFlags & SF_Expanded)!=0 );
  61244. assert( (p->selFlags & SF_Resolved)==0 );
  61245. p->selFlags |= SF_Resolved;
  61246. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  61247. ** are not allowed to refer to any names, so pass an empty NameContext.
  61248. */
  61249. memset(&sNC, 0, sizeof(sNC));
  61250. sNC.pParse = pParse;
  61251. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  61252. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  61253. return WRC_Abort;
  61254. }
  61255. /* Recursively resolve names in all subqueries
  61256. */
  61257. for(i=0; i<p->pSrc->nSrc; i++){
  61258. struct SrcList_item *pItem = &p->pSrc->a[i];
  61259. if( pItem->pSelect ){
  61260. NameContext *pNC; /* Used to iterate name contexts */
  61261. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  61262. const char *zSavedContext = pParse->zAuthContext;
  61263. /* Count the total number of references to pOuterNC and all of its
  61264. ** parent contexts. After resolving references to expressions in
  61265. ** pItem->pSelect, check if this value has changed. If so, then
  61266. ** SELECT statement pItem->pSelect must be correlated. Set the
  61267. ** pItem->isCorrelated flag if this is the case. */
  61268. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  61269. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  61270. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  61271. pParse->zAuthContext = zSavedContext;
  61272. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  61273. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  61274. assert( pItem->isCorrelated==0 && nRef<=0 );
  61275. pItem->isCorrelated = (nRef!=0);
  61276. }
  61277. }
  61278. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  61279. ** resolve the result-set expression list.
  61280. */
  61281. sNC.ncFlags = NC_AllowAgg;
  61282. sNC.pSrcList = p->pSrc;
  61283. sNC.pNext = pOuterNC;
  61284. /* Resolve names in the result set. */
  61285. pEList = p->pEList;
  61286. assert( pEList!=0 );
  61287. for(i=0; i<pEList->nExpr; i++){
  61288. Expr *pX = pEList->a[i].pExpr;
  61289. if( sqlite3ResolveExprNames(&sNC, pX) ){
  61290. return WRC_Abort;
  61291. }
  61292. }
  61293. /* If there are no aggregate functions in the result-set, and no GROUP BY
  61294. ** expression, do not allow aggregates in any of the other expressions.
  61295. */
  61296. assert( (p->selFlags & SF_Aggregate)==0 );
  61297. pGroupBy = p->pGroupBy;
  61298. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  61299. p->selFlags |= SF_Aggregate;
  61300. }else{
  61301. sNC.ncFlags &= ~NC_AllowAgg;
  61302. }
  61303. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  61304. */
  61305. if( p->pHaving && !pGroupBy ){
  61306. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  61307. return WRC_Abort;
  61308. }
  61309. /* Add the output column list to the name-context before parsing the
  61310. ** other expressions in the SELECT statement. This is so that
  61311. ** expressions in the WHERE clause (etc.) can refer to expressions by
  61312. ** aliases in the result set.
  61313. **
  61314. ** Minor point: If this is the case, then the expression will be
  61315. ** re-evaluated for each reference to it.
  61316. */
  61317. sNC.pEList = p->pEList;
  61318. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  61319. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  61320. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  61321. ** outer queries
  61322. */
  61323. sNC.pNext = 0;
  61324. sNC.ncFlags |= NC_AllowAgg;
  61325. /* Process the ORDER BY clause for singleton SELECT statements.
  61326. ** The ORDER BY clause for compounds SELECT statements is handled
  61327. ** below, after all of the result-sets for all of the elements of
  61328. ** the compound have been resolved.
  61329. */
  61330. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  61331. return WRC_Abort;
  61332. }
  61333. if( db->mallocFailed ){
  61334. return WRC_Abort;
  61335. }
  61336. /* Resolve the GROUP BY clause. At the same time, make sure
  61337. ** the GROUP BY clause does not contain aggregate functions.
  61338. */
  61339. if( pGroupBy ){
  61340. struct ExprList_item *pItem;
  61341. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  61342. return WRC_Abort;
  61343. }
  61344. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  61345. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  61346. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  61347. "the GROUP BY clause");
  61348. return WRC_Abort;
  61349. }
  61350. }
  61351. }
  61352. /* Advance to the next term of the compound
  61353. */
  61354. p = p->pPrior;
  61355. nCompound++;
  61356. }
  61357. /* Resolve the ORDER BY on a compound SELECT after all terms of
  61358. ** the compound have been resolved.
  61359. */
  61360. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  61361. return WRC_Abort;
  61362. }
  61363. return WRC_Prune;
  61364. }
  61365. /*
  61366. ** This routine walks an expression tree and resolves references to
  61367. ** table columns and result-set columns. At the same time, do error
  61368. ** checking on function usage and set a flag if any aggregate functions
  61369. ** are seen.
  61370. **
  61371. ** To resolve table columns references we look for nodes (or subtrees) of the
  61372. ** form X.Y.Z or Y.Z or just Z where
  61373. **
  61374. ** X: The name of a database. Ex: "main" or "temp" or
  61375. ** the symbolic name assigned to an ATTACH-ed database.
  61376. **
  61377. ** Y: The name of a table in a FROM clause. Or in a trigger
  61378. ** one of the special names "old" or "new".
  61379. **
  61380. ** Z: The name of a column in table Y.
  61381. **
  61382. ** The node at the root of the subtree is modified as follows:
  61383. **
  61384. ** Expr.op Changed to TK_COLUMN
  61385. ** Expr.pTab Points to the Table object for X.Y
  61386. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  61387. ** Expr.iTable The VDBE cursor number for X.Y
  61388. **
  61389. **
  61390. ** To resolve result-set references, look for expression nodes of the
  61391. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  61392. ** size of an AS clause in the result-set of a SELECT. The Z expression
  61393. ** is replaced by a copy of the left-hand side of the result-set expression.
  61394. ** Table-name and function resolution occurs on the substituted expression
  61395. ** tree. For example, in:
  61396. **
  61397. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  61398. **
  61399. ** The "x" term of the order by is replaced by "a+b" to render:
  61400. **
  61401. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  61402. **
  61403. ** Function calls are checked to make sure that the function is
  61404. ** defined and that the correct number of arguments are specified.
  61405. ** If the function is an aggregate function, then the NC_HasAgg flag is
  61406. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  61407. ** If an expression contains aggregate functions then the EP_Agg
  61408. ** property on the expression is set.
  61409. **
  61410. ** An error message is left in pParse if anything is amiss. The number
  61411. ** if errors is returned.
  61412. */
  61413. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  61414. NameContext *pNC, /* Namespace to resolve expressions in. */
  61415. Expr *pExpr /* The expression to be analyzed. */
  61416. ){
  61417. u8 savedHasAgg;
  61418. Walker w;
  61419. if( pExpr==0 ) return 0;
  61420. #if SQLITE_MAX_EXPR_DEPTH>0
  61421. {
  61422. Parse *pParse = pNC->pParse;
  61423. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  61424. return 1;
  61425. }
  61426. pParse->nHeight += pExpr->nHeight;
  61427. }
  61428. #endif
  61429. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  61430. pNC->ncFlags &= ~NC_HasAgg;
  61431. memset(&w, 0, sizeof(w));
  61432. w.xExprCallback = resolveExprStep;
  61433. w.xSelectCallback = resolveSelectStep;
  61434. w.pParse = pNC->pParse;
  61435. w.u.pNC = pNC;
  61436. sqlite3WalkExpr(&w, pExpr);
  61437. #if SQLITE_MAX_EXPR_DEPTH>0
  61438. pNC->pParse->nHeight -= pExpr->nHeight;
  61439. #endif
  61440. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  61441. ExprSetProperty(pExpr, EP_Error);
  61442. }
  61443. if( pNC->ncFlags & NC_HasAgg ){
  61444. ExprSetProperty(pExpr, EP_Agg);
  61445. }else if( savedHasAgg ){
  61446. pNC->ncFlags |= NC_HasAgg;
  61447. }
  61448. return ExprHasProperty(pExpr, EP_Error);
  61449. }
  61450. /*
  61451. ** Resolve all names in all expressions of a SELECT and in all
  61452. ** decendents of the SELECT, including compounds off of p->pPrior,
  61453. ** subqueries in expressions, and subqueries used as FROM clause
  61454. ** terms.
  61455. **
  61456. ** See sqlite3ResolveExprNames() for a description of the kinds of
  61457. ** transformations that occur.
  61458. **
  61459. ** All SELECT statements should have been expanded using
  61460. ** sqlite3SelectExpand() prior to invoking this routine.
  61461. */
  61462. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  61463. Parse *pParse, /* The parser context */
  61464. Select *p, /* The SELECT statement being coded. */
  61465. NameContext *pOuterNC /* Name context for parent SELECT statement */
  61466. ){
  61467. Walker w;
  61468. assert( p!=0 );
  61469. memset(&w, 0, sizeof(w));
  61470. w.xExprCallback = resolveExprStep;
  61471. w.xSelectCallback = resolveSelectStep;
  61472. w.pParse = pParse;
  61473. w.u.pNC = pOuterNC;
  61474. sqlite3WalkSelect(&w, p);
  61475. }
  61476. /*
  61477. ** Resolve names in expressions that can only reference a single table:
  61478. **
  61479. ** * CHECK constraints
  61480. ** * WHERE clauses on partial indices
  61481. **
  61482. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  61483. ** is set to -1 and the Expr.iColumn value is set to the column number.
  61484. **
  61485. ** Any errors cause an error message to be set in pParse.
  61486. */
  61487. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  61488. Parse *pParse, /* Parsing context */
  61489. Table *pTab, /* The table being referenced */
  61490. int type, /* NC_IsCheck or NC_PartIdx */
  61491. Expr *pExpr, /* Expression to resolve. May be NULL. */
  61492. ExprList *pList /* Expression list to resolve. May be NUL. */
  61493. ){
  61494. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  61495. NameContext sNC; /* Name context for pParse->pNewTable */
  61496. int i; /* Loop counter */
  61497. assert( type==NC_IsCheck || type==NC_PartIdx );
  61498. memset(&sNC, 0, sizeof(sNC));
  61499. memset(&sSrc, 0, sizeof(sSrc));
  61500. sSrc.nSrc = 1;
  61501. sSrc.a[0].zName = pTab->zName;
  61502. sSrc.a[0].pTab = pTab;
  61503. sSrc.a[0].iCursor = -1;
  61504. sNC.pParse = pParse;
  61505. sNC.pSrcList = &sSrc;
  61506. sNC.ncFlags = type;
  61507. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  61508. if( pList ){
  61509. for(i=0; i<pList->nExpr; i++){
  61510. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  61511. return;
  61512. }
  61513. }
  61514. }
  61515. }
  61516. /************** End of resolve.c *********************************************/
  61517. /************** Begin file expr.c ********************************************/
  61518. /*
  61519. ** 2001 September 15
  61520. **
  61521. ** The author disclaims copyright to this source code. In place of
  61522. ** a legal notice, here is a blessing:
  61523. **
  61524. ** May you do good and not evil.
  61525. ** May you find forgiveness for yourself and forgive others.
  61526. ** May you share freely, never taking more than you give.
  61527. **
  61528. *************************************************************************
  61529. ** This file contains routines used for analyzing expressions and
  61530. ** for generating VDBE code that evaluates expressions in SQLite.
  61531. */
  61532. /*
  61533. ** Return the 'affinity' of the expression pExpr if any.
  61534. **
  61535. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  61536. ** or a sub-select with a column as the return value, then the
  61537. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  61538. ** indicating no affinity for the expression.
  61539. **
  61540. ** i.e. the WHERE clause expresssions in the following statements all
  61541. ** have an affinity:
  61542. **
  61543. ** CREATE TABLE t1(a);
  61544. ** SELECT * FROM t1 WHERE a;
  61545. ** SELECT a AS b FROM t1 WHERE b;
  61546. ** SELECT * FROM t1 WHERE (select a from t1);
  61547. */
  61548. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  61549. int op;
  61550. pExpr = sqlite3ExprSkipCollate(pExpr);
  61551. op = pExpr->op;
  61552. if( op==TK_SELECT ){
  61553. assert( pExpr->flags&EP_xIsSelect );
  61554. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  61555. }
  61556. #ifndef SQLITE_OMIT_CAST
  61557. if( op==TK_CAST ){
  61558. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  61559. return sqlite3AffinityType(pExpr->u.zToken, 0);
  61560. }
  61561. #endif
  61562. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  61563. && pExpr->pTab!=0
  61564. ){
  61565. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  61566. ** a TK_COLUMN but was previously evaluated and cached in a register */
  61567. int j = pExpr->iColumn;
  61568. if( j<0 ) return SQLITE_AFF_INTEGER;
  61569. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  61570. return pExpr->pTab->aCol[j].affinity;
  61571. }
  61572. return pExpr->affinity;
  61573. }
  61574. /*
  61575. ** Set the collating sequence for expression pExpr to be the collating
  61576. ** sequence named by pToken. Return a pointer to a new Expr node that
  61577. ** implements the COLLATE operator.
  61578. **
  61579. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  61580. ** and the pExpr parameter is returned unchanged.
  61581. */
  61582. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  61583. if( pCollName->n>0 ){
  61584. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  61585. if( pNew ){
  61586. pNew->pLeft = pExpr;
  61587. pNew->flags |= EP_Collate|EP_Skip;
  61588. pExpr = pNew;
  61589. }
  61590. }
  61591. return pExpr;
  61592. }
  61593. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  61594. Token s;
  61595. assert( zC!=0 );
  61596. s.z = zC;
  61597. s.n = sqlite3Strlen30(s.z);
  61598. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  61599. }
  61600. /*
  61601. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  61602. ** or likelihood() function at the root of an expression.
  61603. */
  61604. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  61605. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  61606. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  61607. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  61608. assert( pExpr->x.pList->nExpr>0 );
  61609. assert( pExpr->op==TK_FUNCTION );
  61610. pExpr = pExpr->x.pList->a[0].pExpr;
  61611. }else{
  61612. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  61613. pExpr = pExpr->pLeft;
  61614. }
  61615. }
  61616. return pExpr;
  61617. }
  61618. /*
  61619. ** Return the collation sequence for the expression pExpr. If
  61620. ** there is no defined collating sequence, return NULL.
  61621. **
  61622. ** The collating sequence might be determined by a COLLATE operator
  61623. ** or by the presence of a column with a defined collating sequence.
  61624. ** COLLATE operators take first precedence. Left operands take
  61625. ** precedence over right operands.
  61626. */
  61627. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  61628. sqlite3 *db = pParse->db;
  61629. CollSeq *pColl = 0;
  61630. Expr *p = pExpr;
  61631. while( p ){
  61632. int op = p->op;
  61633. if( op==TK_CAST || op==TK_UPLUS ){
  61634. p = p->pLeft;
  61635. continue;
  61636. }
  61637. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  61638. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  61639. break;
  61640. }
  61641. if( p->pTab!=0
  61642. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  61643. || op==TK_REGISTER || op==TK_TRIGGER)
  61644. ){
  61645. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  61646. ** a TK_COLUMN but was previously evaluated and cached in a register */
  61647. int j = p->iColumn;
  61648. if( j>=0 ){
  61649. const char *zColl = p->pTab->aCol[j].zColl;
  61650. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  61651. }
  61652. break;
  61653. }
  61654. if( p->flags & EP_Collate ){
  61655. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  61656. p = p->pLeft;
  61657. }else{
  61658. p = p->pRight;
  61659. }
  61660. }else{
  61661. break;
  61662. }
  61663. }
  61664. if( sqlite3CheckCollSeq(pParse, pColl) ){
  61665. pColl = 0;
  61666. }
  61667. return pColl;
  61668. }
  61669. /*
  61670. ** pExpr is an operand of a comparison operator. aff2 is the
  61671. ** type affinity of the other operand. This routine returns the
  61672. ** type affinity that should be used for the comparison operator.
  61673. */
  61674. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  61675. char aff1 = sqlite3ExprAffinity(pExpr);
  61676. if( aff1 && aff2 ){
  61677. /* Both sides of the comparison are columns. If one has numeric
  61678. ** affinity, use that. Otherwise use no affinity.
  61679. */
  61680. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  61681. return SQLITE_AFF_NUMERIC;
  61682. }else{
  61683. return SQLITE_AFF_NONE;
  61684. }
  61685. }else if( !aff1 && !aff2 ){
  61686. /* Neither side of the comparison is a column. Compare the
  61687. ** results directly.
  61688. */
  61689. return SQLITE_AFF_NONE;
  61690. }else{
  61691. /* One side is a column, the other is not. Use the columns affinity. */
  61692. assert( aff1==0 || aff2==0 );
  61693. return (aff1 + aff2);
  61694. }
  61695. }
  61696. /*
  61697. ** pExpr is a comparison operator. Return the type affinity that should
  61698. ** be applied to both operands prior to doing the comparison.
  61699. */
  61700. static char comparisonAffinity(Expr *pExpr){
  61701. char aff;
  61702. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  61703. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  61704. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  61705. assert( pExpr->pLeft );
  61706. aff = sqlite3ExprAffinity(pExpr->pLeft);
  61707. if( pExpr->pRight ){
  61708. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  61709. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  61710. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  61711. }else if( !aff ){
  61712. aff = SQLITE_AFF_NONE;
  61713. }
  61714. return aff;
  61715. }
  61716. /*
  61717. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  61718. ** idx_affinity is the affinity of an indexed column. Return true
  61719. ** if the index with affinity idx_affinity may be used to implement
  61720. ** the comparison in pExpr.
  61721. */
  61722. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  61723. char aff = comparisonAffinity(pExpr);
  61724. switch( aff ){
  61725. case SQLITE_AFF_NONE:
  61726. return 1;
  61727. case SQLITE_AFF_TEXT:
  61728. return idx_affinity==SQLITE_AFF_TEXT;
  61729. default:
  61730. return sqlite3IsNumericAffinity(idx_affinity);
  61731. }
  61732. }
  61733. /*
  61734. ** Return the P5 value that should be used for a binary comparison
  61735. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  61736. */
  61737. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  61738. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  61739. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  61740. return aff;
  61741. }
  61742. /*
  61743. ** Return a pointer to the collation sequence that should be used by
  61744. ** a binary comparison operator comparing pLeft and pRight.
  61745. **
  61746. ** If the left hand expression has a collating sequence type, then it is
  61747. ** used. Otherwise the collation sequence for the right hand expression
  61748. ** is used, or the default (BINARY) if neither expression has a collating
  61749. ** type.
  61750. **
  61751. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  61752. ** it is not considered.
  61753. */
  61754. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  61755. Parse *pParse,
  61756. Expr *pLeft,
  61757. Expr *pRight
  61758. ){
  61759. CollSeq *pColl;
  61760. assert( pLeft );
  61761. if( pLeft->flags & EP_Collate ){
  61762. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  61763. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  61764. pColl = sqlite3ExprCollSeq(pParse, pRight);
  61765. }else{
  61766. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  61767. if( !pColl ){
  61768. pColl = sqlite3ExprCollSeq(pParse, pRight);
  61769. }
  61770. }
  61771. return pColl;
  61772. }
  61773. /*
  61774. ** Generate code for a comparison operator.
  61775. */
  61776. static int codeCompare(
  61777. Parse *pParse, /* The parsing (and code generating) context */
  61778. Expr *pLeft, /* The left operand */
  61779. Expr *pRight, /* The right operand */
  61780. int opcode, /* The comparison opcode */
  61781. int in1, int in2, /* Register holding operands */
  61782. int dest, /* Jump here if true. */
  61783. int jumpIfNull /* If true, jump if either operand is NULL */
  61784. ){
  61785. int p5;
  61786. int addr;
  61787. CollSeq *p4;
  61788. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  61789. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  61790. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  61791. (void*)p4, P4_COLLSEQ);
  61792. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  61793. return addr;
  61794. }
  61795. #if SQLITE_MAX_EXPR_DEPTH>0
  61796. /*
  61797. ** Check that argument nHeight is less than or equal to the maximum
  61798. ** expression depth allowed. If it is not, leave an error message in
  61799. ** pParse.
  61800. */
  61801. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  61802. int rc = SQLITE_OK;
  61803. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  61804. if( nHeight>mxHeight ){
  61805. sqlite3ErrorMsg(pParse,
  61806. "Expression tree is too large (maximum depth %d)", mxHeight
  61807. );
  61808. rc = SQLITE_ERROR;
  61809. }
  61810. return rc;
  61811. }
  61812. /* The following three functions, heightOfExpr(), heightOfExprList()
  61813. ** and heightOfSelect(), are used to determine the maximum height
  61814. ** of any expression tree referenced by the structure passed as the
  61815. ** first argument.
  61816. **
  61817. ** If this maximum height is greater than the current value pointed
  61818. ** to by pnHeight, the second parameter, then set *pnHeight to that
  61819. ** value.
  61820. */
  61821. static void heightOfExpr(Expr *p, int *pnHeight){
  61822. if( p ){
  61823. if( p->nHeight>*pnHeight ){
  61824. *pnHeight = p->nHeight;
  61825. }
  61826. }
  61827. }
  61828. static void heightOfExprList(ExprList *p, int *pnHeight){
  61829. if( p ){
  61830. int i;
  61831. for(i=0; i<p->nExpr; i++){
  61832. heightOfExpr(p->a[i].pExpr, pnHeight);
  61833. }
  61834. }
  61835. }
  61836. static void heightOfSelect(Select *p, int *pnHeight){
  61837. if( p ){
  61838. heightOfExpr(p->pWhere, pnHeight);
  61839. heightOfExpr(p->pHaving, pnHeight);
  61840. heightOfExpr(p->pLimit, pnHeight);
  61841. heightOfExpr(p->pOffset, pnHeight);
  61842. heightOfExprList(p->pEList, pnHeight);
  61843. heightOfExprList(p->pGroupBy, pnHeight);
  61844. heightOfExprList(p->pOrderBy, pnHeight);
  61845. heightOfSelect(p->pPrior, pnHeight);
  61846. }
  61847. }
  61848. /*
  61849. ** Set the Expr.nHeight variable in the structure passed as an
  61850. ** argument. An expression with no children, Expr.pList or
  61851. ** Expr.pSelect member has a height of 1. Any other expression
  61852. ** has a height equal to the maximum height of any other
  61853. ** referenced Expr plus one.
  61854. */
  61855. static void exprSetHeight(Expr *p){
  61856. int nHeight = 0;
  61857. heightOfExpr(p->pLeft, &nHeight);
  61858. heightOfExpr(p->pRight, &nHeight);
  61859. if( ExprHasProperty(p, EP_xIsSelect) ){
  61860. heightOfSelect(p->x.pSelect, &nHeight);
  61861. }else{
  61862. heightOfExprList(p->x.pList, &nHeight);
  61863. }
  61864. p->nHeight = nHeight + 1;
  61865. }
  61866. /*
  61867. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  61868. ** the height is greater than the maximum allowed expression depth,
  61869. ** leave an error in pParse.
  61870. */
  61871. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  61872. exprSetHeight(p);
  61873. sqlite3ExprCheckHeight(pParse, p->nHeight);
  61874. }
  61875. /*
  61876. ** Return the maximum height of any expression tree referenced
  61877. ** by the select statement passed as an argument.
  61878. */
  61879. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  61880. int nHeight = 0;
  61881. heightOfSelect(p, &nHeight);
  61882. return nHeight;
  61883. }
  61884. #else
  61885. #define exprSetHeight(y)
  61886. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  61887. /*
  61888. ** This routine is the core allocator for Expr nodes.
  61889. **
  61890. ** Construct a new expression node and return a pointer to it. Memory
  61891. ** for this node and for the pToken argument is a single allocation
  61892. ** obtained from sqlite3DbMalloc(). The calling function
  61893. ** is responsible for making sure the node eventually gets freed.
  61894. **
  61895. ** If dequote is true, then the token (if it exists) is dequoted.
  61896. ** If dequote is false, no dequoting is performance. The deQuote
  61897. ** parameter is ignored if pToken is NULL or if the token does not
  61898. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  61899. ** then the EP_DblQuoted flag is set on the expression node.
  61900. **
  61901. ** Special case: If op==TK_INTEGER and pToken points to a string that
  61902. ** can be translated into a 32-bit integer, then the token is not
  61903. ** stored in u.zToken. Instead, the integer values is written
  61904. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  61905. ** is allocated to hold the integer text and the dequote flag is ignored.
  61906. */
  61907. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  61908. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  61909. int op, /* Expression opcode */
  61910. const Token *pToken, /* Token argument. Might be NULL */
  61911. int dequote /* True to dequote */
  61912. ){
  61913. Expr *pNew;
  61914. int nExtra = 0;
  61915. int iValue = 0;
  61916. if( pToken ){
  61917. if( op!=TK_INTEGER || pToken->z==0
  61918. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  61919. nExtra = pToken->n+1;
  61920. assert( iValue>=0 );
  61921. }
  61922. }
  61923. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  61924. if( pNew ){
  61925. pNew->op = (u8)op;
  61926. pNew->iAgg = -1;
  61927. if( pToken ){
  61928. if( nExtra==0 ){
  61929. pNew->flags |= EP_IntValue;
  61930. pNew->u.iValue = iValue;
  61931. }else{
  61932. int c;
  61933. pNew->u.zToken = (char*)&pNew[1];
  61934. assert( pToken->z!=0 || pToken->n==0 );
  61935. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  61936. pNew->u.zToken[pToken->n] = 0;
  61937. if( dequote && nExtra>=3
  61938. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  61939. sqlite3Dequote(pNew->u.zToken);
  61940. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  61941. }
  61942. }
  61943. }
  61944. #if SQLITE_MAX_EXPR_DEPTH>0
  61945. pNew->nHeight = 1;
  61946. #endif
  61947. }
  61948. return pNew;
  61949. }
  61950. /*
  61951. ** Allocate a new expression node from a zero-terminated token that has
  61952. ** already been dequoted.
  61953. */
  61954. SQLITE_PRIVATE Expr *sqlite3Expr(
  61955. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  61956. int op, /* Expression opcode */
  61957. const char *zToken /* Token argument. Might be NULL */
  61958. ){
  61959. Token x;
  61960. x.z = zToken;
  61961. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  61962. return sqlite3ExprAlloc(db, op, &x, 0);
  61963. }
  61964. /*
  61965. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  61966. **
  61967. ** If pRoot==NULL that means that a memory allocation error has occurred.
  61968. ** In that case, delete the subtrees pLeft and pRight.
  61969. */
  61970. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  61971. sqlite3 *db,
  61972. Expr *pRoot,
  61973. Expr *pLeft,
  61974. Expr *pRight
  61975. ){
  61976. if( pRoot==0 ){
  61977. assert( db->mallocFailed );
  61978. sqlite3ExprDelete(db, pLeft);
  61979. sqlite3ExprDelete(db, pRight);
  61980. }else{
  61981. if( pRight ){
  61982. pRoot->pRight = pRight;
  61983. pRoot->flags |= EP_Collate & pRight->flags;
  61984. }
  61985. if( pLeft ){
  61986. pRoot->pLeft = pLeft;
  61987. pRoot->flags |= EP_Collate & pLeft->flags;
  61988. }
  61989. exprSetHeight(pRoot);
  61990. }
  61991. }
  61992. /*
  61993. ** Allocate a Expr node which joins as many as two subtrees.
  61994. **
  61995. ** One or both of the subtrees can be NULL. Return a pointer to the new
  61996. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  61997. ** free the subtrees and return NULL.
  61998. */
  61999. SQLITE_PRIVATE Expr *sqlite3PExpr(
  62000. Parse *pParse, /* Parsing context */
  62001. int op, /* Expression opcode */
  62002. Expr *pLeft, /* Left operand */
  62003. Expr *pRight, /* Right operand */
  62004. const Token *pToken /* Argument token */
  62005. ){
  62006. Expr *p;
  62007. if( op==TK_AND && pLeft && pRight ){
  62008. /* Take advantage of short-circuit false optimization for AND */
  62009. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  62010. }else{
  62011. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  62012. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  62013. }
  62014. if( p ) {
  62015. sqlite3ExprCheckHeight(pParse, p->nHeight);
  62016. }
  62017. return p;
  62018. }
  62019. /*
  62020. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  62021. ** expression might be true. This is an optimization. If is OK to
  62022. ** return 0 here even if the expression really is always false (a
  62023. ** false negative). But it is a bug to return 1 if the expression
  62024. ** might be true in some rare circumstances (a false positive.)
  62025. **
  62026. ** Note that if the expression is part of conditional for a
  62027. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  62028. ** is it true or false, so always return 0.
  62029. */
  62030. static int exprAlwaysFalse(Expr *p){
  62031. int v = 0;
  62032. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  62033. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  62034. return v==0;
  62035. }
  62036. /*
  62037. ** Join two expressions using an AND operator. If either expression is
  62038. ** NULL, then just return the other expression.
  62039. **
  62040. ** If one side or the other of the AND is known to be false, then instead
  62041. ** of returning an AND expression, just return a constant expression with
  62042. ** a value of false.
  62043. */
  62044. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  62045. if( pLeft==0 ){
  62046. return pRight;
  62047. }else if( pRight==0 ){
  62048. return pLeft;
  62049. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  62050. sqlite3ExprDelete(db, pLeft);
  62051. sqlite3ExprDelete(db, pRight);
  62052. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  62053. }else{
  62054. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  62055. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  62056. return pNew;
  62057. }
  62058. }
  62059. /*
  62060. ** Construct a new expression node for a function with multiple
  62061. ** arguments.
  62062. */
  62063. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  62064. Expr *pNew;
  62065. sqlite3 *db = pParse->db;
  62066. assert( pToken );
  62067. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  62068. if( pNew==0 ){
  62069. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  62070. return 0;
  62071. }
  62072. pNew->x.pList = pList;
  62073. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  62074. sqlite3ExprSetHeight(pParse, pNew);
  62075. return pNew;
  62076. }
  62077. /*
  62078. ** Assign a variable number to an expression that encodes a wildcard
  62079. ** in the original SQL statement.
  62080. **
  62081. ** Wildcards consisting of a single "?" are assigned the next sequential
  62082. ** variable number.
  62083. **
  62084. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  62085. ** sure "nnn" is not too be to avoid a denial of service attack when
  62086. ** the SQL statement comes from an external source.
  62087. **
  62088. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  62089. ** as the previous instance of the same wildcard. Or if this is the first
  62090. ** instance of the wildcard, the next sequenial variable number is
  62091. ** assigned.
  62092. */
  62093. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  62094. sqlite3 *db = pParse->db;
  62095. const char *z;
  62096. if( pExpr==0 ) return;
  62097. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  62098. z = pExpr->u.zToken;
  62099. assert( z!=0 );
  62100. assert( z[0]!=0 );
  62101. if( z[1]==0 ){
  62102. /* Wildcard of the form "?". Assign the next variable number */
  62103. assert( z[0]=='?' );
  62104. pExpr->iColumn = (ynVar)(++pParse->nVar);
  62105. }else{
  62106. ynVar x = 0;
  62107. u32 n = sqlite3Strlen30(z);
  62108. if( z[0]=='?' ){
  62109. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  62110. ** use it as the variable number */
  62111. i64 i;
  62112. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  62113. pExpr->iColumn = x = (ynVar)i;
  62114. testcase( i==0 );
  62115. testcase( i==1 );
  62116. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  62117. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  62118. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  62119. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  62120. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  62121. x = 0;
  62122. }
  62123. if( i>pParse->nVar ){
  62124. pParse->nVar = (int)i;
  62125. }
  62126. }else{
  62127. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  62128. ** number as the prior appearance of the same name, or if the name
  62129. ** has never appeared before, reuse the same variable number
  62130. */
  62131. ynVar i;
  62132. for(i=0; i<pParse->nzVar; i++){
  62133. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  62134. pExpr->iColumn = x = (ynVar)i+1;
  62135. break;
  62136. }
  62137. }
  62138. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  62139. }
  62140. if( x>0 ){
  62141. if( x>pParse->nzVar ){
  62142. char **a;
  62143. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  62144. if( a==0 ) return; /* Error reported through db->mallocFailed */
  62145. pParse->azVar = a;
  62146. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  62147. pParse->nzVar = x;
  62148. }
  62149. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  62150. sqlite3DbFree(db, pParse->azVar[x-1]);
  62151. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  62152. }
  62153. }
  62154. }
  62155. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  62156. sqlite3ErrorMsg(pParse, "too many SQL variables");
  62157. }
  62158. }
  62159. /*
  62160. ** Recursively delete an expression tree.
  62161. */
  62162. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  62163. if( p==0 ) return;
  62164. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  62165. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  62166. if( !ExprHasProperty(p, EP_TokenOnly) ){
  62167. /* The Expr.x union is never used at the same time as Expr.pRight */
  62168. assert( p->x.pList==0 || p->pRight==0 );
  62169. sqlite3ExprDelete(db, p->pLeft);
  62170. sqlite3ExprDelete(db, p->pRight);
  62171. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  62172. if( ExprHasProperty(p, EP_xIsSelect) ){
  62173. sqlite3SelectDelete(db, p->x.pSelect);
  62174. }else{
  62175. sqlite3ExprListDelete(db, p->x.pList);
  62176. }
  62177. }
  62178. if( !ExprHasProperty(p, EP_Static) ){
  62179. sqlite3DbFree(db, p);
  62180. }
  62181. }
  62182. /*
  62183. ** Return the number of bytes allocated for the expression structure
  62184. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  62185. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  62186. */
  62187. static int exprStructSize(Expr *p){
  62188. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  62189. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  62190. return EXPR_FULLSIZE;
  62191. }
  62192. /*
  62193. ** The dupedExpr*Size() routines each return the number of bytes required
  62194. ** to store a copy of an expression or expression tree. They differ in
  62195. ** how much of the tree is measured.
  62196. **
  62197. ** dupedExprStructSize() Size of only the Expr structure
  62198. ** dupedExprNodeSize() Size of Expr + space for token
  62199. ** dupedExprSize() Expr + token + subtree components
  62200. **
  62201. ***************************************************************************
  62202. **
  62203. ** The dupedExprStructSize() function returns two values OR-ed together:
  62204. ** (1) the space required for a copy of the Expr structure only and
  62205. ** (2) the EP_xxx flags that indicate what the structure size should be.
  62206. ** The return values is always one of:
  62207. **
  62208. ** EXPR_FULLSIZE
  62209. ** EXPR_REDUCEDSIZE | EP_Reduced
  62210. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  62211. **
  62212. ** The size of the structure can be found by masking the return value
  62213. ** of this routine with 0xfff. The flags can be found by masking the
  62214. ** return value with EP_Reduced|EP_TokenOnly.
  62215. **
  62216. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  62217. ** (unreduced) Expr objects as they or originally constructed by the parser.
  62218. ** During expression analysis, extra information is computed and moved into
  62219. ** later parts of teh Expr object and that extra information might get chopped
  62220. ** off if the expression is reduced. Note also that it does not work to
  62221. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  62222. ** to reduce a pristine expression tree from the parser. The implementation
  62223. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  62224. ** to enforce this constraint.
  62225. */
  62226. static int dupedExprStructSize(Expr *p, int flags){
  62227. int nSize;
  62228. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  62229. assert( EXPR_FULLSIZE<=0xfff );
  62230. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  62231. if( 0==(flags&EXPRDUP_REDUCE) ){
  62232. nSize = EXPR_FULLSIZE;
  62233. }else{
  62234. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  62235. assert( !ExprHasProperty(p, EP_FromJoin) );
  62236. assert( !ExprHasProperty(p, EP_MemToken) );
  62237. assert( !ExprHasProperty(p, EP_NoReduce) );
  62238. if( p->pLeft || p->x.pList ){
  62239. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  62240. }else{
  62241. assert( p->pRight==0 );
  62242. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  62243. }
  62244. }
  62245. return nSize;
  62246. }
  62247. /*
  62248. ** This function returns the space in bytes required to store the copy
  62249. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  62250. ** string is defined.)
  62251. */
  62252. static int dupedExprNodeSize(Expr *p, int flags){
  62253. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  62254. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  62255. nByte += sqlite3Strlen30(p->u.zToken)+1;
  62256. }
  62257. return ROUND8(nByte);
  62258. }
  62259. /*
  62260. ** Return the number of bytes required to create a duplicate of the
  62261. ** expression passed as the first argument. The second argument is a
  62262. ** mask containing EXPRDUP_XXX flags.
  62263. **
  62264. ** The value returned includes space to create a copy of the Expr struct
  62265. ** itself and the buffer referred to by Expr.u.zToken, if any.
  62266. **
  62267. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  62268. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  62269. ** and Expr.pRight variables (but not for any structures pointed to or
  62270. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  62271. */
  62272. static int dupedExprSize(Expr *p, int flags){
  62273. int nByte = 0;
  62274. if( p ){
  62275. nByte = dupedExprNodeSize(p, flags);
  62276. if( flags&EXPRDUP_REDUCE ){
  62277. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  62278. }
  62279. }
  62280. return nByte;
  62281. }
  62282. /*
  62283. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  62284. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  62285. ** to store the copy of expression p, the copies of p->u.zToken
  62286. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  62287. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  62288. ** portion of the buffer copied into by this function.
  62289. */
  62290. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  62291. Expr *pNew = 0; /* Value to return */
  62292. if( p ){
  62293. const int isReduced = (flags&EXPRDUP_REDUCE);
  62294. u8 *zAlloc;
  62295. u32 staticFlag = 0;
  62296. assert( pzBuffer==0 || isReduced );
  62297. /* Figure out where to write the new Expr structure. */
  62298. if( pzBuffer ){
  62299. zAlloc = *pzBuffer;
  62300. staticFlag = EP_Static;
  62301. }else{
  62302. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  62303. }
  62304. pNew = (Expr *)zAlloc;
  62305. if( pNew ){
  62306. /* Set nNewSize to the size allocated for the structure pointed to
  62307. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  62308. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  62309. ** by the copy of the p->u.zToken string (if any).
  62310. */
  62311. const unsigned nStructSize = dupedExprStructSize(p, flags);
  62312. const int nNewSize = nStructSize & 0xfff;
  62313. int nToken;
  62314. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  62315. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  62316. }else{
  62317. nToken = 0;
  62318. }
  62319. if( isReduced ){
  62320. assert( ExprHasProperty(p, EP_Reduced)==0 );
  62321. memcpy(zAlloc, p, nNewSize);
  62322. }else{
  62323. int nSize = exprStructSize(p);
  62324. memcpy(zAlloc, p, nSize);
  62325. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  62326. }
  62327. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  62328. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  62329. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  62330. pNew->flags |= staticFlag;
  62331. /* Copy the p->u.zToken string, if any. */
  62332. if( nToken ){
  62333. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  62334. memcpy(zToken, p->u.zToken, nToken);
  62335. }
  62336. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  62337. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  62338. if( ExprHasProperty(p, EP_xIsSelect) ){
  62339. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  62340. }else{
  62341. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  62342. }
  62343. }
  62344. /* Fill in pNew->pLeft and pNew->pRight. */
  62345. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  62346. zAlloc += dupedExprNodeSize(p, flags);
  62347. if( ExprHasProperty(pNew, EP_Reduced) ){
  62348. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  62349. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  62350. }
  62351. if( pzBuffer ){
  62352. *pzBuffer = zAlloc;
  62353. }
  62354. }else{
  62355. if( !ExprHasProperty(p, EP_TokenOnly) ){
  62356. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  62357. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  62358. }
  62359. }
  62360. }
  62361. }
  62362. return pNew;
  62363. }
  62364. /*
  62365. ** The following group of routines make deep copies of expressions,
  62366. ** expression lists, ID lists, and select statements. The copies can
  62367. ** be deleted (by being passed to their respective ...Delete() routines)
  62368. ** without effecting the originals.
  62369. **
  62370. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  62371. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  62372. ** by subsequent calls to sqlite*ListAppend() routines.
  62373. **
  62374. ** Any tables that the SrcList might point to are not duplicated.
  62375. **
  62376. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  62377. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  62378. ** truncated version of the usual Expr structure that will be stored as
  62379. ** part of the in-memory representation of the database schema.
  62380. */
  62381. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  62382. return exprDup(db, p, flags, 0);
  62383. }
  62384. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  62385. ExprList *pNew;
  62386. struct ExprList_item *pItem, *pOldItem;
  62387. int i;
  62388. if( p==0 ) return 0;
  62389. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  62390. if( pNew==0 ) return 0;
  62391. pNew->iECursor = 0;
  62392. pNew->nExpr = i = p->nExpr;
  62393. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  62394. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  62395. if( pItem==0 ){
  62396. sqlite3DbFree(db, pNew);
  62397. return 0;
  62398. }
  62399. pOldItem = p->a;
  62400. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  62401. Expr *pOldExpr = pOldItem->pExpr;
  62402. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  62403. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62404. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  62405. pItem->sortOrder = pOldItem->sortOrder;
  62406. pItem->done = 0;
  62407. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  62408. pItem->iOrderByCol = pOldItem->iOrderByCol;
  62409. pItem->iAlias = pOldItem->iAlias;
  62410. }
  62411. return pNew;
  62412. }
  62413. /*
  62414. ** If cursors, triggers, views and subqueries are all omitted from
  62415. ** the build, then none of the following routines, except for
  62416. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  62417. ** called with a NULL argument.
  62418. */
  62419. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  62420. || !defined(SQLITE_OMIT_SUBQUERY)
  62421. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  62422. SrcList *pNew;
  62423. int i;
  62424. int nByte;
  62425. if( p==0 ) return 0;
  62426. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  62427. pNew = sqlite3DbMallocRaw(db, nByte );
  62428. if( pNew==0 ) return 0;
  62429. pNew->nSrc = pNew->nAlloc = p->nSrc;
  62430. for(i=0; i<p->nSrc; i++){
  62431. struct SrcList_item *pNewItem = &pNew->a[i];
  62432. struct SrcList_item *pOldItem = &p->a[i];
  62433. Table *pTab;
  62434. pNewItem->pSchema = pOldItem->pSchema;
  62435. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  62436. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62437. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  62438. pNewItem->jointype = pOldItem->jointype;
  62439. pNewItem->iCursor = pOldItem->iCursor;
  62440. pNewItem->addrFillSub = pOldItem->addrFillSub;
  62441. pNewItem->regReturn = pOldItem->regReturn;
  62442. pNewItem->isCorrelated = pOldItem->isCorrelated;
  62443. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  62444. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  62445. pNewItem->notIndexed = pOldItem->notIndexed;
  62446. pNewItem->pIndex = pOldItem->pIndex;
  62447. pTab = pNewItem->pTab = pOldItem->pTab;
  62448. if( pTab ){
  62449. pTab->nRef++;
  62450. }
  62451. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  62452. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  62453. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  62454. pNewItem->colUsed = pOldItem->colUsed;
  62455. }
  62456. return pNew;
  62457. }
  62458. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  62459. IdList *pNew;
  62460. int i;
  62461. if( p==0 ) return 0;
  62462. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  62463. if( pNew==0 ) return 0;
  62464. pNew->nId = p->nId;
  62465. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  62466. if( pNew->a==0 ){
  62467. sqlite3DbFree(db, pNew);
  62468. return 0;
  62469. }
  62470. /* Note that because the size of the allocation for p->a[] is not
  62471. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  62472. ** on the duplicate created by this function. */
  62473. for(i=0; i<p->nId; i++){
  62474. struct IdList_item *pNewItem = &pNew->a[i];
  62475. struct IdList_item *pOldItem = &p->a[i];
  62476. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  62477. pNewItem->idx = pOldItem->idx;
  62478. }
  62479. return pNew;
  62480. }
  62481. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  62482. Select *pNew, *pPrior;
  62483. if( p==0 ) return 0;
  62484. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  62485. if( pNew==0 ) return 0;
  62486. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  62487. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  62488. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  62489. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  62490. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  62491. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  62492. pNew->op = p->op;
  62493. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  62494. if( pPrior ) pPrior->pNext = pNew;
  62495. pNew->pNext = 0;
  62496. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  62497. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  62498. pNew->iLimit = 0;
  62499. pNew->iOffset = 0;
  62500. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  62501. pNew->pRightmost = 0;
  62502. pNew->addrOpenEphm[0] = -1;
  62503. pNew->addrOpenEphm[1] = -1;
  62504. pNew->addrOpenEphm[2] = -1;
  62505. return pNew;
  62506. }
  62507. #else
  62508. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  62509. assert( p==0 );
  62510. return 0;
  62511. }
  62512. #endif
  62513. /*
  62514. ** Add a new element to the end of an expression list. If pList is
  62515. ** initially NULL, then create a new expression list.
  62516. **
  62517. ** If a memory allocation error occurs, the entire list is freed and
  62518. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  62519. ** that the new entry was successfully appended.
  62520. */
  62521. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  62522. Parse *pParse, /* Parsing context */
  62523. ExprList *pList, /* List to which to append. Might be NULL */
  62524. Expr *pExpr /* Expression to be appended. Might be NULL */
  62525. ){
  62526. sqlite3 *db = pParse->db;
  62527. if( pList==0 ){
  62528. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  62529. if( pList==0 ){
  62530. goto no_mem;
  62531. }
  62532. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  62533. if( pList->a==0 ) goto no_mem;
  62534. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  62535. struct ExprList_item *a;
  62536. assert( pList->nExpr>0 );
  62537. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  62538. if( a==0 ){
  62539. goto no_mem;
  62540. }
  62541. pList->a = a;
  62542. }
  62543. assert( pList->a!=0 );
  62544. if( 1 ){
  62545. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  62546. memset(pItem, 0, sizeof(*pItem));
  62547. pItem->pExpr = pExpr;
  62548. }
  62549. return pList;
  62550. no_mem:
  62551. /* Avoid leaking memory if malloc has failed. */
  62552. sqlite3ExprDelete(db, pExpr);
  62553. sqlite3ExprListDelete(db, pList);
  62554. return 0;
  62555. }
  62556. /*
  62557. ** Set the ExprList.a[].zName element of the most recently added item
  62558. ** on the expression list.
  62559. **
  62560. ** pList might be NULL following an OOM error. But pName should never be
  62561. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  62562. ** is set.
  62563. */
  62564. SQLITE_PRIVATE void sqlite3ExprListSetName(
  62565. Parse *pParse, /* Parsing context */
  62566. ExprList *pList, /* List to which to add the span. */
  62567. Token *pName, /* Name to be added */
  62568. int dequote /* True to cause the name to be dequoted */
  62569. ){
  62570. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  62571. if( pList ){
  62572. struct ExprList_item *pItem;
  62573. assert( pList->nExpr>0 );
  62574. pItem = &pList->a[pList->nExpr-1];
  62575. assert( pItem->zName==0 );
  62576. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  62577. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  62578. }
  62579. }
  62580. /*
  62581. ** Set the ExprList.a[].zSpan element of the most recently added item
  62582. ** on the expression list.
  62583. **
  62584. ** pList might be NULL following an OOM error. But pSpan should never be
  62585. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  62586. ** is set.
  62587. */
  62588. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  62589. Parse *pParse, /* Parsing context */
  62590. ExprList *pList, /* List to which to add the span. */
  62591. ExprSpan *pSpan /* The span to be added */
  62592. ){
  62593. sqlite3 *db = pParse->db;
  62594. assert( pList!=0 || db->mallocFailed!=0 );
  62595. if( pList ){
  62596. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  62597. assert( pList->nExpr>0 );
  62598. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  62599. sqlite3DbFree(db, pItem->zSpan);
  62600. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  62601. (int)(pSpan->zEnd - pSpan->zStart));
  62602. }
  62603. }
  62604. /*
  62605. ** If the expression list pEList contains more than iLimit elements,
  62606. ** leave an error message in pParse.
  62607. */
  62608. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  62609. Parse *pParse,
  62610. ExprList *pEList,
  62611. const char *zObject
  62612. ){
  62613. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  62614. testcase( pEList && pEList->nExpr==mx );
  62615. testcase( pEList && pEList->nExpr==mx+1 );
  62616. if( pEList && pEList->nExpr>mx ){
  62617. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  62618. }
  62619. }
  62620. /*
  62621. ** Delete an entire expression list.
  62622. */
  62623. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  62624. int i;
  62625. struct ExprList_item *pItem;
  62626. if( pList==0 ) return;
  62627. assert( pList->a!=0 || pList->nExpr==0 );
  62628. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  62629. sqlite3ExprDelete(db, pItem->pExpr);
  62630. sqlite3DbFree(db, pItem->zName);
  62631. sqlite3DbFree(db, pItem->zSpan);
  62632. }
  62633. sqlite3DbFree(db, pList->a);
  62634. sqlite3DbFree(db, pList);
  62635. }
  62636. /*
  62637. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  62638. ** to an integer. These routines are checking an expression to see
  62639. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  62640. ** not constant.
  62641. **
  62642. ** These callback routines are used to implement the following:
  62643. **
  62644. ** sqlite3ExprIsConstant()
  62645. ** sqlite3ExprIsConstantNotJoin()
  62646. ** sqlite3ExprIsConstantOrFunction()
  62647. **
  62648. */
  62649. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  62650. /* If pWalker->u.i is 3 then any term of the expression that comes from
  62651. ** the ON or USING clauses of a join disqualifies the expression
  62652. ** from being considered constant. */
  62653. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  62654. pWalker->u.i = 0;
  62655. return WRC_Abort;
  62656. }
  62657. switch( pExpr->op ){
  62658. /* Consider functions to be constant if all their arguments are constant
  62659. ** and pWalker->u.i==2 */
  62660. case TK_FUNCTION:
  62661. if( pWalker->u.i==2 ) return 0;
  62662. /* Fall through */
  62663. case TK_ID:
  62664. case TK_COLUMN:
  62665. case TK_AGG_FUNCTION:
  62666. case TK_AGG_COLUMN:
  62667. testcase( pExpr->op==TK_ID );
  62668. testcase( pExpr->op==TK_COLUMN );
  62669. testcase( pExpr->op==TK_AGG_FUNCTION );
  62670. testcase( pExpr->op==TK_AGG_COLUMN );
  62671. pWalker->u.i = 0;
  62672. return WRC_Abort;
  62673. default:
  62674. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  62675. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  62676. return WRC_Continue;
  62677. }
  62678. }
  62679. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  62680. UNUSED_PARAMETER(NotUsed);
  62681. pWalker->u.i = 0;
  62682. return WRC_Abort;
  62683. }
  62684. static int exprIsConst(Expr *p, int initFlag){
  62685. Walker w;
  62686. memset(&w, 0, sizeof(w));
  62687. w.u.i = initFlag;
  62688. w.xExprCallback = exprNodeIsConstant;
  62689. w.xSelectCallback = selectNodeIsConstant;
  62690. sqlite3WalkExpr(&w, p);
  62691. return w.u.i;
  62692. }
  62693. /*
  62694. ** Walk an expression tree. Return 1 if the expression is constant
  62695. ** and 0 if it involves variables or function calls.
  62696. **
  62697. ** For the purposes of this function, a double-quoted string (ex: "abc")
  62698. ** is considered a variable but a single-quoted string (ex: 'abc') is
  62699. ** a constant.
  62700. */
  62701. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  62702. return exprIsConst(p, 1);
  62703. }
  62704. /*
  62705. ** Walk an expression tree. Return 1 if the expression is constant
  62706. ** that does no originate from the ON or USING clauses of a join.
  62707. ** Return 0 if it involves variables or function calls or terms from
  62708. ** an ON or USING clause.
  62709. */
  62710. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  62711. return exprIsConst(p, 3);
  62712. }
  62713. /*
  62714. ** Walk an expression tree. Return 1 if the expression is constant
  62715. ** or a function call with constant arguments. Return and 0 if there
  62716. ** are any variables.
  62717. **
  62718. ** For the purposes of this function, a double-quoted string (ex: "abc")
  62719. ** is considered a variable but a single-quoted string (ex: 'abc') is
  62720. ** a constant.
  62721. */
  62722. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  62723. return exprIsConst(p, 2);
  62724. }
  62725. /*
  62726. ** If the expression p codes a constant integer that is small enough
  62727. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  62728. ** in *pValue. If the expression is not an integer or if it is too big
  62729. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  62730. */
  62731. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  62732. int rc = 0;
  62733. /* If an expression is an integer literal that fits in a signed 32-bit
  62734. ** integer, then the EP_IntValue flag will have already been set */
  62735. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  62736. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  62737. if( p->flags & EP_IntValue ){
  62738. *pValue = p->u.iValue;
  62739. return 1;
  62740. }
  62741. switch( p->op ){
  62742. case TK_UPLUS: {
  62743. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  62744. break;
  62745. }
  62746. case TK_UMINUS: {
  62747. int v;
  62748. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  62749. assert( v!=(-2147483647-1) );
  62750. *pValue = -v;
  62751. rc = 1;
  62752. }
  62753. break;
  62754. }
  62755. default: break;
  62756. }
  62757. return rc;
  62758. }
  62759. /*
  62760. ** Return FALSE if there is no chance that the expression can be NULL.
  62761. **
  62762. ** If the expression might be NULL or if the expression is too complex
  62763. ** to tell return TRUE.
  62764. **
  62765. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  62766. ** when we know that a value cannot be NULL. Hence, a false positive
  62767. ** (returning TRUE when in fact the expression can never be NULL) might
  62768. ** be a small performance hit but is otherwise harmless. On the other
  62769. ** hand, a false negative (returning FALSE when the result could be NULL)
  62770. ** will likely result in an incorrect answer. So when in doubt, return
  62771. ** TRUE.
  62772. */
  62773. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  62774. u8 op;
  62775. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  62776. op = p->op;
  62777. if( op==TK_REGISTER ) op = p->op2;
  62778. switch( op ){
  62779. case TK_INTEGER:
  62780. case TK_STRING:
  62781. case TK_FLOAT:
  62782. case TK_BLOB:
  62783. return 0;
  62784. default:
  62785. return 1;
  62786. }
  62787. }
  62788. /*
  62789. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  62790. ** to location iDest if the value in iReg is NULL. The value in iReg
  62791. ** was computed by pExpr. If we can look at pExpr at compile-time and
  62792. ** determine that it can never generate a NULL, then the OP_IsNull operation
  62793. ** can be omitted.
  62794. */
  62795. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  62796. Vdbe *v, /* The VDBE under construction */
  62797. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  62798. int iReg, /* Test the value in this register for NULL */
  62799. int iDest /* Jump here if the value is null */
  62800. ){
  62801. if( sqlite3ExprCanBeNull(pExpr) ){
  62802. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  62803. }
  62804. }
  62805. /*
  62806. ** Return TRUE if the given expression is a constant which would be
  62807. ** unchanged by OP_Affinity with the affinity given in the second
  62808. ** argument.
  62809. **
  62810. ** This routine is used to determine if the OP_Affinity operation
  62811. ** can be omitted. When in doubt return FALSE. A false negative
  62812. ** is harmless. A false positive, however, can result in the wrong
  62813. ** answer.
  62814. */
  62815. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  62816. u8 op;
  62817. if( aff==SQLITE_AFF_NONE ) return 1;
  62818. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  62819. op = p->op;
  62820. if( op==TK_REGISTER ) op = p->op2;
  62821. switch( op ){
  62822. case TK_INTEGER: {
  62823. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  62824. }
  62825. case TK_FLOAT: {
  62826. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  62827. }
  62828. case TK_STRING: {
  62829. return aff==SQLITE_AFF_TEXT;
  62830. }
  62831. case TK_BLOB: {
  62832. return 1;
  62833. }
  62834. case TK_COLUMN: {
  62835. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  62836. return p->iColumn<0
  62837. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  62838. }
  62839. default: {
  62840. return 0;
  62841. }
  62842. }
  62843. }
  62844. /*
  62845. ** Return TRUE if the given string is a row-id column name.
  62846. */
  62847. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  62848. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  62849. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  62850. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  62851. return 0;
  62852. }
  62853. /*
  62854. ** Return true if we are able to the IN operator optimization on a
  62855. ** query of the form
  62856. **
  62857. ** x IN (SELECT ...)
  62858. **
  62859. ** Where the SELECT... clause is as specified by the parameter to this
  62860. ** routine.
  62861. **
  62862. ** The Select object passed in has already been preprocessed and no
  62863. ** errors have been found.
  62864. */
  62865. #ifndef SQLITE_OMIT_SUBQUERY
  62866. static int isCandidateForInOpt(Select *p){
  62867. SrcList *pSrc;
  62868. ExprList *pEList;
  62869. Table *pTab;
  62870. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  62871. if( p->pPrior ) return 0; /* Not a compound SELECT */
  62872. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  62873. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  62874. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  62875. return 0; /* No DISTINCT keyword and no aggregate functions */
  62876. }
  62877. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  62878. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  62879. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  62880. if( p->pWhere ) return 0; /* Has no WHERE clause */
  62881. pSrc = p->pSrc;
  62882. assert( pSrc!=0 );
  62883. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  62884. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  62885. pTab = pSrc->a[0].pTab;
  62886. if( NEVER(pTab==0) ) return 0;
  62887. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  62888. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  62889. pEList = p->pEList;
  62890. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  62891. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  62892. return 1;
  62893. }
  62894. #endif /* SQLITE_OMIT_SUBQUERY */
  62895. /*
  62896. ** Code an OP_Once instruction and allocate space for its flag. Return the
  62897. ** address of the new instruction.
  62898. */
  62899. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  62900. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  62901. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  62902. }
  62903. /*
  62904. ** This function is used by the implementation of the IN (...) operator.
  62905. ** The pX parameter is the expression on the RHS of the IN operator, which
  62906. ** might be either a list of expressions or a subquery.
  62907. **
  62908. ** The job of this routine is to find or create a b-tree object that can
  62909. ** be used either to test for membership in the RHS set or to iterate through
  62910. ** all members of the RHS set, skipping duplicates.
  62911. **
  62912. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  62913. ** and pX->iTable is set to the index of that cursor.
  62914. **
  62915. ** The returned value of this function indicates the b-tree type, as follows:
  62916. **
  62917. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  62918. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  62919. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  62920. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  62921. ** populated epheremal table.
  62922. **
  62923. ** An existing b-tree might be used if the RHS expression pX is a simple
  62924. ** subquery such as:
  62925. **
  62926. ** SELECT <column> FROM <table>
  62927. **
  62928. ** If the RHS of the IN operator is a list or a more complex subquery, then
  62929. ** an ephemeral table might need to be generated from the RHS and then
  62930. ** pX->iTable made to point to the ephermeral table instead of an
  62931. ** existing table.
  62932. **
  62933. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  62934. ** through the set members, skipping any duplicates. In this case an
  62935. ** epheremal table must be used unless the selected <column> is guaranteed
  62936. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  62937. ** has a UNIQUE constraint or UNIQUE index.
  62938. **
  62939. ** If the prNotFound parameter is not 0, then the b-tree will be used
  62940. ** for fast set membership tests. In this case an epheremal table must
  62941. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  62942. ** be found with <column> as its left-most column.
  62943. **
  62944. ** When the b-tree is being used for membership tests, the calling function
  62945. ** needs to know whether or not the structure contains an SQL NULL
  62946. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  62947. ** If there is any chance that the (...) might contain a NULL value at
  62948. ** runtime, then a register is allocated and the register number written
  62949. ** to *prNotFound. If there is no chance that the (...) contains a
  62950. ** NULL value, then *prNotFound is left unchanged.
  62951. **
  62952. ** If a register is allocated and its location stored in *prNotFound, then
  62953. ** its initial value is NULL. If the (...) does not remain constant
  62954. ** for the duration of the query (i.e. the SELECT within the (...)
  62955. ** is a correlated subquery) then the value of the allocated register is
  62956. ** reset to NULL each time the subquery is rerun. This allows the
  62957. ** caller to use vdbe code equivalent to the following:
  62958. **
  62959. ** if( register==NULL ){
  62960. ** has_null = <test if data structure contains null>
  62961. ** register = 1
  62962. ** }
  62963. **
  62964. ** in order to avoid running the <test if data structure contains null>
  62965. ** test more often than is necessary.
  62966. */
  62967. #ifndef SQLITE_OMIT_SUBQUERY
  62968. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  62969. Select *p; /* SELECT to the right of IN operator */
  62970. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  62971. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  62972. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  62973. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  62974. assert( pX->op==TK_IN );
  62975. /* Check to see if an existing table or index can be used to
  62976. ** satisfy the query. This is preferable to generating a new
  62977. ** ephemeral table.
  62978. */
  62979. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  62980. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  62981. sqlite3 *db = pParse->db; /* Database connection */
  62982. Table *pTab; /* Table <table>. */
  62983. Expr *pExpr; /* Expression <column> */
  62984. int iCol; /* Index of column <column> */
  62985. int iDb; /* Database idx for pTab */
  62986. assert( p ); /* Because of isCandidateForInOpt(p) */
  62987. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  62988. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  62989. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  62990. pTab = p->pSrc->a[0].pTab;
  62991. pExpr = p->pEList->a[0].pExpr;
  62992. iCol = pExpr->iColumn;
  62993. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  62994. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  62995. sqlite3CodeVerifySchema(pParse, iDb);
  62996. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  62997. /* This function is only called from two places. In both cases the vdbe
  62998. ** has already been allocated. So assume sqlite3GetVdbe() is always
  62999. ** successful here.
  63000. */
  63001. assert(v);
  63002. if( iCol<0 ){
  63003. int iAddr;
  63004. iAddr = sqlite3CodeOnce(pParse);
  63005. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  63006. eType = IN_INDEX_ROWID;
  63007. sqlite3VdbeJumpHere(v, iAddr);
  63008. }else{
  63009. Index *pIdx; /* Iterator variable */
  63010. /* The collation sequence used by the comparison. If an index is to
  63011. ** be used in place of a temp-table, it must be ordered according
  63012. ** to this collation sequence. */
  63013. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  63014. /* Check that the affinity that will be used to perform the
  63015. ** comparison is the same as the affinity of the column. If
  63016. ** it is not, it is not possible to use any index.
  63017. */
  63018. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  63019. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  63020. if( (pIdx->aiColumn[0]==iCol)
  63021. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  63022. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  63023. ){
  63024. int iAddr;
  63025. char *pKey;
  63026. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  63027. iAddr = sqlite3CodeOnce(pParse);
  63028. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  63029. pKey,P4_KEYINFO_HANDOFF);
  63030. VdbeComment((v, "%s", pIdx->zName));
  63031. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  63032. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  63033. sqlite3VdbeJumpHere(v, iAddr);
  63034. if( prNotFound && !pTab->aCol[iCol].notNull ){
  63035. *prNotFound = ++pParse->nMem;
  63036. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  63037. }
  63038. }
  63039. }
  63040. }
  63041. }
  63042. if( eType==0 ){
  63043. /* Could not found an existing table or index to use as the RHS b-tree.
  63044. ** We will have to generate an ephemeral table to do the job.
  63045. */
  63046. u32 savedNQueryLoop = pParse->nQueryLoop;
  63047. int rMayHaveNull = 0;
  63048. eType = IN_INDEX_EPH;
  63049. if( prNotFound ){
  63050. *prNotFound = rMayHaveNull = ++pParse->nMem;
  63051. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  63052. }else{
  63053. testcase( pParse->nQueryLoop>0 );
  63054. pParse->nQueryLoop = 0;
  63055. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  63056. eType = IN_INDEX_ROWID;
  63057. }
  63058. }
  63059. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  63060. pParse->nQueryLoop = savedNQueryLoop;
  63061. }else{
  63062. pX->iTable = iTab;
  63063. }
  63064. return eType;
  63065. }
  63066. #endif
  63067. /*
  63068. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  63069. ** or IN operators. Examples:
  63070. **
  63071. ** (SELECT a FROM b) -- subquery
  63072. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  63073. ** x IN (4,5,11) -- IN operator with list on right-hand side
  63074. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  63075. **
  63076. ** The pExpr parameter describes the expression that contains the IN
  63077. ** operator or subquery.
  63078. **
  63079. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  63080. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  63081. ** to some integer key column of a table B-Tree. In this case, use an
  63082. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  63083. ** (slower) variable length keys B-Tree.
  63084. **
  63085. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  63086. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  63087. ** Furthermore, the IN is in a WHERE clause and that we really want
  63088. ** to iterate over the RHS of the IN operator in order to quickly locate
  63089. ** all corresponding LHS elements. All this routine does is initialize
  63090. ** the register given by rMayHaveNull to NULL. Calling routines will take
  63091. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  63092. **
  63093. ** If rMayHaveNull is zero, that means that the subquery is being used
  63094. ** for membership testing only. There is no need to initialize any
  63095. ** registers to indicate the presence or absence of NULLs on the RHS.
  63096. **
  63097. ** For a SELECT or EXISTS operator, return the register that holds the
  63098. ** result. For IN operators or if an error occurs, the return value is 0.
  63099. */
  63100. #ifndef SQLITE_OMIT_SUBQUERY
  63101. SQLITE_PRIVATE int sqlite3CodeSubselect(
  63102. Parse *pParse, /* Parsing context */
  63103. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  63104. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  63105. int isRowid /* If true, LHS of IN operator is a rowid */
  63106. ){
  63107. int testAddr = -1; /* One-time test address */
  63108. int rReg = 0; /* Register storing resulting */
  63109. Vdbe *v = sqlite3GetVdbe(pParse);
  63110. if( NEVER(v==0) ) return 0;
  63111. sqlite3ExprCachePush(pParse);
  63112. /* This code must be run in its entirety every time it is encountered
  63113. ** if any of the following is true:
  63114. **
  63115. ** * The right-hand side is a correlated subquery
  63116. ** * The right-hand side is an expression list containing variables
  63117. ** * We are inside a trigger
  63118. **
  63119. ** If all of the above are false, then we can run this code just once
  63120. ** save the results, and reuse the same result on subsequent invocations.
  63121. */
  63122. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  63123. testAddr = sqlite3CodeOnce(pParse);
  63124. }
  63125. #ifndef SQLITE_OMIT_EXPLAIN
  63126. if( pParse->explain==2 ){
  63127. char *zMsg = sqlite3MPrintf(
  63128. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  63129. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  63130. );
  63131. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  63132. }
  63133. #endif
  63134. switch( pExpr->op ){
  63135. case TK_IN: {
  63136. char affinity; /* Affinity of the LHS of the IN */
  63137. int addr; /* Address of OP_OpenEphemeral instruction */
  63138. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  63139. KeyInfo *pKeyInfo = 0; /* Key information */
  63140. if( rMayHaveNull ){
  63141. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  63142. }
  63143. affinity = sqlite3ExprAffinity(pLeft);
  63144. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  63145. ** expression it is handled the same way. An ephemeral table is
  63146. ** filled with single-field index keys representing the results
  63147. ** from the SELECT or the <exprlist>.
  63148. **
  63149. ** If the 'x' expression is a column value, or the SELECT...
  63150. ** statement returns a column value, then the affinity of that
  63151. ** column is used to build the index keys. If both 'x' and the
  63152. ** SELECT... statement are columns, then numeric affinity is used
  63153. ** if either column has NUMERIC or INTEGER affinity. If neither
  63154. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  63155. ** is used.
  63156. */
  63157. pExpr->iTable = pParse->nTab++;
  63158. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  63159. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  63160. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  63161. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  63162. /* Case 1: expr IN (SELECT ...)
  63163. **
  63164. ** Generate code to write the results of the select into the temporary
  63165. ** table allocated and opened above.
  63166. */
  63167. SelectDest dest;
  63168. ExprList *pEList;
  63169. assert( !isRowid );
  63170. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  63171. dest.affSdst = (u8)affinity;
  63172. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  63173. pExpr->x.pSelect->iLimit = 0;
  63174. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  63175. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  63176. sqlite3DbFree(pParse->db, pKeyInfo);
  63177. return 0;
  63178. }
  63179. pEList = pExpr->x.pSelect->pEList;
  63180. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  63181. assert( pEList!=0 );
  63182. assert( pEList->nExpr>0 );
  63183. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  63184. pEList->a[0].pExpr);
  63185. }else if( ALWAYS(pExpr->x.pList!=0) ){
  63186. /* Case 2: expr IN (exprlist)
  63187. **
  63188. ** For each expression, build an index key from the evaluation and
  63189. ** store it in the temporary table. If <expr> is a column, then use
  63190. ** that columns affinity when building index keys. If <expr> is not
  63191. ** a column, use numeric affinity.
  63192. */
  63193. int i;
  63194. ExprList *pList = pExpr->x.pList;
  63195. struct ExprList_item *pItem;
  63196. int r1, r2, r3;
  63197. if( !affinity ){
  63198. affinity = SQLITE_AFF_NONE;
  63199. }
  63200. if( pKeyInfo ){
  63201. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  63202. }
  63203. /* Loop through each expression in <exprlist>. */
  63204. r1 = sqlite3GetTempReg(pParse);
  63205. r2 = sqlite3GetTempReg(pParse);
  63206. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  63207. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  63208. Expr *pE2 = pItem->pExpr;
  63209. int iValToIns;
  63210. /* If the expression is not constant then we will need to
  63211. ** disable the test that was generated above that makes sure
  63212. ** this code only executes once. Because for a non-constant
  63213. ** expression we need to rerun this code each time.
  63214. */
  63215. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  63216. sqlite3VdbeChangeToNoop(v, testAddr);
  63217. testAddr = -1;
  63218. }
  63219. /* Evaluate the expression and insert it into the temp table */
  63220. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  63221. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  63222. }else{
  63223. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  63224. if( isRowid ){
  63225. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  63226. sqlite3VdbeCurrentAddr(v)+2);
  63227. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  63228. }else{
  63229. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  63230. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  63231. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  63232. }
  63233. }
  63234. }
  63235. sqlite3ReleaseTempReg(pParse, r1);
  63236. sqlite3ReleaseTempReg(pParse, r2);
  63237. }
  63238. if( pKeyInfo ){
  63239. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  63240. }
  63241. break;
  63242. }
  63243. case TK_EXISTS:
  63244. case TK_SELECT:
  63245. default: {
  63246. /* If this has to be a scalar SELECT. Generate code to put the
  63247. ** value of this select in a memory cell and record the number
  63248. ** of the memory cell in iColumn. If this is an EXISTS, write
  63249. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  63250. ** and record that memory cell in iColumn.
  63251. */
  63252. Select *pSel; /* SELECT statement to encode */
  63253. SelectDest dest; /* How to deal with SELECt result */
  63254. testcase( pExpr->op==TK_EXISTS );
  63255. testcase( pExpr->op==TK_SELECT );
  63256. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  63257. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  63258. pSel = pExpr->x.pSelect;
  63259. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  63260. if( pExpr->op==TK_SELECT ){
  63261. dest.eDest = SRT_Mem;
  63262. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  63263. VdbeComment((v, "Init subquery result"));
  63264. }else{
  63265. dest.eDest = SRT_Exists;
  63266. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  63267. VdbeComment((v, "Init EXISTS result"));
  63268. }
  63269. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  63270. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  63271. &sqlite3IntTokens[1]);
  63272. pSel->iLimit = 0;
  63273. if( sqlite3Select(pParse, pSel, &dest) ){
  63274. return 0;
  63275. }
  63276. rReg = dest.iSDParm;
  63277. ExprSetVVAProperty(pExpr, EP_NoReduce);
  63278. break;
  63279. }
  63280. }
  63281. if( testAddr>=0 ){
  63282. sqlite3VdbeJumpHere(v, testAddr);
  63283. }
  63284. sqlite3ExprCachePop(pParse, 1);
  63285. return rReg;
  63286. }
  63287. #endif /* SQLITE_OMIT_SUBQUERY */
  63288. #ifndef SQLITE_OMIT_SUBQUERY
  63289. /*
  63290. ** Generate code for an IN expression.
  63291. **
  63292. ** x IN (SELECT ...)
  63293. ** x IN (value, value, ...)
  63294. **
  63295. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  63296. ** is an array of zero or more values. The expression is true if the LHS is
  63297. ** contained within the RHS. The value of the expression is unknown (NULL)
  63298. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  63299. ** RHS contains one or more NULL values.
  63300. **
  63301. ** This routine generates code will jump to destIfFalse if the LHS is not
  63302. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  63303. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  63304. ** within the RHS then fall through.
  63305. */
  63306. static void sqlite3ExprCodeIN(
  63307. Parse *pParse, /* Parsing and code generating context */
  63308. Expr *pExpr, /* The IN expression */
  63309. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  63310. int destIfNull /* Jump here if the results are unknown due to NULLs */
  63311. ){
  63312. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  63313. char affinity; /* Comparison affinity to use */
  63314. int eType; /* Type of the RHS */
  63315. int r1; /* Temporary use register */
  63316. Vdbe *v; /* Statement under construction */
  63317. /* Compute the RHS. After this step, the table with cursor
  63318. ** pExpr->iTable will contains the values that make up the RHS.
  63319. */
  63320. v = pParse->pVdbe;
  63321. assert( v!=0 ); /* OOM detected prior to this routine */
  63322. VdbeNoopComment((v, "begin IN expr"));
  63323. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  63324. /* Figure out the affinity to use to create a key from the results
  63325. ** of the expression. affinityStr stores a static string suitable for
  63326. ** P4 of OP_MakeRecord.
  63327. */
  63328. affinity = comparisonAffinity(pExpr);
  63329. /* Code the LHS, the <expr> from "<expr> IN (...)".
  63330. */
  63331. sqlite3ExprCachePush(pParse);
  63332. r1 = sqlite3GetTempReg(pParse);
  63333. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  63334. /* If the LHS is NULL, then the result is either false or NULL depending
  63335. ** on whether the RHS is empty or not, respectively.
  63336. */
  63337. if( destIfNull==destIfFalse ){
  63338. /* Shortcut for the common case where the false and NULL outcomes are
  63339. ** the same. */
  63340. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  63341. }else{
  63342. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  63343. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  63344. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  63345. sqlite3VdbeJumpHere(v, addr1);
  63346. }
  63347. if( eType==IN_INDEX_ROWID ){
  63348. /* In this case, the RHS is the ROWID of table b-tree
  63349. */
  63350. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  63351. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  63352. }else{
  63353. /* In this case, the RHS is an index b-tree.
  63354. */
  63355. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  63356. /* If the set membership test fails, then the result of the
  63357. ** "x IN (...)" expression must be either 0 or NULL. If the set
  63358. ** contains no NULL values, then the result is 0. If the set
  63359. ** contains one or more NULL values, then the result of the
  63360. ** expression is also NULL.
  63361. */
  63362. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  63363. /* This branch runs if it is known at compile time that the RHS
  63364. ** cannot contain NULL values. This happens as the result
  63365. ** of a "NOT NULL" constraint in the database schema.
  63366. **
  63367. ** Also run this branch if NULL is equivalent to FALSE
  63368. ** for this particular IN operator.
  63369. */
  63370. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  63371. }else{
  63372. /* In this branch, the RHS of the IN might contain a NULL and
  63373. ** the presence of a NULL on the RHS makes a difference in the
  63374. ** outcome.
  63375. */
  63376. int j1, j2, j3;
  63377. /* First check to see if the LHS is contained in the RHS. If so,
  63378. ** then the presence of NULLs in the RHS does not matter, so jump
  63379. ** over all of the code that follows.
  63380. */
  63381. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  63382. /* Here we begin generating code that runs if the LHS is not
  63383. ** contained within the RHS. Generate additional code that
  63384. ** tests the RHS for NULLs. If the RHS contains a NULL then
  63385. ** jump to destIfNull. If there are no NULLs in the RHS then
  63386. ** jump to destIfFalse.
  63387. */
  63388. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  63389. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  63390. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  63391. sqlite3VdbeJumpHere(v, j3);
  63392. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  63393. sqlite3VdbeJumpHere(v, j2);
  63394. /* Jump to the appropriate target depending on whether or not
  63395. ** the RHS contains a NULL
  63396. */
  63397. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  63398. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  63399. /* The OP_Found at the top of this branch jumps here when true,
  63400. ** causing the overall IN expression evaluation to fall through.
  63401. */
  63402. sqlite3VdbeJumpHere(v, j1);
  63403. }
  63404. }
  63405. sqlite3ReleaseTempReg(pParse, r1);
  63406. sqlite3ExprCachePop(pParse, 1);
  63407. VdbeComment((v, "end IN expr"));
  63408. }
  63409. #endif /* SQLITE_OMIT_SUBQUERY */
  63410. /*
  63411. ** Duplicate an 8-byte value
  63412. */
  63413. static char *dup8bytes(Vdbe *v, const char *in){
  63414. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  63415. if( out ){
  63416. memcpy(out, in, 8);
  63417. }
  63418. return out;
  63419. }
  63420. #ifndef SQLITE_OMIT_FLOATING_POINT
  63421. /*
  63422. ** Generate an instruction that will put the floating point
  63423. ** value described by z[0..n-1] into register iMem.
  63424. **
  63425. ** The z[] string will probably not be zero-terminated. But the
  63426. ** z[n] character is guaranteed to be something that does not look
  63427. ** like the continuation of the number.
  63428. */
  63429. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  63430. if( ALWAYS(z!=0) ){
  63431. double value;
  63432. char *zV;
  63433. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  63434. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  63435. if( negateFlag ) value = -value;
  63436. zV = dup8bytes(v, (char*)&value);
  63437. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  63438. }
  63439. }
  63440. #endif
  63441. /*
  63442. ** Generate an instruction that will put the integer describe by
  63443. ** text z[0..n-1] into register iMem.
  63444. **
  63445. ** Expr.u.zToken is always UTF8 and zero-terminated.
  63446. */
  63447. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  63448. Vdbe *v = pParse->pVdbe;
  63449. if( pExpr->flags & EP_IntValue ){
  63450. int i = pExpr->u.iValue;
  63451. assert( i>=0 );
  63452. if( negFlag ) i = -i;
  63453. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  63454. }else{
  63455. int c;
  63456. i64 value;
  63457. const char *z = pExpr->u.zToken;
  63458. assert( z!=0 );
  63459. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  63460. if( c==0 || (c==2 && negFlag) ){
  63461. char *zV;
  63462. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  63463. zV = dup8bytes(v, (char*)&value);
  63464. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  63465. }else{
  63466. #ifdef SQLITE_OMIT_FLOATING_POINT
  63467. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  63468. #else
  63469. codeReal(v, z, negFlag, iMem);
  63470. #endif
  63471. }
  63472. }
  63473. }
  63474. /*
  63475. ** Clear a cache entry.
  63476. */
  63477. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  63478. if( p->tempReg ){
  63479. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  63480. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  63481. }
  63482. p->tempReg = 0;
  63483. }
  63484. }
  63485. /*
  63486. ** Record in the column cache that a particular column from a
  63487. ** particular table is stored in a particular register.
  63488. */
  63489. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  63490. int i;
  63491. int minLru;
  63492. int idxLru;
  63493. struct yColCache *p;
  63494. assert( iReg>0 ); /* Register numbers are always positive */
  63495. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  63496. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  63497. ** for testing only - to verify that SQLite always gets the same answer
  63498. ** with and without the column cache.
  63499. */
  63500. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  63501. /* First replace any existing entry.
  63502. **
  63503. ** Actually, the way the column cache is currently used, we are guaranteed
  63504. ** that the object will never already be in cache. Verify this guarantee.
  63505. */
  63506. #ifndef NDEBUG
  63507. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63508. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  63509. }
  63510. #endif
  63511. /* Find an empty slot and replace it */
  63512. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63513. if( p->iReg==0 ){
  63514. p->iLevel = pParse->iCacheLevel;
  63515. p->iTable = iTab;
  63516. p->iColumn = iCol;
  63517. p->iReg = iReg;
  63518. p->tempReg = 0;
  63519. p->lru = pParse->iCacheCnt++;
  63520. return;
  63521. }
  63522. }
  63523. /* Replace the last recently used */
  63524. minLru = 0x7fffffff;
  63525. idxLru = -1;
  63526. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63527. if( p->lru<minLru ){
  63528. idxLru = i;
  63529. minLru = p->lru;
  63530. }
  63531. }
  63532. if( ALWAYS(idxLru>=0) ){
  63533. p = &pParse->aColCache[idxLru];
  63534. p->iLevel = pParse->iCacheLevel;
  63535. p->iTable = iTab;
  63536. p->iColumn = iCol;
  63537. p->iReg = iReg;
  63538. p->tempReg = 0;
  63539. p->lru = pParse->iCacheCnt++;
  63540. return;
  63541. }
  63542. }
  63543. /*
  63544. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  63545. ** Purge the range of registers from the column cache.
  63546. */
  63547. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  63548. int i;
  63549. int iLast = iReg + nReg - 1;
  63550. struct yColCache *p;
  63551. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63552. int r = p->iReg;
  63553. if( r>=iReg && r<=iLast ){
  63554. cacheEntryClear(pParse, p);
  63555. p->iReg = 0;
  63556. }
  63557. }
  63558. }
  63559. /*
  63560. ** Remember the current column cache context. Any new entries added
  63561. ** added to the column cache after this call are removed when the
  63562. ** corresponding pop occurs.
  63563. */
  63564. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  63565. pParse->iCacheLevel++;
  63566. }
  63567. /*
  63568. ** Remove from the column cache any entries that were added since the
  63569. ** the previous N Push operations. In other words, restore the cache
  63570. ** to the state it was in N Pushes ago.
  63571. */
  63572. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  63573. int i;
  63574. struct yColCache *p;
  63575. assert( N>0 );
  63576. assert( pParse->iCacheLevel>=N );
  63577. pParse->iCacheLevel -= N;
  63578. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63579. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  63580. cacheEntryClear(pParse, p);
  63581. p->iReg = 0;
  63582. }
  63583. }
  63584. }
  63585. /*
  63586. ** When a cached column is reused, make sure that its register is
  63587. ** no longer available as a temp register. ticket #3879: that same
  63588. ** register might be in the cache in multiple places, so be sure to
  63589. ** get them all.
  63590. */
  63591. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  63592. int i;
  63593. struct yColCache *p;
  63594. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63595. if( p->iReg==iReg ){
  63596. p->tempReg = 0;
  63597. }
  63598. }
  63599. }
  63600. /*
  63601. ** Generate code to extract the value of the iCol-th column of a table.
  63602. */
  63603. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  63604. Vdbe *v, /* The VDBE under construction */
  63605. Table *pTab, /* The table containing the value */
  63606. int iTabCur, /* The cursor for this table */
  63607. int iCol, /* Index of the column to extract */
  63608. int regOut /* Extract the valud into this register */
  63609. ){
  63610. if( iCol<0 || iCol==pTab->iPKey ){
  63611. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  63612. }else{
  63613. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  63614. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  63615. }
  63616. if( iCol>=0 ){
  63617. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  63618. }
  63619. }
  63620. /*
  63621. ** Generate code that will extract the iColumn-th column from
  63622. ** table pTab and store the column value in a register. An effort
  63623. ** is made to store the column value in register iReg, but this is
  63624. ** not guaranteed. The location of the column value is returned.
  63625. **
  63626. ** There must be an open cursor to pTab in iTable when this routine
  63627. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  63628. */
  63629. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  63630. Parse *pParse, /* Parsing and code generating context */
  63631. Table *pTab, /* Description of the table we are reading from */
  63632. int iColumn, /* Index of the table column */
  63633. int iTable, /* The cursor pointing to the table */
  63634. int iReg, /* Store results here */
  63635. u8 p5 /* P5 value for OP_Column */
  63636. ){
  63637. Vdbe *v = pParse->pVdbe;
  63638. int i;
  63639. struct yColCache *p;
  63640. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63641. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  63642. p->lru = pParse->iCacheCnt++;
  63643. sqlite3ExprCachePinRegister(pParse, p->iReg);
  63644. return p->iReg;
  63645. }
  63646. }
  63647. assert( v!=0 );
  63648. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  63649. if( p5 ){
  63650. sqlite3VdbeChangeP5(v, p5);
  63651. }else{
  63652. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  63653. }
  63654. return iReg;
  63655. }
  63656. /*
  63657. ** Clear all column cache entries.
  63658. */
  63659. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  63660. int i;
  63661. struct yColCache *p;
  63662. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63663. if( p->iReg ){
  63664. cacheEntryClear(pParse, p);
  63665. p->iReg = 0;
  63666. }
  63667. }
  63668. }
  63669. /*
  63670. ** Record the fact that an affinity change has occurred on iCount
  63671. ** registers starting with iStart.
  63672. */
  63673. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  63674. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  63675. }
  63676. /*
  63677. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  63678. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  63679. */
  63680. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  63681. int i;
  63682. struct yColCache *p;
  63683. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  63684. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  63685. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63686. int x = p->iReg;
  63687. if( x>=iFrom && x<iFrom+nReg ){
  63688. p->iReg += iTo-iFrom;
  63689. }
  63690. }
  63691. }
  63692. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  63693. /*
  63694. ** Return true if any register in the range iFrom..iTo (inclusive)
  63695. ** is used as part of the column cache.
  63696. **
  63697. ** This routine is used within assert() and testcase() macros only
  63698. ** and does not appear in a normal build.
  63699. */
  63700. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  63701. int i;
  63702. struct yColCache *p;
  63703. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  63704. int r = p->iReg;
  63705. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  63706. }
  63707. return 0;
  63708. }
  63709. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  63710. /*
  63711. ** Convert an expression node to a TK_REGISTER
  63712. */
  63713. static void exprToRegister(Expr *p, int iReg){
  63714. p->op2 = p->op;
  63715. p->op = TK_REGISTER;
  63716. p->iTable = iReg;
  63717. ExprClearProperty(p, EP_Skip);
  63718. }
  63719. /*
  63720. ** Generate code into the current Vdbe to evaluate the given
  63721. ** expression. Attempt to store the results in register "target".
  63722. ** Return the register where results are stored.
  63723. **
  63724. ** With this routine, there is no guarantee that results will
  63725. ** be stored in target. The result might be stored in some other
  63726. ** register if it is convenient to do so. The calling function
  63727. ** must check the return code and move the results to the desired
  63728. ** register.
  63729. */
  63730. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  63731. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  63732. int op; /* The opcode being coded */
  63733. int inReg = target; /* Results stored in register inReg */
  63734. int regFree1 = 0; /* If non-zero free this temporary register */
  63735. int regFree2 = 0; /* If non-zero free this temporary register */
  63736. int r1, r2, r3, r4; /* Various register numbers */
  63737. sqlite3 *db = pParse->db; /* The database connection */
  63738. assert( target>0 && target<=pParse->nMem );
  63739. if( v==0 ){
  63740. assert( pParse->db->mallocFailed );
  63741. return 0;
  63742. }
  63743. if( pExpr==0 ){
  63744. op = TK_NULL;
  63745. }else{
  63746. op = pExpr->op;
  63747. }
  63748. switch( op ){
  63749. case TK_AGG_COLUMN: {
  63750. AggInfo *pAggInfo = pExpr->pAggInfo;
  63751. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  63752. if( !pAggInfo->directMode ){
  63753. assert( pCol->iMem>0 );
  63754. inReg = pCol->iMem;
  63755. break;
  63756. }else if( pAggInfo->useSortingIdx ){
  63757. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  63758. pCol->iSorterColumn, target);
  63759. break;
  63760. }
  63761. /* Otherwise, fall thru into the TK_COLUMN case */
  63762. }
  63763. case TK_COLUMN: {
  63764. int iTab = pExpr->iTable;
  63765. if( iTab<0 ){
  63766. if( pParse->ckBase>0 ){
  63767. /* Generating CHECK constraints or inserting into partial index */
  63768. inReg = pExpr->iColumn + pParse->ckBase;
  63769. break;
  63770. }else{
  63771. /* Deleting from a partial index */
  63772. iTab = pParse->iPartIdxTab;
  63773. }
  63774. }
  63775. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  63776. pExpr->iColumn, iTab, target,
  63777. pExpr->op2);
  63778. break;
  63779. }
  63780. case TK_INTEGER: {
  63781. codeInteger(pParse, pExpr, 0, target);
  63782. break;
  63783. }
  63784. #ifndef SQLITE_OMIT_FLOATING_POINT
  63785. case TK_FLOAT: {
  63786. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63787. codeReal(v, pExpr->u.zToken, 0, target);
  63788. break;
  63789. }
  63790. #endif
  63791. case TK_STRING: {
  63792. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63793. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  63794. break;
  63795. }
  63796. case TK_NULL: {
  63797. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  63798. break;
  63799. }
  63800. #ifndef SQLITE_OMIT_BLOB_LITERAL
  63801. case TK_BLOB: {
  63802. int n;
  63803. const char *z;
  63804. char *zBlob;
  63805. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63806. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  63807. assert( pExpr->u.zToken[1]=='\'' );
  63808. z = &pExpr->u.zToken[2];
  63809. n = sqlite3Strlen30(z) - 1;
  63810. assert( z[n]=='\'' );
  63811. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  63812. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  63813. break;
  63814. }
  63815. #endif
  63816. case TK_VARIABLE: {
  63817. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63818. assert( pExpr->u.zToken!=0 );
  63819. assert( pExpr->u.zToken[0]!=0 );
  63820. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  63821. if( pExpr->u.zToken[1]!=0 ){
  63822. assert( pExpr->u.zToken[0]=='?'
  63823. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  63824. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  63825. }
  63826. break;
  63827. }
  63828. case TK_REGISTER: {
  63829. inReg = pExpr->iTable;
  63830. break;
  63831. }
  63832. case TK_AS: {
  63833. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  63834. break;
  63835. }
  63836. #ifndef SQLITE_OMIT_CAST
  63837. case TK_CAST: {
  63838. /* Expressions of the form: CAST(pLeft AS token) */
  63839. int aff, to_op;
  63840. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  63841. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63842. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  63843. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  63844. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  63845. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  63846. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  63847. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  63848. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  63849. testcase( to_op==OP_ToText );
  63850. testcase( to_op==OP_ToBlob );
  63851. testcase( to_op==OP_ToNumeric );
  63852. testcase( to_op==OP_ToInt );
  63853. testcase( to_op==OP_ToReal );
  63854. if( inReg!=target ){
  63855. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  63856. inReg = target;
  63857. }
  63858. sqlite3VdbeAddOp1(v, to_op, inReg);
  63859. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  63860. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  63861. break;
  63862. }
  63863. #endif /* SQLITE_OMIT_CAST */
  63864. case TK_LT:
  63865. case TK_LE:
  63866. case TK_GT:
  63867. case TK_GE:
  63868. case TK_NE:
  63869. case TK_EQ: {
  63870. assert( TK_LT==OP_Lt );
  63871. assert( TK_LE==OP_Le );
  63872. assert( TK_GT==OP_Gt );
  63873. assert( TK_GE==OP_Ge );
  63874. assert( TK_EQ==OP_Eq );
  63875. assert( TK_NE==OP_Ne );
  63876. testcase( op==TK_LT );
  63877. testcase( op==TK_LE );
  63878. testcase( op==TK_GT );
  63879. testcase( op==TK_GE );
  63880. testcase( op==TK_EQ );
  63881. testcase( op==TK_NE );
  63882. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63883. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63884. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  63885. r1, r2, inReg, SQLITE_STOREP2);
  63886. testcase( regFree1==0 );
  63887. testcase( regFree2==0 );
  63888. break;
  63889. }
  63890. case TK_IS:
  63891. case TK_ISNOT: {
  63892. testcase( op==TK_IS );
  63893. testcase( op==TK_ISNOT );
  63894. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63895. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63896. op = (op==TK_IS) ? TK_EQ : TK_NE;
  63897. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  63898. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  63899. testcase( regFree1==0 );
  63900. testcase( regFree2==0 );
  63901. break;
  63902. }
  63903. case TK_AND:
  63904. case TK_OR:
  63905. case TK_PLUS:
  63906. case TK_STAR:
  63907. case TK_MINUS:
  63908. case TK_REM:
  63909. case TK_BITAND:
  63910. case TK_BITOR:
  63911. case TK_SLASH:
  63912. case TK_LSHIFT:
  63913. case TK_RSHIFT:
  63914. case TK_CONCAT: {
  63915. assert( TK_AND==OP_And );
  63916. assert( TK_OR==OP_Or );
  63917. assert( TK_PLUS==OP_Add );
  63918. assert( TK_MINUS==OP_Subtract );
  63919. assert( TK_REM==OP_Remainder );
  63920. assert( TK_BITAND==OP_BitAnd );
  63921. assert( TK_BITOR==OP_BitOr );
  63922. assert( TK_SLASH==OP_Divide );
  63923. assert( TK_LSHIFT==OP_ShiftLeft );
  63924. assert( TK_RSHIFT==OP_ShiftRight );
  63925. assert( TK_CONCAT==OP_Concat );
  63926. testcase( op==TK_AND );
  63927. testcase( op==TK_OR );
  63928. testcase( op==TK_PLUS );
  63929. testcase( op==TK_MINUS );
  63930. testcase( op==TK_REM );
  63931. testcase( op==TK_BITAND );
  63932. testcase( op==TK_BITOR );
  63933. testcase( op==TK_SLASH );
  63934. testcase( op==TK_LSHIFT );
  63935. testcase( op==TK_RSHIFT );
  63936. testcase( op==TK_CONCAT );
  63937. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63938. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  63939. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  63940. testcase( regFree1==0 );
  63941. testcase( regFree2==0 );
  63942. break;
  63943. }
  63944. case TK_UMINUS: {
  63945. Expr *pLeft = pExpr->pLeft;
  63946. assert( pLeft );
  63947. if( pLeft->op==TK_INTEGER ){
  63948. codeInteger(pParse, pLeft, 1, target);
  63949. #ifndef SQLITE_OMIT_FLOATING_POINT
  63950. }else if( pLeft->op==TK_FLOAT ){
  63951. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63952. codeReal(v, pLeft->u.zToken, 1, target);
  63953. #endif
  63954. }else{
  63955. regFree1 = r1 = sqlite3GetTempReg(pParse);
  63956. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  63957. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  63958. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  63959. testcase( regFree2==0 );
  63960. }
  63961. inReg = target;
  63962. break;
  63963. }
  63964. case TK_BITNOT:
  63965. case TK_NOT: {
  63966. assert( TK_BITNOT==OP_BitNot );
  63967. assert( TK_NOT==OP_Not );
  63968. testcase( op==TK_BITNOT );
  63969. testcase( op==TK_NOT );
  63970. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63971. testcase( regFree1==0 );
  63972. inReg = target;
  63973. sqlite3VdbeAddOp2(v, op, r1, inReg);
  63974. break;
  63975. }
  63976. case TK_ISNULL:
  63977. case TK_NOTNULL: {
  63978. int addr;
  63979. assert( TK_ISNULL==OP_IsNull );
  63980. assert( TK_NOTNULL==OP_NotNull );
  63981. testcase( op==TK_ISNULL );
  63982. testcase( op==TK_NOTNULL );
  63983. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  63984. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  63985. testcase( regFree1==0 );
  63986. addr = sqlite3VdbeAddOp1(v, op, r1);
  63987. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  63988. sqlite3VdbeJumpHere(v, addr);
  63989. break;
  63990. }
  63991. case TK_AGG_FUNCTION: {
  63992. AggInfo *pInfo = pExpr->pAggInfo;
  63993. if( pInfo==0 ){
  63994. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  63995. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  63996. }else{
  63997. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  63998. }
  63999. break;
  64000. }
  64001. case TK_CONST_FUNC:
  64002. case TK_FUNCTION: {
  64003. ExprList *pFarg; /* List of function arguments */
  64004. int nFarg; /* Number of function arguments */
  64005. FuncDef *pDef; /* The function definition object */
  64006. int nId; /* Length of the function name in bytes */
  64007. const char *zId; /* The function name */
  64008. int constMask = 0; /* Mask of function arguments that are constant */
  64009. int i; /* Loop counter */
  64010. u8 enc = ENC(db); /* The text encoding used by this database */
  64011. CollSeq *pColl = 0; /* A collating sequence */
  64012. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64013. testcase( op==TK_CONST_FUNC );
  64014. testcase( op==TK_FUNCTION );
  64015. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  64016. pFarg = 0;
  64017. }else{
  64018. pFarg = pExpr->x.pList;
  64019. }
  64020. nFarg = pFarg ? pFarg->nExpr : 0;
  64021. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  64022. zId = pExpr->u.zToken;
  64023. nId = sqlite3Strlen30(zId);
  64024. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  64025. if( pDef==0 ){
  64026. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  64027. break;
  64028. }
  64029. /* Attempt a direct implementation of the built-in COALESCE() and
  64030. ** IFNULL() functions. This avoids unnecessary evalation of
  64031. ** arguments past the first non-NULL argument.
  64032. */
  64033. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  64034. int endCoalesce = sqlite3VdbeMakeLabel(v);
  64035. assert( nFarg>=2 );
  64036. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  64037. for(i=1; i<nFarg; i++){
  64038. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  64039. sqlite3ExprCacheRemove(pParse, target, 1);
  64040. sqlite3ExprCachePush(pParse);
  64041. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  64042. sqlite3ExprCachePop(pParse, 1);
  64043. }
  64044. sqlite3VdbeResolveLabel(v, endCoalesce);
  64045. break;
  64046. }
  64047. /* The UNLIKELY() function is a no-op. The result is the value
  64048. ** of the first argument.
  64049. */
  64050. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  64051. assert( nFarg>=1 );
  64052. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  64053. break;
  64054. }
  64055. if( pFarg ){
  64056. r1 = sqlite3GetTempRange(pParse, nFarg);
  64057. /* For length() and typeof() functions with a column argument,
  64058. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  64059. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  64060. ** loading.
  64061. */
  64062. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  64063. u8 exprOp;
  64064. assert( nFarg==1 );
  64065. assert( pFarg->a[0].pExpr!=0 );
  64066. exprOp = pFarg->a[0].pExpr->op;
  64067. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  64068. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  64069. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  64070. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  64071. ==SQLITE_FUNC_LENGTH );
  64072. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  64073. }
  64074. }
  64075. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  64076. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  64077. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  64078. }else{
  64079. r1 = 0;
  64080. }
  64081. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64082. /* Possibly overload the function if the first argument is
  64083. ** a virtual table column.
  64084. **
  64085. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  64086. ** second argument, not the first, as the argument to test to
  64087. ** see if it is a column in a virtual table. This is done because
  64088. ** the left operand of infix functions (the operand we want to
  64089. ** control overloading) ends up as the second argument to the
  64090. ** function. The expression "A glob B" is equivalent to
  64091. ** "glob(B,A). We want to use the A in "A glob B" to test
  64092. ** for function overloading. But we use the B term in "glob(B,A)".
  64093. */
  64094. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  64095. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  64096. }else if( nFarg>0 ){
  64097. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  64098. }
  64099. #endif
  64100. for(i=0; i<nFarg; i++){
  64101. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  64102. constMask |= (1<<i);
  64103. }
  64104. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  64105. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  64106. }
  64107. }
  64108. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  64109. if( !pColl ) pColl = db->pDfltColl;
  64110. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  64111. }
  64112. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  64113. (char*)pDef, P4_FUNCDEF);
  64114. sqlite3VdbeChangeP5(v, (u8)nFarg);
  64115. if( nFarg ){
  64116. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  64117. }
  64118. break;
  64119. }
  64120. #ifndef SQLITE_OMIT_SUBQUERY
  64121. case TK_EXISTS:
  64122. case TK_SELECT: {
  64123. testcase( op==TK_EXISTS );
  64124. testcase( op==TK_SELECT );
  64125. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  64126. break;
  64127. }
  64128. case TK_IN: {
  64129. int destIfFalse = sqlite3VdbeMakeLabel(v);
  64130. int destIfNull = sqlite3VdbeMakeLabel(v);
  64131. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  64132. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  64133. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  64134. sqlite3VdbeResolveLabel(v, destIfFalse);
  64135. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  64136. sqlite3VdbeResolveLabel(v, destIfNull);
  64137. break;
  64138. }
  64139. #endif /* SQLITE_OMIT_SUBQUERY */
  64140. /*
  64141. ** x BETWEEN y AND z
  64142. **
  64143. ** This is equivalent to
  64144. **
  64145. ** x>=y AND x<=z
  64146. **
  64147. ** X is stored in pExpr->pLeft.
  64148. ** Y is stored in pExpr->pList->a[0].pExpr.
  64149. ** Z is stored in pExpr->pList->a[1].pExpr.
  64150. */
  64151. case TK_BETWEEN: {
  64152. Expr *pLeft = pExpr->pLeft;
  64153. struct ExprList_item *pLItem = pExpr->x.pList->a;
  64154. Expr *pRight = pLItem->pExpr;
  64155. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  64156. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  64157. testcase( regFree1==0 );
  64158. testcase( regFree2==0 );
  64159. r3 = sqlite3GetTempReg(pParse);
  64160. r4 = sqlite3GetTempReg(pParse);
  64161. codeCompare(pParse, pLeft, pRight, OP_Ge,
  64162. r1, r2, r3, SQLITE_STOREP2);
  64163. pLItem++;
  64164. pRight = pLItem->pExpr;
  64165. sqlite3ReleaseTempReg(pParse, regFree2);
  64166. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  64167. testcase( regFree2==0 );
  64168. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  64169. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  64170. sqlite3ReleaseTempReg(pParse, r3);
  64171. sqlite3ReleaseTempReg(pParse, r4);
  64172. break;
  64173. }
  64174. case TK_COLLATE:
  64175. case TK_UPLUS: {
  64176. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  64177. break;
  64178. }
  64179. case TK_TRIGGER: {
  64180. /* If the opcode is TK_TRIGGER, then the expression is a reference
  64181. ** to a column in the new.* or old.* pseudo-tables available to
  64182. ** trigger programs. In this case Expr.iTable is set to 1 for the
  64183. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  64184. ** is set to the column of the pseudo-table to read, or to -1 to
  64185. ** read the rowid field.
  64186. **
  64187. ** The expression is implemented using an OP_Param opcode. The p1
  64188. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  64189. ** to reference another column of the old.* pseudo-table, where
  64190. ** i is the index of the column. For a new.rowid reference, p1 is
  64191. ** set to (n+1), where n is the number of columns in each pseudo-table.
  64192. ** For a reference to any other column in the new.* pseudo-table, p1
  64193. ** is set to (n+2+i), where n and i are as defined previously. For
  64194. ** example, if the table on which triggers are being fired is
  64195. ** declared as:
  64196. **
  64197. ** CREATE TABLE t1(a, b);
  64198. **
  64199. ** Then p1 is interpreted as follows:
  64200. **
  64201. ** p1==0 -> old.rowid p1==3 -> new.rowid
  64202. ** p1==1 -> old.a p1==4 -> new.a
  64203. ** p1==2 -> old.b p1==5 -> new.b
  64204. */
  64205. Table *pTab = pExpr->pTab;
  64206. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  64207. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  64208. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  64209. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  64210. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  64211. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  64212. VdbeComment((v, "%s.%s -> $%d",
  64213. (pExpr->iTable ? "new" : "old"),
  64214. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  64215. target
  64216. ));
  64217. #ifndef SQLITE_OMIT_FLOATING_POINT
  64218. /* If the column has REAL affinity, it may currently be stored as an
  64219. ** integer. Use OP_RealAffinity to make sure it is really real. */
  64220. if( pExpr->iColumn>=0
  64221. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  64222. ){
  64223. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  64224. }
  64225. #endif
  64226. break;
  64227. }
  64228. /*
  64229. ** Form A:
  64230. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  64231. **
  64232. ** Form B:
  64233. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  64234. **
  64235. ** Form A is can be transformed into the equivalent form B as follows:
  64236. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  64237. ** WHEN x=eN THEN rN ELSE y END
  64238. **
  64239. ** X (if it exists) is in pExpr->pLeft.
  64240. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  64241. ** odd. The Y is also optional. If the number of elements in x.pList
  64242. ** is even, then Y is omitted and the "otherwise" result is NULL.
  64243. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  64244. **
  64245. ** The result of the expression is the Ri for the first matching Ei,
  64246. ** or if there is no matching Ei, the ELSE term Y, or if there is
  64247. ** no ELSE term, NULL.
  64248. */
  64249. default: assert( op==TK_CASE ); {
  64250. int endLabel; /* GOTO label for end of CASE stmt */
  64251. int nextCase; /* GOTO label for next WHEN clause */
  64252. int nExpr; /* 2x number of WHEN terms */
  64253. int i; /* Loop counter */
  64254. ExprList *pEList; /* List of WHEN terms */
  64255. struct ExprList_item *aListelem; /* Array of WHEN terms */
  64256. Expr opCompare; /* The X==Ei expression */
  64257. Expr cacheX; /* Cached expression X */
  64258. Expr *pX; /* The X expression */
  64259. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  64260. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  64261. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  64262. assert(pExpr->x.pList->nExpr > 0);
  64263. pEList = pExpr->x.pList;
  64264. aListelem = pEList->a;
  64265. nExpr = pEList->nExpr;
  64266. endLabel = sqlite3VdbeMakeLabel(v);
  64267. if( (pX = pExpr->pLeft)!=0 ){
  64268. cacheX = *pX;
  64269. testcase( pX->op==TK_COLUMN );
  64270. testcase( pX->op==TK_REGISTER );
  64271. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  64272. testcase( regFree1==0 );
  64273. opCompare.op = TK_EQ;
  64274. opCompare.pLeft = &cacheX;
  64275. pTest = &opCompare;
  64276. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  64277. ** The value in regFree1 might get SCopy-ed into the file result.
  64278. ** So make sure that the regFree1 register is not reused for other
  64279. ** purposes and possibly overwritten. */
  64280. regFree1 = 0;
  64281. }
  64282. for(i=0; i<nExpr-1; i=i+2){
  64283. sqlite3ExprCachePush(pParse);
  64284. if( pX ){
  64285. assert( pTest!=0 );
  64286. opCompare.pRight = aListelem[i].pExpr;
  64287. }else{
  64288. pTest = aListelem[i].pExpr;
  64289. }
  64290. nextCase = sqlite3VdbeMakeLabel(v);
  64291. testcase( pTest->op==TK_COLUMN );
  64292. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  64293. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  64294. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  64295. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  64296. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  64297. sqlite3ExprCachePop(pParse, 1);
  64298. sqlite3VdbeResolveLabel(v, nextCase);
  64299. }
  64300. if( (nExpr&1)!=0 ){
  64301. sqlite3ExprCachePush(pParse);
  64302. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  64303. sqlite3ExprCachePop(pParse, 1);
  64304. }else{
  64305. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  64306. }
  64307. assert( db->mallocFailed || pParse->nErr>0
  64308. || pParse->iCacheLevel==iCacheLevel );
  64309. sqlite3VdbeResolveLabel(v, endLabel);
  64310. break;
  64311. }
  64312. #ifndef SQLITE_OMIT_TRIGGER
  64313. case TK_RAISE: {
  64314. assert( pExpr->affinity==OE_Rollback
  64315. || pExpr->affinity==OE_Abort
  64316. || pExpr->affinity==OE_Fail
  64317. || pExpr->affinity==OE_Ignore
  64318. );
  64319. if( !pParse->pTriggerTab ){
  64320. sqlite3ErrorMsg(pParse,
  64321. "RAISE() may only be used within a trigger-program");
  64322. return 0;
  64323. }
  64324. if( pExpr->affinity==OE_Abort ){
  64325. sqlite3MayAbort(pParse);
  64326. }
  64327. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  64328. if( pExpr->affinity==OE_Ignore ){
  64329. sqlite3VdbeAddOp4(
  64330. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  64331. }else{
  64332. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  64333. pExpr->affinity, pExpr->u.zToken, 0);
  64334. }
  64335. break;
  64336. }
  64337. #endif
  64338. }
  64339. sqlite3ReleaseTempReg(pParse, regFree1);
  64340. sqlite3ReleaseTempReg(pParse, regFree2);
  64341. return inReg;
  64342. }
  64343. /*
  64344. ** Generate code to evaluate an expression and store the results
  64345. ** into a register. Return the register number where the results
  64346. ** are stored.
  64347. **
  64348. ** If the register is a temporary register that can be deallocated,
  64349. ** then write its number into *pReg. If the result register is not
  64350. ** a temporary, then set *pReg to zero.
  64351. */
  64352. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  64353. int r1 = sqlite3GetTempReg(pParse);
  64354. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  64355. if( r2==r1 ){
  64356. *pReg = r1;
  64357. }else{
  64358. sqlite3ReleaseTempReg(pParse, r1);
  64359. *pReg = 0;
  64360. }
  64361. return r2;
  64362. }
  64363. /*
  64364. ** Generate code that will evaluate expression pExpr and store the
  64365. ** results in register target. The results are guaranteed to appear
  64366. ** in register target.
  64367. */
  64368. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  64369. int inReg;
  64370. assert( target>0 && target<=pParse->nMem );
  64371. if( pExpr && pExpr->op==TK_REGISTER ){
  64372. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  64373. }else{
  64374. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  64375. assert( pParse->pVdbe || pParse->db->mallocFailed );
  64376. if( inReg!=target && pParse->pVdbe ){
  64377. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  64378. }
  64379. }
  64380. return target;
  64381. }
  64382. /*
  64383. ** Generate code that evalutes the given expression and puts the result
  64384. ** in register target.
  64385. **
  64386. ** Also make a copy of the expression results into another "cache" register
  64387. ** and modify the expression so that the next time it is evaluated,
  64388. ** the result is a copy of the cache register.
  64389. **
  64390. ** This routine is used for expressions that are used multiple
  64391. ** times. They are evaluated once and the results of the expression
  64392. ** are reused.
  64393. */
  64394. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  64395. Vdbe *v = pParse->pVdbe;
  64396. int inReg;
  64397. inReg = sqlite3ExprCode(pParse, pExpr, target);
  64398. assert( target>0 );
  64399. /* This routine is called for terms to INSERT or UPDATE. And the only
  64400. ** other place where expressions can be converted into TK_REGISTER is
  64401. ** in WHERE clause processing. So as currently implemented, there is
  64402. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  64403. ** keep the ALWAYS() in case the conditions above change with future
  64404. ** modifications or enhancements. */
  64405. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  64406. int iMem;
  64407. iMem = ++pParse->nMem;
  64408. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  64409. exprToRegister(pExpr, iMem);
  64410. }
  64411. return inReg;
  64412. }
  64413. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64414. /*
  64415. ** Generate a human-readable explanation of an expression tree.
  64416. */
  64417. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  64418. int op; /* The opcode being coded */
  64419. const char *zBinOp = 0; /* Binary operator */
  64420. const char *zUniOp = 0; /* Unary operator */
  64421. if( pExpr==0 ){
  64422. op = TK_NULL;
  64423. }else{
  64424. op = pExpr->op;
  64425. }
  64426. switch( op ){
  64427. case TK_AGG_COLUMN: {
  64428. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  64429. pExpr->iTable, pExpr->iColumn);
  64430. break;
  64431. }
  64432. case TK_COLUMN: {
  64433. if( pExpr->iTable<0 ){
  64434. /* This only happens when coding check constraints */
  64435. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  64436. }else{
  64437. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  64438. pExpr->iTable, pExpr->iColumn);
  64439. }
  64440. break;
  64441. }
  64442. case TK_INTEGER: {
  64443. if( pExpr->flags & EP_IntValue ){
  64444. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  64445. }else{
  64446. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  64447. }
  64448. break;
  64449. }
  64450. #ifndef SQLITE_OMIT_FLOATING_POINT
  64451. case TK_FLOAT: {
  64452. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  64453. break;
  64454. }
  64455. #endif
  64456. case TK_STRING: {
  64457. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  64458. break;
  64459. }
  64460. case TK_NULL: {
  64461. sqlite3ExplainPrintf(pOut,"NULL");
  64462. break;
  64463. }
  64464. #ifndef SQLITE_OMIT_BLOB_LITERAL
  64465. case TK_BLOB: {
  64466. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  64467. break;
  64468. }
  64469. #endif
  64470. case TK_VARIABLE: {
  64471. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  64472. pExpr->u.zToken, pExpr->iColumn);
  64473. break;
  64474. }
  64475. case TK_REGISTER: {
  64476. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  64477. break;
  64478. }
  64479. case TK_AS: {
  64480. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64481. break;
  64482. }
  64483. #ifndef SQLITE_OMIT_CAST
  64484. case TK_CAST: {
  64485. /* Expressions of the form: CAST(pLeft AS token) */
  64486. const char *zAff = "unk";
  64487. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  64488. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  64489. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  64490. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  64491. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  64492. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  64493. }
  64494. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  64495. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64496. sqlite3ExplainPrintf(pOut, ")");
  64497. break;
  64498. }
  64499. #endif /* SQLITE_OMIT_CAST */
  64500. case TK_LT: zBinOp = "LT"; break;
  64501. case TK_LE: zBinOp = "LE"; break;
  64502. case TK_GT: zBinOp = "GT"; break;
  64503. case TK_GE: zBinOp = "GE"; break;
  64504. case TK_NE: zBinOp = "NE"; break;
  64505. case TK_EQ: zBinOp = "EQ"; break;
  64506. case TK_IS: zBinOp = "IS"; break;
  64507. case TK_ISNOT: zBinOp = "ISNOT"; break;
  64508. case TK_AND: zBinOp = "AND"; break;
  64509. case TK_OR: zBinOp = "OR"; break;
  64510. case TK_PLUS: zBinOp = "ADD"; break;
  64511. case TK_STAR: zBinOp = "MUL"; break;
  64512. case TK_MINUS: zBinOp = "SUB"; break;
  64513. case TK_REM: zBinOp = "REM"; break;
  64514. case TK_BITAND: zBinOp = "BITAND"; break;
  64515. case TK_BITOR: zBinOp = "BITOR"; break;
  64516. case TK_SLASH: zBinOp = "DIV"; break;
  64517. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  64518. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  64519. case TK_CONCAT: zBinOp = "CONCAT"; break;
  64520. case TK_UMINUS: zUniOp = "UMINUS"; break;
  64521. case TK_UPLUS: zUniOp = "UPLUS"; break;
  64522. case TK_BITNOT: zUniOp = "BITNOT"; break;
  64523. case TK_NOT: zUniOp = "NOT"; break;
  64524. case TK_ISNULL: zUniOp = "ISNULL"; break;
  64525. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  64526. case TK_COLLATE: {
  64527. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64528. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  64529. break;
  64530. }
  64531. case TK_AGG_FUNCTION:
  64532. case TK_CONST_FUNC:
  64533. case TK_FUNCTION: {
  64534. ExprList *pFarg; /* List of function arguments */
  64535. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  64536. pFarg = 0;
  64537. }else{
  64538. pFarg = pExpr->x.pList;
  64539. }
  64540. if( op==TK_AGG_FUNCTION ){
  64541. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  64542. pExpr->op2, pExpr->u.zToken);
  64543. }else{
  64544. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  64545. }
  64546. if( pFarg ){
  64547. sqlite3ExplainExprList(pOut, pFarg);
  64548. }
  64549. sqlite3ExplainPrintf(pOut, ")");
  64550. break;
  64551. }
  64552. #ifndef SQLITE_OMIT_SUBQUERY
  64553. case TK_EXISTS: {
  64554. sqlite3ExplainPrintf(pOut, "EXISTS(");
  64555. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64556. sqlite3ExplainPrintf(pOut,")");
  64557. break;
  64558. }
  64559. case TK_SELECT: {
  64560. sqlite3ExplainPrintf(pOut, "(");
  64561. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64562. sqlite3ExplainPrintf(pOut, ")");
  64563. break;
  64564. }
  64565. case TK_IN: {
  64566. sqlite3ExplainPrintf(pOut, "IN(");
  64567. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64568. sqlite3ExplainPrintf(pOut, ",");
  64569. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  64570. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  64571. }else{
  64572. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  64573. }
  64574. sqlite3ExplainPrintf(pOut, ")");
  64575. break;
  64576. }
  64577. #endif /* SQLITE_OMIT_SUBQUERY */
  64578. /*
  64579. ** x BETWEEN y AND z
  64580. **
  64581. ** This is equivalent to
  64582. **
  64583. ** x>=y AND x<=z
  64584. **
  64585. ** X is stored in pExpr->pLeft.
  64586. ** Y is stored in pExpr->pList->a[0].pExpr.
  64587. ** Z is stored in pExpr->pList->a[1].pExpr.
  64588. */
  64589. case TK_BETWEEN: {
  64590. Expr *pX = pExpr->pLeft;
  64591. Expr *pY = pExpr->x.pList->a[0].pExpr;
  64592. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  64593. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  64594. sqlite3ExplainExpr(pOut, pX);
  64595. sqlite3ExplainPrintf(pOut, ",");
  64596. sqlite3ExplainExpr(pOut, pY);
  64597. sqlite3ExplainPrintf(pOut, ",");
  64598. sqlite3ExplainExpr(pOut, pZ);
  64599. sqlite3ExplainPrintf(pOut, ")");
  64600. break;
  64601. }
  64602. case TK_TRIGGER: {
  64603. /* If the opcode is TK_TRIGGER, then the expression is a reference
  64604. ** to a column in the new.* or old.* pseudo-tables available to
  64605. ** trigger programs. In this case Expr.iTable is set to 1 for the
  64606. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  64607. ** is set to the column of the pseudo-table to read, or to -1 to
  64608. ** read the rowid field.
  64609. */
  64610. sqlite3ExplainPrintf(pOut, "%s(%d)",
  64611. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  64612. break;
  64613. }
  64614. case TK_CASE: {
  64615. sqlite3ExplainPrintf(pOut, "CASE(");
  64616. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64617. sqlite3ExplainPrintf(pOut, ",");
  64618. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  64619. break;
  64620. }
  64621. #ifndef SQLITE_OMIT_TRIGGER
  64622. case TK_RAISE: {
  64623. const char *zType = "unk";
  64624. switch( pExpr->affinity ){
  64625. case OE_Rollback: zType = "rollback"; break;
  64626. case OE_Abort: zType = "abort"; break;
  64627. case OE_Fail: zType = "fail"; break;
  64628. case OE_Ignore: zType = "ignore"; break;
  64629. }
  64630. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  64631. break;
  64632. }
  64633. #endif
  64634. }
  64635. if( zBinOp ){
  64636. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  64637. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64638. sqlite3ExplainPrintf(pOut,",");
  64639. sqlite3ExplainExpr(pOut, pExpr->pRight);
  64640. sqlite3ExplainPrintf(pOut,")");
  64641. }else if( zUniOp ){
  64642. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  64643. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  64644. sqlite3ExplainPrintf(pOut,")");
  64645. }
  64646. }
  64647. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  64648. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64649. /*
  64650. ** Generate a human-readable explanation of an expression list.
  64651. */
  64652. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  64653. int i;
  64654. if( pList==0 || pList->nExpr==0 ){
  64655. sqlite3ExplainPrintf(pOut, "(empty-list)");
  64656. return;
  64657. }else if( pList->nExpr==1 ){
  64658. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  64659. }else{
  64660. sqlite3ExplainPush(pOut);
  64661. for(i=0; i<pList->nExpr; i++){
  64662. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  64663. sqlite3ExplainPush(pOut);
  64664. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  64665. sqlite3ExplainPop(pOut);
  64666. if( pList->a[i].zName ){
  64667. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  64668. }
  64669. if( pList->a[i].bSpanIsTab ){
  64670. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  64671. }
  64672. if( i<pList->nExpr-1 ){
  64673. sqlite3ExplainNL(pOut);
  64674. }
  64675. }
  64676. sqlite3ExplainPop(pOut);
  64677. }
  64678. }
  64679. #endif /* SQLITE_DEBUG */
  64680. /*
  64681. ** Return TRUE if pExpr is an constant expression that is appropriate
  64682. ** for factoring out of a loop. Appropriate expressions are:
  64683. **
  64684. ** * Any expression that evaluates to two or more opcodes.
  64685. **
  64686. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  64687. ** or OP_Variable that does not need to be placed in a
  64688. ** specific register.
  64689. **
  64690. ** There is no point in factoring out single-instruction constant
  64691. ** expressions that need to be placed in a particular register.
  64692. ** We could factor them out, but then we would end up adding an
  64693. ** OP_SCopy instruction to move the value into the correct register
  64694. ** later. We might as well just use the original instruction and
  64695. ** avoid the OP_SCopy.
  64696. */
  64697. static int isAppropriateForFactoring(Expr *p){
  64698. if( !sqlite3ExprIsConstantNotJoin(p) ){
  64699. return 0; /* Only constant expressions are appropriate for factoring */
  64700. }
  64701. if( (p->flags & EP_FixedDest)==0 ){
  64702. return 1; /* Any constant without a fixed destination is appropriate */
  64703. }
  64704. while( p->op==TK_UPLUS ) p = p->pLeft;
  64705. switch( p->op ){
  64706. #ifndef SQLITE_OMIT_BLOB_LITERAL
  64707. case TK_BLOB:
  64708. #endif
  64709. case TK_VARIABLE:
  64710. case TK_INTEGER:
  64711. case TK_FLOAT:
  64712. case TK_NULL:
  64713. case TK_STRING: {
  64714. testcase( p->op==TK_BLOB );
  64715. testcase( p->op==TK_VARIABLE );
  64716. testcase( p->op==TK_INTEGER );
  64717. testcase( p->op==TK_FLOAT );
  64718. testcase( p->op==TK_NULL );
  64719. testcase( p->op==TK_STRING );
  64720. /* Single-instruction constants with a fixed destination are
  64721. ** better done in-line. If we factor them, they will just end
  64722. ** up generating an OP_SCopy to move the value to the destination
  64723. ** register. */
  64724. return 0;
  64725. }
  64726. case TK_UMINUS: {
  64727. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  64728. return 0;
  64729. }
  64730. break;
  64731. }
  64732. default: {
  64733. break;
  64734. }
  64735. }
  64736. return 1;
  64737. }
  64738. /*
  64739. ** If pExpr is a constant expression that is appropriate for
  64740. ** factoring out of a loop, then evaluate the expression
  64741. ** into a register and convert the expression into a TK_REGISTER
  64742. ** expression.
  64743. */
  64744. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  64745. Parse *pParse = pWalker->pParse;
  64746. switch( pExpr->op ){
  64747. case TK_IN:
  64748. case TK_REGISTER: {
  64749. return WRC_Prune;
  64750. }
  64751. case TK_COLLATE: {
  64752. return WRC_Continue;
  64753. }
  64754. case TK_FUNCTION:
  64755. case TK_AGG_FUNCTION:
  64756. case TK_CONST_FUNC: {
  64757. /* The arguments to a function have a fixed destination.
  64758. ** Mark them this way to avoid generated unneeded OP_SCopy
  64759. ** instructions.
  64760. */
  64761. ExprList *pList = pExpr->x.pList;
  64762. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64763. if( pList ){
  64764. int i = pList->nExpr;
  64765. struct ExprList_item *pItem = pList->a;
  64766. for(; i>0; i--, pItem++){
  64767. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  64768. }
  64769. }
  64770. break;
  64771. }
  64772. }
  64773. if( isAppropriateForFactoring(pExpr) ){
  64774. int r1 = ++pParse->nMem;
  64775. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  64776. /* If r2!=r1, it means that register r1 is never used. That is harmless
  64777. ** but suboptimal, so we want to know about the situation to fix it.
  64778. ** Hence the following assert: */
  64779. assert( r2==r1 );
  64780. exprToRegister(pExpr, r2);
  64781. return WRC_Prune;
  64782. }
  64783. return WRC_Continue;
  64784. }
  64785. /*
  64786. ** Preevaluate constant subexpressions within pExpr and store the
  64787. ** results in registers. Modify pExpr so that the constant subexpresions
  64788. ** are TK_REGISTER opcodes that refer to the precomputed values.
  64789. **
  64790. ** This routine is a no-op if the jump to the cookie-check code has
  64791. ** already occur. Since the cookie-check jump is generated prior to
  64792. ** any other serious processing, this check ensures that there is no
  64793. ** way to accidently bypass the constant initializations.
  64794. **
  64795. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  64796. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  64797. ** interface. This allows test logic to verify that the same answer is
  64798. ** obtained for queries regardless of whether or not constants are
  64799. ** precomputed into registers or if they are inserted in-line.
  64800. */
  64801. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  64802. Walker w;
  64803. if( pParse->cookieGoto ) return;
  64804. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  64805. memset(&w, 0, sizeof(w));
  64806. w.xExprCallback = evalConstExpr;
  64807. w.pParse = pParse;
  64808. sqlite3WalkExpr(&w, pExpr);
  64809. }
  64810. /*
  64811. ** Generate code that pushes the value of every element of the given
  64812. ** expression list into a sequence of registers beginning at target.
  64813. **
  64814. ** Return the number of elements evaluated.
  64815. */
  64816. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  64817. Parse *pParse, /* Parsing context */
  64818. ExprList *pList, /* The expression list to be coded */
  64819. int target, /* Where to write results */
  64820. int doHardCopy /* Make a hard copy of every element */
  64821. ){
  64822. struct ExprList_item *pItem;
  64823. int i, n;
  64824. assert( pList!=0 );
  64825. assert( target>0 );
  64826. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  64827. n = pList->nExpr;
  64828. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  64829. Expr *pExpr = pItem->pExpr;
  64830. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  64831. if( inReg!=target+i ){
  64832. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  64833. inReg, target+i);
  64834. }
  64835. }
  64836. return n;
  64837. }
  64838. /*
  64839. ** Generate code for a BETWEEN operator.
  64840. **
  64841. ** x BETWEEN y AND z
  64842. **
  64843. ** The above is equivalent to
  64844. **
  64845. ** x>=y AND x<=z
  64846. **
  64847. ** Code it as such, taking care to do the common subexpression
  64848. ** elementation of x.
  64849. */
  64850. static void exprCodeBetween(
  64851. Parse *pParse, /* Parsing and code generating context */
  64852. Expr *pExpr, /* The BETWEEN expression */
  64853. int dest, /* Jump here if the jump is taken */
  64854. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  64855. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  64856. ){
  64857. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  64858. Expr compLeft; /* The x>=y term */
  64859. Expr compRight; /* The x<=z term */
  64860. Expr exprX; /* The x subexpression */
  64861. int regFree1 = 0; /* Temporary use register */
  64862. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  64863. exprX = *pExpr->pLeft;
  64864. exprAnd.op = TK_AND;
  64865. exprAnd.pLeft = &compLeft;
  64866. exprAnd.pRight = &compRight;
  64867. compLeft.op = TK_GE;
  64868. compLeft.pLeft = &exprX;
  64869. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  64870. compRight.op = TK_LE;
  64871. compRight.pLeft = &exprX;
  64872. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  64873. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  64874. if( jumpIfTrue ){
  64875. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  64876. }else{
  64877. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  64878. }
  64879. sqlite3ReleaseTempReg(pParse, regFree1);
  64880. /* Ensure adequate test coverage */
  64881. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  64882. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  64883. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  64884. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  64885. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  64886. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  64887. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  64888. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  64889. }
  64890. /*
  64891. ** Generate code for a boolean expression such that a jump is made
  64892. ** to the label "dest" if the expression is true but execution
  64893. ** continues straight thru if the expression is false.
  64894. **
  64895. ** If the expression evaluates to NULL (neither true nor false), then
  64896. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  64897. **
  64898. ** This code depends on the fact that certain token values (ex: TK_EQ)
  64899. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  64900. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  64901. ** the make process cause these values to align. Assert()s in the code
  64902. ** below verify that the numbers are aligned correctly.
  64903. */
  64904. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  64905. Vdbe *v = pParse->pVdbe;
  64906. int op = 0;
  64907. int regFree1 = 0;
  64908. int regFree2 = 0;
  64909. int r1, r2;
  64910. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  64911. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  64912. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  64913. op = pExpr->op;
  64914. switch( op ){
  64915. case TK_AND: {
  64916. int d2 = sqlite3VdbeMakeLabel(v);
  64917. testcase( jumpIfNull==0 );
  64918. sqlite3ExprCachePush(pParse);
  64919. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  64920. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  64921. sqlite3VdbeResolveLabel(v, d2);
  64922. sqlite3ExprCachePop(pParse, 1);
  64923. break;
  64924. }
  64925. case TK_OR: {
  64926. testcase( jumpIfNull==0 );
  64927. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  64928. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  64929. break;
  64930. }
  64931. case TK_NOT: {
  64932. testcase( jumpIfNull==0 );
  64933. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  64934. break;
  64935. }
  64936. case TK_LT:
  64937. case TK_LE:
  64938. case TK_GT:
  64939. case TK_GE:
  64940. case TK_NE:
  64941. case TK_EQ: {
  64942. assert( TK_LT==OP_Lt );
  64943. assert( TK_LE==OP_Le );
  64944. assert( TK_GT==OP_Gt );
  64945. assert( TK_GE==OP_Ge );
  64946. assert( TK_EQ==OP_Eq );
  64947. assert( TK_NE==OP_Ne );
  64948. testcase( op==TK_LT );
  64949. testcase( op==TK_LE );
  64950. testcase( op==TK_GT );
  64951. testcase( op==TK_GE );
  64952. testcase( op==TK_EQ );
  64953. testcase( op==TK_NE );
  64954. testcase( jumpIfNull==0 );
  64955. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64956. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  64957. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  64958. r1, r2, dest, jumpIfNull);
  64959. testcase( regFree1==0 );
  64960. testcase( regFree2==0 );
  64961. break;
  64962. }
  64963. case TK_IS:
  64964. case TK_ISNOT: {
  64965. testcase( op==TK_IS );
  64966. testcase( op==TK_ISNOT );
  64967. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64968. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  64969. op = (op==TK_IS) ? TK_EQ : TK_NE;
  64970. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  64971. r1, r2, dest, SQLITE_NULLEQ);
  64972. testcase( regFree1==0 );
  64973. testcase( regFree2==0 );
  64974. break;
  64975. }
  64976. case TK_ISNULL:
  64977. case TK_NOTNULL: {
  64978. assert( TK_ISNULL==OP_IsNull );
  64979. assert( TK_NOTNULL==OP_NotNull );
  64980. testcase( op==TK_ISNULL );
  64981. testcase( op==TK_NOTNULL );
  64982. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  64983. sqlite3VdbeAddOp2(v, op, r1, dest);
  64984. testcase( regFree1==0 );
  64985. break;
  64986. }
  64987. case TK_BETWEEN: {
  64988. testcase( jumpIfNull==0 );
  64989. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  64990. break;
  64991. }
  64992. #ifndef SQLITE_OMIT_SUBQUERY
  64993. case TK_IN: {
  64994. int destIfFalse = sqlite3VdbeMakeLabel(v);
  64995. int destIfNull = jumpIfNull ? dest : destIfFalse;
  64996. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  64997. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  64998. sqlite3VdbeResolveLabel(v, destIfFalse);
  64999. break;
  65000. }
  65001. #endif
  65002. default: {
  65003. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  65004. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  65005. testcase( regFree1==0 );
  65006. testcase( jumpIfNull==0 );
  65007. break;
  65008. }
  65009. }
  65010. sqlite3ReleaseTempReg(pParse, regFree1);
  65011. sqlite3ReleaseTempReg(pParse, regFree2);
  65012. }
  65013. /*
  65014. ** Generate code for a boolean expression such that a jump is made
  65015. ** to the label "dest" if the expression is false but execution
  65016. ** continues straight thru if the expression is true.
  65017. **
  65018. ** If the expression evaluates to NULL (neither true nor false) then
  65019. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  65020. ** is 0.
  65021. */
  65022. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  65023. Vdbe *v = pParse->pVdbe;
  65024. int op = 0;
  65025. int regFree1 = 0;
  65026. int regFree2 = 0;
  65027. int r1, r2;
  65028. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  65029. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  65030. if( pExpr==0 ) return;
  65031. /* The value of pExpr->op and op are related as follows:
  65032. **
  65033. ** pExpr->op op
  65034. ** --------- ----------
  65035. ** TK_ISNULL OP_NotNull
  65036. ** TK_NOTNULL OP_IsNull
  65037. ** TK_NE OP_Eq
  65038. ** TK_EQ OP_Ne
  65039. ** TK_GT OP_Le
  65040. ** TK_LE OP_Gt
  65041. ** TK_GE OP_Lt
  65042. ** TK_LT OP_Ge
  65043. **
  65044. ** For other values of pExpr->op, op is undefined and unused.
  65045. ** The value of TK_ and OP_ constants are arranged such that we
  65046. ** can compute the mapping above using the following expression.
  65047. ** Assert()s verify that the computation is correct.
  65048. */
  65049. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  65050. /* Verify correct alignment of TK_ and OP_ constants
  65051. */
  65052. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  65053. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  65054. assert( pExpr->op!=TK_NE || op==OP_Eq );
  65055. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  65056. assert( pExpr->op!=TK_LT || op==OP_Ge );
  65057. assert( pExpr->op!=TK_LE || op==OP_Gt );
  65058. assert( pExpr->op!=TK_GT || op==OP_Le );
  65059. assert( pExpr->op!=TK_GE || op==OP_Lt );
  65060. switch( pExpr->op ){
  65061. case TK_AND: {
  65062. testcase( jumpIfNull==0 );
  65063. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  65064. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  65065. break;
  65066. }
  65067. case TK_OR: {
  65068. int d2 = sqlite3VdbeMakeLabel(v);
  65069. testcase( jumpIfNull==0 );
  65070. sqlite3ExprCachePush(pParse);
  65071. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  65072. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  65073. sqlite3VdbeResolveLabel(v, d2);
  65074. sqlite3ExprCachePop(pParse, 1);
  65075. break;
  65076. }
  65077. case TK_NOT: {
  65078. testcase( jumpIfNull==0 );
  65079. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  65080. break;
  65081. }
  65082. case TK_LT:
  65083. case TK_LE:
  65084. case TK_GT:
  65085. case TK_GE:
  65086. case TK_NE:
  65087. case TK_EQ: {
  65088. testcase( op==TK_LT );
  65089. testcase( op==TK_LE );
  65090. testcase( op==TK_GT );
  65091. testcase( op==TK_GE );
  65092. testcase( op==TK_EQ );
  65093. testcase( op==TK_NE );
  65094. testcase( jumpIfNull==0 );
  65095. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65096. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  65097. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  65098. r1, r2, dest, jumpIfNull);
  65099. testcase( regFree1==0 );
  65100. testcase( regFree2==0 );
  65101. break;
  65102. }
  65103. case TK_IS:
  65104. case TK_ISNOT: {
  65105. testcase( pExpr->op==TK_IS );
  65106. testcase( pExpr->op==TK_ISNOT );
  65107. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65108. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  65109. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  65110. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  65111. r1, r2, dest, SQLITE_NULLEQ);
  65112. testcase( regFree1==0 );
  65113. testcase( regFree2==0 );
  65114. break;
  65115. }
  65116. case TK_ISNULL:
  65117. case TK_NOTNULL: {
  65118. testcase( op==TK_ISNULL );
  65119. testcase( op==TK_NOTNULL );
  65120. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  65121. sqlite3VdbeAddOp2(v, op, r1, dest);
  65122. testcase( regFree1==0 );
  65123. break;
  65124. }
  65125. case TK_BETWEEN: {
  65126. testcase( jumpIfNull==0 );
  65127. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  65128. break;
  65129. }
  65130. #ifndef SQLITE_OMIT_SUBQUERY
  65131. case TK_IN: {
  65132. if( jumpIfNull ){
  65133. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  65134. }else{
  65135. int destIfNull = sqlite3VdbeMakeLabel(v);
  65136. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  65137. sqlite3VdbeResolveLabel(v, destIfNull);
  65138. }
  65139. break;
  65140. }
  65141. #endif
  65142. default: {
  65143. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  65144. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  65145. testcase( regFree1==0 );
  65146. testcase( jumpIfNull==0 );
  65147. break;
  65148. }
  65149. }
  65150. sqlite3ReleaseTempReg(pParse, regFree1);
  65151. sqlite3ReleaseTempReg(pParse, regFree2);
  65152. }
  65153. /*
  65154. ** Do a deep comparison of two expression trees. Return 0 if the two
  65155. ** expressions are completely identical. Return 1 if they differ only
  65156. ** by a COLLATE operator at the top level. Return 2 if there are differences
  65157. ** other than the top-level COLLATE operator.
  65158. **
  65159. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  65160. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  65161. **
  65162. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  65163. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  65164. **
  65165. ** Sometimes this routine will return 2 even if the two expressions
  65166. ** really are equivalent. If we cannot prove that the expressions are
  65167. ** identical, we return 2 just to be safe. So if this routine
  65168. ** returns 2, then you do not really know for certain if the two
  65169. ** expressions are the same. But if you get a 0 or 1 return, then you
  65170. ** can be sure the expressions are the same. In the places where
  65171. ** this routine is used, it does not hurt to get an extra 2 - that
  65172. ** just might result in some slightly slower code. But returning
  65173. ** an incorrect 0 or 1 could lead to a malfunction.
  65174. */
  65175. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  65176. if( pA==0||pB==0 ){
  65177. return pB==pA ? 0 : 2;
  65178. }
  65179. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  65180. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  65181. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  65182. return 2;
  65183. }
  65184. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  65185. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  65186. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  65187. return 1;
  65188. }
  65189. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  65190. return 1;
  65191. }
  65192. return 2;
  65193. }
  65194. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  65195. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  65196. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  65197. if( pA->iColumn!=pB->iColumn ) return 2;
  65198. if( pA->iTable!=pB->iTable
  65199. && pA->op!=TK_REGISTER
  65200. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  65201. if( ExprHasProperty(pA, EP_IntValue) ){
  65202. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  65203. return 2;
  65204. }
  65205. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  65206. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  65207. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  65208. return pA->op==TK_COLLATE ? 1 : 2;
  65209. }
  65210. }
  65211. return 0;
  65212. }
  65213. /*
  65214. ** Compare two ExprList objects. Return 0 if they are identical and
  65215. ** non-zero if they differ in any way.
  65216. **
  65217. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  65218. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  65219. **
  65220. ** This routine might return non-zero for equivalent ExprLists. The
  65221. ** only consequence will be disabled optimizations. But this routine
  65222. ** must never return 0 if the two ExprList objects are different, or
  65223. ** a malfunction will result.
  65224. **
  65225. ** Two NULL pointers are considered to be the same. But a NULL pointer
  65226. ** always differs from a non-NULL pointer.
  65227. */
  65228. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  65229. int i;
  65230. if( pA==0 && pB==0 ) return 0;
  65231. if( pA==0 || pB==0 ) return 1;
  65232. if( pA->nExpr!=pB->nExpr ) return 1;
  65233. for(i=0; i<pA->nExpr; i++){
  65234. Expr *pExprA = pA->a[i].pExpr;
  65235. Expr *pExprB = pB->a[i].pExpr;
  65236. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  65237. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  65238. }
  65239. return 0;
  65240. }
  65241. /*
  65242. ** Return true if we can prove the pE2 will always be true if pE1 is
  65243. ** true. Return false if we cannot complete the proof or if pE2 might
  65244. ** be false. Examples:
  65245. **
  65246. ** pE1: x==5 pE2: x==5 Result: true
  65247. ** pE1: x>0 pE2: x==5 Result: false
  65248. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  65249. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  65250. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  65251. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  65252. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  65253. **
  65254. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  65255. ** Expr.iTable<0 then assume a table number given by iTab.
  65256. **
  65257. ** When in doubt, return false. Returning true might give a performance
  65258. ** improvement. Returning false might cause a performance reduction, but
  65259. ** it will always give the correct answer and is hence always safe.
  65260. */
  65261. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  65262. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  65263. return 1;
  65264. }
  65265. if( pE2->op==TK_OR
  65266. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  65267. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  65268. ){
  65269. return 1;
  65270. }
  65271. if( pE2->op==TK_NOTNULL
  65272. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  65273. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  65274. ){
  65275. return 1;
  65276. }
  65277. return 0;
  65278. }
  65279. /*
  65280. ** An instance of the following structure is used by the tree walker
  65281. ** to count references to table columns in the arguments of an
  65282. ** aggregate function, in order to implement the
  65283. ** sqlite3FunctionThisSrc() routine.
  65284. */
  65285. struct SrcCount {
  65286. SrcList *pSrc; /* One particular FROM clause in a nested query */
  65287. int nThis; /* Number of references to columns in pSrcList */
  65288. int nOther; /* Number of references to columns in other FROM clauses */
  65289. };
  65290. /*
  65291. ** Count the number of references to columns.
  65292. */
  65293. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  65294. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  65295. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  65296. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  65297. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  65298. ** NEVER() will need to be removed. */
  65299. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  65300. int i;
  65301. struct SrcCount *p = pWalker->u.pSrcCount;
  65302. SrcList *pSrc = p->pSrc;
  65303. for(i=0; i<pSrc->nSrc; i++){
  65304. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  65305. }
  65306. if( i<pSrc->nSrc ){
  65307. p->nThis++;
  65308. }else{
  65309. p->nOther++;
  65310. }
  65311. }
  65312. return WRC_Continue;
  65313. }
  65314. /*
  65315. ** Determine if any of the arguments to the pExpr Function reference
  65316. ** pSrcList. Return true if they do. Also return true if the function
  65317. ** has no arguments or has only constant arguments. Return false if pExpr
  65318. ** references columns but not columns of tables found in pSrcList.
  65319. */
  65320. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  65321. Walker w;
  65322. struct SrcCount cnt;
  65323. assert( pExpr->op==TK_AGG_FUNCTION );
  65324. memset(&w, 0, sizeof(w));
  65325. w.xExprCallback = exprSrcCount;
  65326. w.u.pSrcCount = &cnt;
  65327. cnt.pSrc = pSrcList;
  65328. cnt.nThis = 0;
  65329. cnt.nOther = 0;
  65330. sqlite3WalkExprList(&w, pExpr->x.pList);
  65331. return cnt.nThis>0 || cnt.nOther==0;
  65332. }
  65333. /*
  65334. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  65335. ** the new element. Return a negative number if malloc fails.
  65336. */
  65337. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  65338. int i;
  65339. pInfo->aCol = sqlite3ArrayAllocate(
  65340. db,
  65341. pInfo->aCol,
  65342. sizeof(pInfo->aCol[0]),
  65343. &pInfo->nColumn,
  65344. &i
  65345. );
  65346. return i;
  65347. }
  65348. /*
  65349. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  65350. ** the new element. Return a negative number if malloc fails.
  65351. */
  65352. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  65353. int i;
  65354. pInfo->aFunc = sqlite3ArrayAllocate(
  65355. db,
  65356. pInfo->aFunc,
  65357. sizeof(pInfo->aFunc[0]),
  65358. &pInfo->nFunc,
  65359. &i
  65360. );
  65361. return i;
  65362. }
  65363. /*
  65364. ** This is the xExprCallback for a tree walker. It is used to
  65365. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  65366. ** for additional information.
  65367. */
  65368. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  65369. int i;
  65370. NameContext *pNC = pWalker->u.pNC;
  65371. Parse *pParse = pNC->pParse;
  65372. SrcList *pSrcList = pNC->pSrcList;
  65373. AggInfo *pAggInfo = pNC->pAggInfo;
  65374. switch( pExpr->op ){
  65375. case TK_AGG_COLUMN:
  65376. case TK_COLUMN: {
  65377. testcase( pExpr->op==TK_AGG_COLUMN );
  65378. testcase( pExpr->op==TK_COLUMN );
  65379. /* Check to see if the column is in one of the tables in the FROM
  65380. ** clause of the aggregate query */
  65381. if( ALWAYS(pSrcList!=0) ){
  65382. struct SrcList_item *pItem = pSrcList->a;
  65383. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  65384. struct AggInfo_col *pCol;
  65385. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  65386. if( pExpr->iTable==pItem->iCursor ){
  65387. /* If we reach this point, it means that pExpr refers to a table
  65388. ** that is in the FROM clause of the aggregate query.
  65389. **
  65390. ** Make an entry for the column in pAggInfo->aCol[] if there
  65391. ** is not an entry there already.
  65392. */
  65393. int k;
  65394. pCol = pAggInfo->aCol;
  65395. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  65396. if( pCol->iTable==pExpr->iTable &&
  65397. pCol->iColumn==pExpr->iColumn ){
  65398. break;
  65399. }
  65400. }
  65401. if( (k>=pAggInfo->nColumn)
  65402. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  65403. ){
  65404. pCol = &pAggInfo->aCol[k];
  65405. pCol->pTab = pExpr->pTab;
  65406. pCol->iTable = pExpr->iTable;
  65407. pCol->iColumn = pExpr->iColumn;
  65408. pCol->iMem = ++pParse->nMem;
  65409. pCol->iSorterColumn = -1;
  65410. pCol->pExpr = pExpr;
  65411. if( pAggInfo->pGroupBy ){
  65412. int j, n;
  65413. ExprList *pGB = pAggInfo->pGroupBy;
  65414. struct ExprList_item *pTerm = pGB->a;
  65415. n = pGB->nExpr;
  65416. for(j=0; j<n; j++, pTerm++){
  65417. Expr *pE = pTerm->pExpr;
  65418. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  65419. pE->iColumn==pExpr->iColumn ){
  65420. pCol->iSorterColumn = j;
  65421. break;
  65422. }
  65423. }
  65424. }
  65425. if( pCol->iSorterColumn<0 ){
  65426. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  65427. }
  65428. }
  65429. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  65430. ** because it was there before or because we just created it).
  65431. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  65432. ** pAggInfo->aCol[] entry.
  65433. */
  65434. ExprSetVVAProperty(pExpr, EP_NoReduce);
  65435. pExpr->pAggInfo = pAggInfo;
  65436. pExpr->op = TK_AGG_COLUMN;
  65437. pExpr->iAgg = (i16)k;
  65438. break;
  65439. } /* endif pExpr->iTable==pItem->iCursor */
  65440. } /* end loop over pSrcList */
  65441. }
  65442. return WRC_Prune;
  65443. }
  65444. case TK_AGG_FUNCTION: {
  65445. if( (pNC->ncFlags & NC_InAggFunc)==0
  65446. && pWalker->walkerDepth==pExpr->op2
  65447. ){
  65448. /* Check to see if pExpr is a duplicate of another aggregate
  65449. ** function that is already in the pAggInfo structure
  65450. */
  65451. struct AggInfo_func *pItem = pAggInfo->aFunc;
  65452. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  65453. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  65454. break;
  65455. }
  65456. }
  65457. if( i>=pAggInfo->nFunc ){
  65458. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  65459. */
  65460. u8 enc = ENC(pParse->db);
  65461. i = addAggInfoFunc(pParse->db, pAggInfo);
  65462. if( i>=0 ){
  65463. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  65464. pItem = &pAggInfo->aFunc[i];
  65465. pItem->pExpr = pExpr;
  65466. pItem->iMem = ++pParse->nMem;
  65467. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  65468. pItem->pFunc = sqlite3FindFunction(pParse->db,
  65469. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  65470. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  65471. if( pExpr->flags & EP_Distinct ){
  65472. pItem->iDistinct = pParse->nTab++;
  65473. }else{
  65474. pItem->iDistinct = -1;
  65475. }
  65476. }
  65477. }
  65478. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  65479. */
  65480. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  65481. ExprSetVVAProperty(pExpr, EP_NoReduce);
  65482. pExpr->iAgg = (i16)i;
  65483. pExpr->pAggInfo = pAggInfo;
  65484. return WRC_Prune;
  65485. }else{
  65486. return WRC_Continue;
  65487. }
  65488. }
  65489. }
  65490. return WRC_Continue;
  65491. }
  65492. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  65493. UNUSED_PARAMETER(pWalker);
  65494. UNUSED_PARAMETER(pSelect);
  65495. return WRC_Continue;
  65496. }
  65497. /*
  65498. ** Analyze the pExpr expression looking for aggregate functions and
  65499. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  65500. ** points to. Additional entries are made on the AggInfo object as
  65501. ** necessary.
  65502. **
  65503. ** This routine should only be called after the expression has been
  65504. ** analyzed by sqlite3ResolveExprNames().
  65505. */
  65506. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  65507. Walker w;
  65508. memset(&w, 0, sizeof(w));
  65509. w.xExprCallback = analyzeAggregate;
  65510. w.xSelectCallback = analyzeAggregatesInSelect;
  65511. w.u.pNC = pNC;
  65512. assert( pNC->pSrcList!=0 );
  65513. sqlite3WalkExpr(&w, pExpr);
  65514. }
  65515. /*
  65516. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  65517. ** expression list. Return the number of errors.
  65518. **
  65519. ** If an error is found, the analysis is cut short.
  65520. */
  65521. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  65522. struct ExprList_item *pItem;
  65523. int i;
  65524. if( pList ){
  65525. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  65526. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  65527. }
  65528. }
  65529. }
  65530. /*
  65531. ** Allocate a single new register for use to hold some intermediate result.
  65532. */
  65533. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  65534. if( pParse->nTempReg==0 ){
  65535. return ++pParse->nMem;
  65536. }
  65537. return pParse->aTempReg[--pParse->nTempReg];
  65538. }
  65539. /*
  65540. ** Deallocate a register, making available for reuse for some other
  65541. ** purpose.
  65542. **
  65543. ** If a register is currently being used by the column cache, then
  65544. ** the dallocation is deferred until the column cache line that uses
  65545. ** the register becomes stale.
  65546. */
  65547. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  65548. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  65549. int i;
  65550. struct yColCache *p;
  65551. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  65552. if( p->iReg==iReg ){
  65553. p->tempReg = 1;
  65554. return;
  65555. }
  65556. }
  65557. pParse->aTempReg[pParse->nTempReg++] = iReg;
  65558. }
  65559. }
  65560. /*
  65561. ** Allocate or deallocate a block of nReg consecutive registers
  65562. */
  65563. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  65564. int i, n;
  65565. i = pParse->iRangeReg;
  65566. n = pParse->nRangeReg;
  65567. if( nReg<=n ){
  65568. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  65569. pParse->iRangeReg += nReg;
  65570. pParse->nRangeReg -= nReg;
  65571. }else{
  65572. i = pParse->nMem+1;
  65573. pParse->nMem += nReg;
  65574. }
  65575. return i;
  65576. }
  65577. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  65578. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  65579. if( nReg>pParse->nRangeReg ){
  65580. pParse->nRangeReg = nReg;
  65581. pParse->iRangeReg = iReg;
  65582. }
  65583. }
  65584. /*
  65585. ** Mark all temporary registers as being unavailable for reuse.
  65586. */
  65587. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  65588. pParse->nTempReg = 0;
  65589. pParse->nRangeReg = 0;
  65590. }
  65591. /************** End of expr.c ************************************************/
  65592. /************** Begin file alter.c *******************************************/
  65593. /*
  65594. ** 2005 February 15
  65595. **
  65596. ** The author disclaims copyright to this source code. In place of
  65597. ** a legal notice, here is a blessing:
  65598. **
  65599. ** May you do good and not evil.
  65600. ** May you find forgiveness for yourself and forgive others.
  65601. ** May you share freely, never taking more than you give.
  65602. **
  65603. *************************************************************************
  65604. ** This file contains C code routines that used to generate VDBE code
  65605. ** that implements the ALTER TABLE command.
  65606. */
  65607. /*
  65608. ** The code in this file only exists if we are not omitting the
  65609. ** ALTER TABLE logic from the build.
  65610. */
  65611. #ifndef SQLITE_OMIT_ALTERTABLE
  65612. /*
  65613. ** This function is used by SQL generated to implement the
  65614. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  65615. ** CREATE INDEX command. The second is a table name. The table name in
  65616. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  65617. ** argument and the result returned. Examples:
  65618. **
  65619. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  65620. ** -> 'CREATE TABLE def(a, b, c)'
  65621. **
  65622. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  65623. ** -> 'CREATE INDEX i ON def(a, b, c)'
  65624. */
  65625. static void renameTableFunc(
  65626. sqlite3_context *context,
  65627. int NotUsed,
  65628. sqlite3_value **argv
  65629. ){
  65630. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  65631. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  65632. int token;
  65633. Token tname;
  65634. unsigned char const *zCsr = zSql;
  65635. int len = 0;
  65636. char *zRet;
  65637. sqlite3 *db = sqlite3_context_db_handle(context);
  65638. UNUSED_PARAMETER(NotUsed);
  65639. /* The principle used to locate the table name in the CREATE TABLE
  65640. ** statement is that the table name is the first non-space token that
  65641. ** is immediately followed by a TK_LP or TK_USING token.
  65642. */
  65643. if( zSql ){
  65644. do {
  65645. if( !*zCsr ){
  65646. /* Ran out of input before finding an opening bracket. Return NULL. */
  65647. return;
  65648. }
  65649. /* Store the token that zCsr points to in tname. */
  65650. tname.z = (char*)zCsr;
  65651. tname.n = len;
  65652. /* Advance zCsr to the next token. Store that token type in 'token',
  65653. ** and its length in 'len' (to be used next iteration of this loop).
  65654. */
  65655. do {
  65656. zCsr += len;
  65657. len = sqlite3GetToken(zCsr, &token);
  65658. } while( token==TK_SPACE );
  65659. assert( len>0 );
  65660. } while( token!=TK_LP && token!=TK_USING );
  65661. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  65662. zTableName, tname.z+tname.n);
  65663. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  65664. }
  65665. }
  65666. /*
  65667. ** This C function implements an SQL user function that is used by SQL code
  65668. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  65669. ** of any foreign key constraints that use the table being renamed as the
  65670. ** parent table. It is passed three arguments:
  65671. **
  65672. ** 1) The complete text of the CREATE TABLE statement being modified,
  65673. ** 2) The old name of the table being renamed, and
  65674. ** 3) The new name of the table being renamed.
  65675. **
  65676. ** It returns the new CREATE TABLE statement. For example:
  65677. **
  65678. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  65679. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  65680. */
  65681. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65682. static void renameParentFunc(
  65683. sqlite3_context *context,
  65684. int NotUsed,
  65685. sqlite3_value **argv
  65686. ){
  65687. sqlite3 *db = sqlite3_context_db_handle(context);
  65688. char *zOutput = 0;
  65689. char *zResult;
  65690. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  65691. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  65692. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  65693. unsigned const char *z; /* Pointer to token */
  65694. int n; /* Length of token z */
  65695. int token; /* Type of token */
  65696. UNUSED_PARAMETER(NotUsed);
  65697. for(z=zInput; *z; z=z+n){
  65698. n = sqlite3GetToken(z, &token);
  65699. if( token==TK_REFERENCES ){
  65700. char *zParent;
  65701. do {
  65702. z += n;
  65703. n = sqlite3GetToken(z, &token);
  65704. }while( token==TK_SPACE );
  65705. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  65706. if( zParent==0 ) break;
  65707. sqlite3Dequote(zParent);
  65708. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  65709. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  65710. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  65711. );
  65712. sqlite3DbFree(db, zOutput);
  65713. zOutput = zOut;
  65714. zInput = &z[n];
  65715. }
  65716. sqlite3DbFree(db, zParent);
  65717. }
  65718. }
  65719. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  65720. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  65721. sqlite3DbFree(db, zOutput);
  65722. }
  65723. #endif
  65724. #ifndef SQLITE_OMIT_TRIGGER
  65725. /* This function is used by SQL generated to implement the
  65726. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  65727. ** statement. The second is a table name. The table name in the CREATE
  65728. ** TRIGGER statement is replaced with the third argument and the result
  65729. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  65730. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  65731. */
  65732. static void renameTriggerFunc(
  65733. sqlite3_context *context,
  65734. int NotUsed,
  65735. sqlite3_value **argv
  65736. ){
  65737. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  65738. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  65739. int token;
  65740. Token tname;
  65741. int dist = 3;
  65742. unsigned char const *zCsr = zSql;
  65743. int len = 0;
  65744. char *zRet;
  65745. sqlite3 *db = sqlite3_context_db_handle(context);
  65746. UNUSED_PARAMETER(NotUsed);
  65747. /* The principle used to locate the table name in the CREATE TRIGGER
  65748. ** statement is that the table name is the first token that is immediatedly
  65749. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  65750. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  65751. */
  65752. if( zSql ){
  65753. do {
  65754. if( !*zCsr ){
  65755. /* Ran out of input before finding the table name. Return NULL. */
  65756. return;
  65757. }
  65758. /* Store the token that zCsr points to in tname. */
  65759. tname.z = (char*)zCsr;
  65760. tname.n = len;
  65761. /* Advance zCsr to the next token. Store that token type in 'token',
  65762. ** and its length in 'len' (to be used next iteration of this loop).
  65763. */
  65764. do {
  65765. zCsr += len;
  65766. len = sqlite3GetToken(zCsr, &token);
  65767. }while( token==TK_SPACE );
  65768. assert( len>0 );
  65769. /* Variable 'dist' stores the number of tokens read since the most
  65770. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  65771. ** token is read and 'dist' equals 2, the condition stated above
  65772. ** to be met.
  65773. **
  65774. ** Note that ON cannot be a database, table or column name, so
  65775. ** there is no need to worry about syntax like
  65776. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  65777. */
  65778. dist++;
  65779. if( token==TK_DOT || token==TK_ON ){
  65780. dist = 0;
  65781. }
  65782. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  65783. /* Variable tname now contains the token that is the old table-name
  65784. ** in the CREATE TRIGGER statement.
  65785. */
  65786. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  65787. zTableName, tname.z+tname.n);
  65788. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  65789. }
  65790. }
  65791. #endif /* !SQLITE_OMIT_TRIGGER */
  65792. /*
  65793. ** Register built-in functions used to help implement ALTER TABLE
  65794. */
  65795. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  65796. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  65797. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  65798. #ifndef SQLITE_OMIT_TRIGGER
  65799. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  65800. #endif
  65801. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65802. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  65803. #endif
  65804. };
  65805. int i;
  65806. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  65807. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  65808. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  65809. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  65810. }
  65811. }
  65812. /*
  65813. ** This function is used to create the text of expressions of the form:
  65814. **
  65815. ** name=<constant1> OR name=<constant2> OR ...
  65816. **
  65817. ** If argument zWhere is NULL, then a pointer string containing the text
  65818. ** "name=<constant>" is returned, where <constant> is the quoted version
  65819. ** of the string passed as argument zConstant. The returned buffer is
  65820. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  65821. ** caller to ensure that it is eventually freed.
  65822. **
  65823. ** If argument zWhere is not NULL, then the string returned is
  65824. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  65825. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  65826. **
  65827. */
  65828. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  65829. char *zNew;
  65830. if( !zWhere ){
  65831. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  65832. }else{
  65833. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  65834. sqlite3DbFree(db, zWhere);
  65835. }
  65836. return zNew;
  65837. }
  65838. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  65839. /*
  65840. ** Generate the text of a WHERE expression which can be used to select all
  65841. ** tables that have foreign key constraints that refer to table pTab (i.e.
  65842. ** constraints for which pTab is the parent table) from the sqlite_master
  65843. ** table.
  65844. */
  65845. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  65846. FKey *p;
  65847. char *zWhere = 0;
  65848. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  65849. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  65850. }
  65851. return zWhere;
  65852. }
  65853. #endif
  65854. /*
  65855. ** Generate the text of a WHERE expression which can be used to select all
  65856. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  65857. ** table pTab has no temporary triggers, or is itself stored in the
  65858. ** temporary database, NULL is returned.
  65859. */
  65860. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  65861. Trigger *pTrig;
  65862. char *zWhere = 0;
  65863. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  65864. /* If the table is not located in the temp-db (in which case NULL is
  65865. ** returned, loop through the tables list of triggers. For each trigger
  65866. ** that is not part of the temp-db schema, add a clause to the WHERE
  65867. ** expression being built up in zWhere.
  65868. */
  65869. if( pTab->pSchema!=pTempSchema ){
  65870. sqlite3 *db = pParse->db;
  65871. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  65872. if( pTrig->pSchema==pTempSchema ){
  65873. zWhere = whereOrName(db, zWhere, pTrig->zName);
  65874. }
  65875. }
  65876. }
  65877. if( zWhere ){
  65878. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  65879. sqlite3DbFree(pParse->db, zWhere);
  65880. zWhere = zNew;
  65881. }
  65882. return zWhere;
  65883. }
  65884. /*
  65885. ** Generate code to drop and reload the internal representation of table
  65886. ** pTab from the database, including triggers and temporary triggers.
  65887. ** Argument zName is the name of the table in the database schema at
  65888. ** the time the generated code is executed. This can be different from
  65889. ** pTab->zName if this function is being called to code part of an
  65890. ** "ALTER TABLE RENAME TO" statement.
  65891. */
  65892. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  65893. Vdbe *v;
  65894. char *zWhere;
  65895. int iDb; /* Index of database containing pTab */
  65896. #ifndef SQLITE_OMIT_TRIGGER
  65897. Trigger *pTrig;
  65898. #endif
  65899. v = sqlite3GetVdbe(pParse);
  65900. if( NEVER(v==0) ) return;
  65901. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  65902. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  65903. assert( iDb>=0 );
  65904. #ifndef SQLITE_OMIT_TRIGGER
  65905. /* Drop any table triggers from the internal schema. */
  65906. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  65907. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  65908. assert( iTrigDb==iDb || iTrigDb==1 );
  65909. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  65910. }
  65911. #endif
  65912. /* Drop the table and index from the internal schema. */
  65913. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  65914. /* Reload the table, index and permanent trigger schemas. */
  65915. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  65916. if( !zWhere ) return;
  65917. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  65918. #ifndef SQLITE_OMIT_TRIGGER
  65919. /* Now, if the table is not stored in the temp database, reload any temp
  65920. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  65921. */
  65922. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  65923. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  65924. }
  65925. #endif
  65926. }
  65927. /*
  65928. ** Parameter zName is the name of a table that is about to be altered
  65929. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  65930. ** If the table is a system table, this function leaves an error message
  65931. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  65932. **
  65933. ** Or, if zName is not a system table, zero is returned.
  65934. */
  65935. static int isSystemTable(Parse *pParse, const char *zName){
  65936. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  65937. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  65938. return 1;
  65939. }
  65940. return 0;
  65941. }
  65942. /*
  65943. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  65944. ** command.
  65945. */
  65946. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  65947. Parse *pParse, /* Parser context. */
  65948. SrcList *pSrc, /* The table to rename. */
  65949. Token *pName /* The new table name. */
  65950. ){
  65951. int iDb; /* Database that contains the table */
  65952. char *zDb; /* Name of database iDb */
  65953. Table *pTab; /* Table being renamed */
  65954. char *zName = 0; /* NULL-terminated version of pName */
  65955. sqlite3 *db = pParse->db; /* Database connection */
  65956. int nTabName; /* Number of UTF-8 characters in zTabName */
  65957. const char *zTabName; /* Original name of the table */
  65958. Vdbe *v;
  65959. #ifndef SQLITE_OMIT_TRIGGER
  65960. char *zWhere = 0; /* Where clause to locate temp triggers */
  65961. #endif
  65962. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  65963. int savedDbFlags; /* Saved value of db->flags */
  65964. savedDbFlags = db->flags;
  65965. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  65966. assert( pSrc->nSrc==1 );
  65967. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  65968. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  65969. if( !pTab ) goto exit_rename_table;
  65970. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  65971. zDb = db->aDb[iDb].zName;
  65972. db->flags |= SQLITE_PreferBuiltin;
  65973. /* Get a NULL terminated version of the new table name. */
  65974. zName = sqlite3NameFromToken(db, pName);
  65975. if( !zName ) goto exit_rename_table;
  65976. /* Check that a table or index named 'zName' does not already exist
  65977. ** in database iDb. If so, this is an error.
  65978. */
  65979. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  65980. sqlite3ErrorMsg(pParse,
  65981. "there is already another table or index with this name: %s", zName);
  65982. goto exit_rename_table;
  65983. }
  65984. /* Make sure it is not a system table being altered, or a reserved name
  65985. ** that the table is being renamed to.
  65986. */
  65987. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  65988. goto exit_rename_table;
  65989. }
  65990. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  65991. exit_rename_table;
  65992. }
  65993. #ifndef SQLITE_OMIT_VIEW
  65994. if( pTab->pSelect ){
  65995. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  65996. goto exit_rename_table;
  65997. }
  65998. #endif
  65999. #ifndef SQLITE_OMIT_AUTHORIZATION
  66000. /* Invoke the authorization callback. */
  66001. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  66002. goto exit_rename_table;
  66003. }
  66004. #endif
  66005. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66006. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  66007. goto exit_rename_table;
  66008. }
  66009. if( IsVirtual(pTab) ){
  66010. pVTab = sqlite3GetVTable(db, pTab);
  66011. if( pVTab->pVtab->pModule->xRename==0 ){
  66012. pVTab = 0;
  66013. }
  66014. }
  66015. #endif
  66016. /* Begin a transaction and code the VerifyCookie for database iDb.
  66017. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  66018. ** schema). Open a statement transaction if the table is a virtual
  66019. ** table.
  66020. */
  66021. v = sqlite3GetVdbe(pParse);
  66022. if( v==0 ){
  66023. goto exit_rename_table;
  66024. }
  66025. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  66026. sqlite3ChangeCookie(pParse, iDb);
  66027. /* If this is a virtual table, invoke the xRename() function if
  66028. ** one is defined. The xRename() callback will modify the names
  66029. ** of any resources used by the v-table implementation (including other
  66030. ** SQLite tables) that are identified by the name of the virtual table.
  66031. */
  66032. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66033. if( pVTab ){
  66034. int i = ++pParse->nMem;
  66035. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  66036. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  66037. sqlite3MayAbort(pParse);
  66038. }
  66039. #endif
  66040. /* figure out how many UTF-8 characters are in zName */
  66041. zTabName = pTab->zName;
  66042. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  66043. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  66044. if( db->flags&SQLITE_ForeignKeys ){
  66045. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  66046. ** statements corresponding to all child tables of foreign key constraints
  66047. ** for which the renamed table is the parent table. */
  66048. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  66049. sqlite3NestedParse(pParse,
  66050. "UPDATE \"%w\".%s SET "
  66051. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  66052. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  66053. sqlite3DbFree(db, zWhere);
  66054. }
  66055. }
  66056. #endif
  66057. /* Modify the sqlite_master table to use the new table name. */
  66058. sqlite3NestedParse(pParse,
  66059. "UPDATE %Q.%s SET "
  66060. #ifdef SQLITE_OMIT_TRIGGER
  66061. "sql = sqlite_rename_table(sql, %Q), "
  66062. #else
  66063. "sql = CASE "
  66064. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  66065. "ELSE sqlite_rename_table(sql, %Q) END, "
  66066. #endif
  66067. "tbl_name = %Q, "
  66068. "name = CASE "
  66069. "WHEN type='table' THEN %Q "
  66070. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  66071. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  66072. "ELSE name END "
  66073. "WHERE tbl_name=%Q COLLATE nocase AND "
  66074. "(type='table' OR type='index' OR type='trigger');",
  66075. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  66076. #ifndef SQLITE_OMIT_TRIGGER
  66077. zName,
  66078. #endif
  66079. zName, nTabName, zTabName
  66080. );
  66081. #ifndef SQLITE_OMIT_AUTOINCREMENT
  66082. /* If the sqlite_sequence table exists in this database, then update
  66083. ** it with the new table name.
  66084. */
  66085. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  66086. sqlite3NestedParse(pParse,
  66087. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  66088. zDb, zName, pTab->zName);
  66089. }
  66090. #endif
  66091. #ifndef SQLITE_OMIT_TRIGGER
  66092. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  66093. ** table. Don't do this if the table being ALTERed is itself located in
  66094. ** the temp database.
  66095. */
  66096. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  66097. sqlite3NestedParse(pParse,
  66098. "UPDATE sqlite_temp_master SET "
  66099. "sql = sqlite_rename_trigger(sql, %Q), "
  66100. "tbl_name = %Q "
  66101. "WHERE %s;", zName, zName, zWhere);
  66102. sqlite3DbFree(db, zWhere);
  66103. }
  66104. #endif
  66105. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  66106. if( db->flags&SQLITE_ForeignKeys ){
  66107. FKey *p;
  66108. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  66109. Table *pFrom = p->pFrom;
  66110. if( pFrom!=pTab ){
  66111. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  66112. }
  66113. }
  66114. }
  66115. #endif
  66116. /* Drop and reload the internal table schema. */
  66117. reloadTableSchema(pParse, pTab, zName);
  66118. exit_rename_table:
  66119. sqlite3SrcListDelete(db, pSrc);
  66120. sqlite3DbFree(db, zName);
  66121. db->flags = savedDbFlags;
  66122. }
  66123. /*
  66124. ** Generate code to make sure the file format number is at least minFormat.
  66125. ** The generated code will increase the file format number if necessary.
  66126. */
  66127. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  66128. Vdbe *v;
  66129. v = sqlite3GetVdbe(pParse);
  66130. /* The VDBE should have been allocated before this routine is called.
  66131. ** If that allocation failed, we would have quit before reaching this
  66132. ** point */
  66133. if( ALWAYS(v) ){
  66134. int r1 = sqlite3GetTempReg(pParse);
  66135. int r2 = sqlite3GetTempReg(pParse);
  66136. int j1;
  66137. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  66138. sqlite3VdbeUsesBtree(v, iDb);
  66139. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  66140. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  66141. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  66142. sqlite3VdbeJumpHere(v, j1);
  66143. sqlite3ReleaseTempReg(pParse, r1);
  66144. sqlite3ReleaseTempReg(pParse, r2);
  66145. }
  66146. }
  66147. /*
  66148. ** This function is called after an "ALTER TABLE ... ADD" statement
  66149. ** has been parsed. Argument pColDef contains the text of the new
  66150. ** column definition.
  66151. **
  66152. ** The Table structure pParse->pNewTable was extended to include
  66153. ** the new column during parsing.
  66154. */
  66155. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  66156. Table *pNew; /* Copy of pParse->pNewTable */
  66157. Table *pTab; /* Table being altered */
  66158. int iDb; /* Database number */
  66159. const char *zDb; /* Database name */
  66160. const char *zTab; /* Table name */
  66161. char *zCol; /* Null-terminated column definition */
  66162. Column *pCol; /* The new column */
  66163. Expr *pDflt; /* Default value for the new column */
  66164. sqlite3 *db; /* The database connection; */
  66165. db = pParse->db;
  66166. if( pParse->nErr || db->mallocFailed ) return;
  66167. pNew = pParse->pNewTable;
  66168. assert( pNew );
  66169. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66170. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  66171. zDb = db->aDb[iDb].zName;
  66172. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  66173. pCol = &pNew->aCol[pNew->nCol-1];
  66174. pDflt = pCol->pDflt;
  66175. pTab = sqlite3FindTable(db, zTab, zDb);
  66176. assert( pTab );
  66177. #ifndef SQLITE_OMIT_AUTHORIZATION
  66178. /* Invoke the authorization callback. */
  66179. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  66180. return;
  66181. }
  66182. #endif
  66183. /* If the default value for the new column was specified with a
  66184. ** literal NULL, then set pDflt to 0. This simplifies checking
  66185. ** for an SQL NULL default below.
  66186. */
  66187. if( pDflt && pDflt->op==TK_NULL ){
  66188. pDflt = 0;
  66189. }
  66190. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  66191. ** If there is a NOT NULL constraint, then the default value for the
  66192. ** column must not be NULL.
  66193. */
  66194. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  66195. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  66196. return;
  66197. }
  66198. if( pNew->pIndex ){
  66199. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  66200. return;
  66201. }
  66202. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  66203. sqlite3ErrorMsg(pParse,
  66204. "Cannot add a REFERENCES column with non-NULL default value");
  66205. return;
  66206. }
  66207. if( pCol->notNull && !pDflt ){
  66208. sqlite3ErrorMsg(pParse,
  66209. "Cannot add a NOT NULL column with default value NULL");
  66210. return;
  66211. }
  66212. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  66213. ** can handle (i.e. not CURRENT_TIME etc.)
  66214. */
  66215. if( pDflt ){
  66216. sqlite3_value *pVal = 0;
  66217. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  66218. db->mallocFailed = 1;
  66219. return;
  66220. }
  66221. if( !pVal ){
  66222. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  66223. return;
  66224. }
  66225. sqlite3ValueFree(pVal);
  66226. }
  66227. /* Modify the CREATE TABLE statement. */
  66228. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  66229. if( zCol ){
  66230. char *zEnd = &zCol[pColDef->n-1];
  66231. int savedDbFlags = db->flags;
  66232. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  66233. *zEnd-- = '\0';
  66234. }
  66235. db->flags |= SQLITE_PreferBuiltin;
  66236. sqlite3NestedParse(pParse,
  66237. "UPDATE \"%w\".%s SET "
  66238. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  66239. "WHERE type = 'table' AND name = %Q",
  66240. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  66241. zTab
  66242. );
  66243. sqlite3DbFree(db, zCol);
  66244. db->flags = savedDbFlags;
  66245. }
  66246. /* If the default value of the new column is NULL, then set the file
  66247. ** format to 2. If the default value of the new column is not NULL,
  66248. ** the file format becomes 3.
  66249. */
  66250. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  66251. /* Reload the schema of the modified table. */
  66252. reloadTableSchema(pParse, pTab, pTab->zName);
  66253. }
  66254. /*
  66255. ** This function is called by the parser after the table-name in
  66256. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  66257. ** pSrc is the full-name of the table being altered.
  66258. **
  66259. ** This routine makes a (partial) copy of the Table structure
  66260. ** for the table being altered and sets Parse.pNewTable to point
  66261. ** to it. Routines called by the parser as the column definition
  66262. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  66263. ** the copy. The copy of the Table structure is deleted by tokenize.c
  66264. ** after parsing is finished.
  66265. **
  66266. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  66267. ** coding the "ALTER TABLE ... ADD" statement.
  66268. */
  66269. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  66270. Table *pNew;
  66271. Table *pTab;
  66272. Vdbe *v;
  66273. int iDb;
  66274. int i;
  66275. int nAlloc;
  66276. sqlite3 *db = pParse->db;
  66277. /* Look up the table being altered. */
  66278. assert( pParse->pNewTable==0 );
  66279. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66280. if( db->mallocFailed ) goto exit_begin_add_column;
  66281. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  66282. if( !pTab ) goto exit_begin_add_column;
  66283. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66284. if( IsVirtual(pTab) ){
  66285. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  66286. goto exit_begin_add_column;
  66287. }
  66288. #endif
  66289. /* Make sure this is not an attempt to ALTER a view. */
  66290. if( pTab->pSelect ){
  66291. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  66292. goto exit_begin_add_column;
  66293. }
  66294. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  66295. goto exit_begin_add_column;
  66296. }
  66297. assert( pTab->addColOffset>0 );
  66298. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  66299. /* Put a copy of the Table struct in Parse.pNewTable for the
  66300. ** sqlite3AddColumn() function and friends to modify. But modify
  66301. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  66302. ** prefix, we insure that the name will not collide with an existing
  66303. ** table because user table are not allowed to have the "sqlite_"
  66304. ** prefix on their name.
  66305. */
  66306. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  66307. if( !pNew ) goto exit_begin_add_column;
  66308. pParse->pNewTable = pNew;
  66309. pNew->nRef = 1;
  66310. pNew->nCol = pTab->nCol;
  66311. assert( pNew->nCol>0 );
  66312. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  66313. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  66314. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  66315. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  66316. if( !pNew->aCol || !pNew->zName ){
  66317. db->mallocFailed = 1;
  66318. goto exit_begin_add_column;
  66319. }
  66320. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  66321. for(i=0; i<pNew->nCol; i++){
  66322. Column *pCol = &pNew->aCol[i];
  66323. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  66324. pCol->zColl = 0;
  66325. pCol->zType = 0;
  66326. pCol->pDflt = 0;
  66327. pCol->zDflt = 0;
  66328. }
  66329. pNew->pSchema = db->aDb[iDb].pSchema;
  66330. pNew->addColOffset = pTab->addColOffset;
  66331. pNew->nRef = 1;
  66332. /* Begin a transaction and increment the schema cookie. */
  66333. sqlite3BeginWriteOperation(pParse, 0, iDb);
  66334. v = sqlite3GetVdbe(pParse);
  66335. if( !v ) goto exit_begin_add_column;
  66336. sqlite3ChangeCookie(pParse, iDb);
  66337. exit_begin_add_column:
  66338. sqlite3SrcListDelete(db, pSrc);
  66339. return;
  66340. }
  66341. #endif /* SQLITE_ALTER_TABLE */
  66342. /************** End of alter.c ***********************************************/
  66343. /************** Begin file analyze.c *****************************************/
  66344. /*
  66345. ** 2005-07-08
  66346. **
  66347. ** The author disclaims copyright to this source code. In place of
  66348. ** a legal notice, here is a blessing:
  66349. **
  66350. ** May you do good and not evil.
  66351. ** May you find forgiveness for yourself and forgive others.
  66352. ** May you share freely, never taking more than you give.
  66353. **
  66354. *************************************************************************
  66355. ** This file contains code associated with the ANALYZE command.
  66356. **
  66357. ** The ANALYZE command gather statistics about the content of tables
  66358. ** and indices. These statistics are made available to the query planner
  66359. ** to help it make better decisions about how to perform queries.
  66360. **
  66361. ** The following system tables are or have been supported:
  66362. **
  66363. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  66364. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  66365. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  66366. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  66367. **
  66368. ** Additional tables might be added in future releases of SQLite.
  66369. ** The sqlite_stat2 table is not created or used unless the SQLite version
  66370. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  66371. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  66372. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  66373. ** created and used by SQLite versions 3.7.9 and later and with
  66374. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  66375. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  66376. ** version of sqlite_stat3 and is only available when compiled with
  66377. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  66378. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  66379. ** are both enabled, then STAT4 takes precedence.
  66380. **
  66381. ** For most applications, sqlite_stat1 provides all the statisics required
  66382. ** for the query planner to make good choices.
  66383. **
  66384. ** Format of sqlite_stat1:
  66385. **
  66386. ** There is normally one row per index, with the index identified by the
  66387. ** name in the idx column. The tbl column is the name of the table to
  66388. ** which the index belongs. In each such row, the stat column will be
  66389. ** a string consisting of a list of integers. The first integer in this
  66390. ** list is the number of rows in the index. (This is the same as the
  66391. ** number of rows in the table, except for partial indices.) The second
  66392. ** integer is the average number of rows in the index that have the same
  66393. ** value in the first column of the index. The third integer is the average
  66394. ** number of rows in the index that have the same value for the first two
  66395. ** columns. The N-th integer (for N>1) is the average number of rows in
  66396. ** the index which have the same value for the first N-1 columns. For
  66397. ** a K-column index, there will be K+1 integers in the stat column. If
  66398. ** the index is unique, then the last integer will be 1.
  66399. **
  66400. ** The list of integers in the stat column can optionally be followed
  66401. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  66402. ** must be separated from the last integer by a single space. If the
  66403. ** "unordered" keyword is present, then the query planner assumes that
  66404. ** the index is unordered and will not use the index for a range query.
  66405. **
  66406. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  66407. ** column contains a single integer which is the (estimated) number of
  66408. ** rows in the table identified by sqlite_stat1.tbl.
  66409. **
  66410. ** Format of sqlite_stat2:
  66411. **
  66412. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  66413. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  66414. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  66415. ** about the distribution of keys within an index. The index is identified by
  66416. ** the "idx" column and the "tbl" column is the name of the table to which
  66417. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  66418. ** table for each index.
  66419. **
  66420. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  66421. ** inclusive are samples of the left-most key value in the index taken at
  66422. ** evenly spaced points along the index. Let the number of samples be S
  66423. ** (10 in the standard build) and let C be the number of rows in the index.
  66424. ** Then the sampled rows are given by:
  66425. **
  66426. ** rownumber = (i*C*2 + C)/(S*2)
  66427. **
  66428. ** For i between 0 and S-1. Conceptually, the index space is divided into
  66429. ** S uniform buckets and the samples are the middle row from each bucket.
  66430. **
  66431. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  66432. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  66433. ** writes the sqlite_stat2 table. This version of SQLite only supports
  66434. ** sqlite_stat3.
  66435. **
  66436. ** Format for sqlite_stat3:
  66437. **
  66438. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  66439. ** sqlite_stat4 format will be described first. Further information
  66440. ** about sqlite_stat3 follows the sqlite_stat4 description.
  66441. **
  66442. ** Format for sqlite_stat4:
  66443. **
  66444. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  66445. ** to aid the query planner in choosing good indices based on the values
  66446. ** that indexed columns are compared against in the WHERE clauses of
  66447. ** queries.
  66448. **
  66449. ** The sqlite_stat4 table contains multiple entries for each index.
  66450. ** The idx column names the index and the tbl column is the table of the
  66451. ** index. If the idx and tbl columns are the same, then the sample is
  66452. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  66453. ** binary encoding of a key from the index. The nEq column is a
  66454. ** list of integers. The first integer is the approximate number
  66455. ** of entries in the index whose left-most column exactly matches
  66456. ** the left-most column of the sample. The second integer in nEq
  66457. ** is the approximate number of entries in the index where the
  66458. ** first two columns match the first two columns of the sample.
  66459. ** And so forth. nLt is another list of integers that show the approximate
  66460. ** number of entries that are strictly less than the sample. The first
  66461. ** integer in nLt contains the number of entries in the index where the
  66462. ** left-most column is less than the left-most column of the sample.
  66463. ** The K-th integer in the nLt entry is the number of index entries
  66464. ** where the first K columns are less than the first K columns of the
  66465. ** sample. The nDLt column is like nLt except that it contains the
  66466. ** number of distinct entries in the index that are less than the
  66467. ** sample.
  66468. **
  66469. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  66470. ** The ANALYZE command will typically generate sqlite_stat4 tables
  66471. ** that contain between 10 and 40 samples which are distributed across
  66472. ** the key space, though not uniformly, and which include samples with
  66473. ** large nEq values.
  66474. **
  66475. ** Format for sqlite_stat3 redux:
  66476. **
  66477. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  66478. ** looks at the left-most column of the index. The sqlite_stat3.sample
  66479. ** column contains the actual value of the left-most column instead
  66480. ** of a blob encoding of the complete index key as is found in
  66481. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  66482. ** all contain just a single integer which is the same as the first
  66483. ** integer in the equivalent columns in sqlite_stat4.
  66484. */
  66485. #ifndef SQLITE_OMIT_ANALYZE
  66486. #if defined(SQLITE_ENABLE_STAT4)
  66487. # define IsStat4 1
  66488. # define IsStat3 0
  66489. #elif defined(SQLITE_ENABLE_STAT3)
  66490. # define IsStat4 0
  66491. # define IsStat3 1
  66492. #else
  66493. # define IsStat4 0
  66494. # define IsStat3 0
  66495. # undef SQLITE_STAT4_SAMPLES
  66496. # define SQLITE_STAT4_SAMPLES 1
  66497. #endif
  66498. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  66499. /*
  66500. ** This routine generates code that opens the sqlite_statN tables.
  66501. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  66502. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  66503. ** appropriate compile-time options are provided.
  66504. **
  66505. ** If the sqlite_statN tables do not previously exist, it is created.
  66506. **
  66507. ** Argument zWhere may be a pointer to a buffer containing a table name,
  66508. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  66509. ** the sqlite_statN tables associated with the named table are deleted.
  66510. ** If zWhere==0, then code is generated to delete all stat table entries.
  66511. */
  66512. static void openStatTable(
  66513. Parse *pParse, /* Parsing context */
  66514. int iDb, /* The database we are looking in */
  66515. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  66516. const char *zWhere, /* Delete entries for this table or index */
  66517. const char *zWhereType /* Either "tbl" or "idx" */
  66518. ){
  66519. static const struct {
  66520. const char *zName;
  66521. const char *zCols;
  66522. } aTable[] = {
  66523. { "sqlite_stat1", "tbl,idx,stat" },
  66524. #if defined(SQLITE_ENABLE_STAT4)
  66525. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  66526. { "sqlite_stat3", 0 },
  66527. #elif defined(SQLITE_ENABLE_STAT3)
  66528. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  66529. { "sqlite_stat4", 0 },
  66530. #else
  66531. { "sqlite_stat3", 0 },
  66532. { "sqlite_stat4", 0 },
  66533. #endif
  66534. };
  66535. int i;
  66536. sqlite3 *db = pParse->db;
  66537. Db *pDb;
  66538. Vdbe *v = sqlite3GetVdbe(pParse);
  66539. int aRoot[ArraySize(aTable)];
  66540. u8 aCreateTbl[ArraySize(aTable)];
  66541. if( v==0 ) return;
  66542. assert( sqlite3BtreeHoldsAllMutexes(db) );
  66543. assert( sqlite3VdbeDb(v)==db );
  66544. pDb = &db->aDb[iDb];
  66545. /* Create new statistic tables if they do not exist, or clear them
  66546. ** if they do already exist.
  66547. */
  66548. for(i=0; i<ArraySize(aTable); i++){
  66549. const char *zTab = aTable[i].zName;
  66550. Table *pStat;
  66551. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  66552. if( aTable[i].zCols ){
  66553. /* The sqlite_statN table does not exist. Create it. Note that a
  66554. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  66555. ** of the new table in register pParse->regRoot. This is important
  66556. ** because the OpenWrite opcode below will be needing it. */
  66557. sqlite3NestedParse(pParse,
  66558. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  66559. );
  66560. aRoot[i] = pParse->regRoot;
  66561. aCreateTbl[i] = OPFLAG_P2ISREG;
  66562. }
  66563. }else{
  66564. /* The table already exists. If zWhere is not NULL, delete all entries
  66565. ** associated with the table zWhere. If zWhere is NULL, delete the
  66566. ** entire contents of the table. */
  66567. aRoot[i] = pStat->tnum;
  66568. aCreateTbl[i] = 0;
  66569. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  66570. if( zWhere ){
  66571. sqlite3NestedParse(pParse,
  66572. "DELETE FROM %Q.%s WHERE %s=%Q",
  66573. pDb->zName, zTab, zWhereType, zWhere
  66574. );
  66575. }else{
  66576. /* The sqlite_stat[134] table already exists. Delete all rows. */
  66577. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  66578. }
  66579. }
  66580. }
  66581. /* Open the sqlite_stat[134] tables for writing. */
  66582. for(i=0; aTable[i].zCols; i++){
  66583. assert( i<ArraySize(aTable) );
  66584. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  66585. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  66586. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  66587. }
  66588. }
  66589. /*
  66590. ** Recommended number of samples for sqlite_stat4
  66591. */
  66592. #ifndef SQLITE_STAT4_SAMPLES
  66593. # define SQLITE_STAT4_SAMPLES 24
  66594. #endif
  66595. /*
  66596. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  66597. ** share an instance of the following structure to hold their state
  66598. ** information.
  66599. */
  66600. typedef struct Stat4Accum Stat4Accum;
  66601. typedef struct Stat4Sample Stat4Sample;
  66602. struct Stat4Sample {
  66603. tRowcnt *anEq; /* sqlite_stat4.nEq */
  66604. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  66605. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66606. tRowcnt *anLt; /* sqlite_stat4.nLt */
  66607. i64 iRowid; /* Rowid in main table of the key */
  66608. u8 isPSample; /* True if a periodic sample */
  66609. int iCol; /* If !isPSample, the reason for inclusion */
  66610. u32 iHash; /* Tiebreaker hash */
  66611. #endif
  66612. };
  66613. struct Stat4Accum {
  66614. tRowcnt nRow; /* Number of rows in the entire table */
  66615. tRowcnt nPSample; /* How often to do a periodic sample */
  66616. int nCol; /* Number of columns in index + rowid */
  66617. int mxSample; /* Maximum number of samples to accumulate */
  66618. Stat4Sample current; /* Current row as a Stat4Sample */
  66619. u32 iPrn; /* Pseudo-random number used for sampling */
  66620. Stat4Sample *aBest; /* Array of (nCol-1) best samples */
  66621. int iMin; /* Index in a[] of entry with minimum score */
  66622. int nSample; /* Current number of samples */
  66623. int iGet; /* Index of current sample accessed by stat_get() */
  66624. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  66625. };
  66626. /*
  66627. ** Implementation of the stat_init(N,C) SQL function. The two parameters
  66628. ** are the number of rows in the table or index (C) and the number of columns
  66629. ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
  66630. **
  66631. ** This routine allocates the Stat4Accum object in heap memory. The return
  66632. ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
  66633. ** the size of the blob is sizeof(void*) bytes).
  66634. */
  66635. static void statInit(
  66636. sqlite3_context *context,
  66637. int argc,
  66638. sqlite3_value **argv
  66639. ){
  66640. Stat4Accum *p;
  66641. int nCol; /* Number of columns in index being sampled */
  66642. int nColUp; /* nCol rounded up for alignment */
  66643. int n; /* Bytes of space to allocate */
  66644. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66645. int mxSample = SQLITE_STAT4_SAMPLES;
  66646. #endif
  66647. /* Decode the three function arguments */
  66648. UNUSED_PARAMETER(argc);
  66649. nCol = sqlite3_value_int(argv[0]);
  66650. assert( nCol>1 ); /* >1 because it includes the rowid column */
  66651. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  66652. /* Allocate the space required for the Stat4Accum object */
  66653. n = sizeof(*p)
  66654. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  66655. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  66656. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66657. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  66658. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  66659. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  66660. #endif
  66661. ;
  66662. p = sqlite3MallocZero(n);
  66663. if( p==0 ){
  66664. sqlite3_result_error_nomem(context);
  66665. return;
  66666. }
  66667. p->nRow = 0;
  66668. p->nCol = nCol;
  66669. p->current.anDLt = (tRowcnt*)&p[1];
  66670. p->current.anEq = &p->current.anDLt[nColUp];
  66671. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66672. {
  66673. u8 *pSpace; /* Allocated space not yet assigned */
  66674. int i; /* Used to iterate through p->aSample[] */
  66675. p->iGet = -1;
  66676. p->mxSample = mxSample;
  66677. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
  66678. p->current.anLt = &p->current.anEq[nColUp];
  66679. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
  66680. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  66681. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  66682. p->aBest = &p->a[mxSample];
  66683. pSpace = (u8*)(&p->a[mxSample+nCol]);
  66684. for(i=0; i<(mxSample+nCol); i++){
  66685. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66686. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66687. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  66688. }
  66689. assert( (pSpace - (u8*)p)==n );
  66690. for(i=0; i<nCol; i++){
  66691. p->aBest[i].iCol = i;
  66692. }
  66693. }
  66694. #endif
  66695. /* Return a pointer to the allocated object to the caller */
  66696. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  66697. }
  66698. static const FuncDef statInitFuncdef = {
  66699. 1+IsStat34, /* nArg */
  66700. SQLITE_UTF8, /* funcFlags */
  66701. 0, /* pUserData */
  66702. 0, /* pNext */
  66703. statInit, /* xFunc */
  66704. 0, /* xStep */
  66705. 0, /* xFinalize */
  66706. "stat_init", /* zName */
  66707. 0, /* pHash */
  66708. 0 /* pDestructor */
  66709. };
  66710. #ifdef SQLITE_ENABLE_STAT4
  66711. /*
  66712. ** pNew and pOld are both candidate non-periodic samples selected for
  66713. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  66714. ** considering only any trailing columns and the sample hash value, this
  66715. ** function returns true if sample pNew is to be preferred over pOld.
  66716. ** In other words, if we assume that the cardinalities of the selected
  66717. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  66718. **
  66719. ** This function assumes that for each argument sample, the contents of
  66720. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  66721. */
  66722. static int sampleIsBetterPost(
  66723. Stat4Accum *pAccum,
  66724. Stat4Sample *pNew,
  66725. Stat4Sample *pOld
  66726. ){
  66727. int nCol = pAccum->nCol;
  66728. int i;
  66729. assert( pNew->iCol==pOld->iCol );
  66730. for(i=pNew->iCol+1; i<nCol; i++){
  66731. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  66732. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  66733. }
  66734. if( pNew->iHash>pOld->iHash ) return 1;
  66735. return 0;
  66736. }
  66737. #endif
  66738. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66739. /*
  66740. ** Return true if pNew is to be preferred over pOld.
  66741. **
  66742. ** This function assumes that for each argument sample, the contents of
  66743. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  66744. */
  66745. static int sampleIsBetter(
  66746. Stat4Accum *pAccum,
  66747. Stat4Sample *pNew,
  66748. Stat4Sample *pOld
  66749. ){
  66750. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  66751. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  66752. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  66753. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  66754. if( (nEqNew>nEqOld) ) return 1;
  66755. #ifdef SQLITE_ENABLE_STAT4
  66756. if( nEqNew==nEqOld ){
  66757. if( pNew->iCol<pOld->iCol ) return 1;
  66758. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  66759. }
  66760. return 0;
  66761. #else
  66762. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  66763. #endif
  66764. }
  66765. /*
  66766. ** Copy the contents of object (*pFrom) into (*pTo).
  66767. */
  66768. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  66769. pTo->iRowid = pFrom->iRowid;
  66770. pTo->isPSample = pFrom->isPSample;
  66771. pTo->iCol = pFrom->iCol;
  66772. pTo->iHash = pFrom->iHash;
  66773. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  66774. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  66775. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  66776. }
  66777. /*
  66778. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  66779. ** remove the least desirable sample from p->a[] to make room.
  66780. */
  66781. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  66782. Stat4Sample *pSample;
  66783. int i;
  66784. assert( IsStat4 || nEqZero==0 );
  66785. #ifdef SQLITE_ENABLE_STAT4
  66786. if( pNew->isPSample==0 ){
  66787. Stat4Sample *pUpgrade = 0;
  66788. assert( pNew->anEq[pNew->iCol]>0 );
  66789. /* This sample is being added because the prefix that ends in column
  66790. ** iCol occurs many times in the table. However, if we have already
  66791. ** added a sample that shares this prefix, there is no need to add
  66792. ** this one. Instead, upgrade the priority of the highest priority
  66793. ** existing sample that shares this prefix. */
  66794. for(i=p->nSample-1; i>=0; i--){
  66795. Stat4Sample *pOld = &p->a[i];
  66796. if( pOld->anEq[pNew->iCol]==0 ){
  66797. if( pOld->isPSample ) return;
  66798. assert( pOld->iCol>pNew->iCol );
  66799. assert( sampleIsBetter(p, pNew, pOld) );
  66800. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  66801. pUpgrade = pOld;
  66802. }
  66803. }
  66804. }
  66805. if( pUpgrade ){
  66806. pUpgrade->iCol = pNew->iCol;
  66807. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  66808. goto find_new_min;
  66809. }
  66810. }
  66811. #endif
  66812. /* If necessary, remove sample iMin to make room for the new sample. */
  66813. if( p->nSample>=p->mxSample ){
  66814. Stat4Sample *pMin = &p->a[p->iMin];
  66815. tRowcnt *anEq = pMin->anEq;
  66816. tRowcnt *anLt = pMin->anLt;
  66817. tRowcnt *anDLt = pMin->anDLt;
  66818. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  66819. pSample = &p->a[p->nSample-1];
  66820. pSample->anEq = anEq;
  66821. pSample->anDLt = anDLt;
  66822. pSample->anLt = anLt;
  66823. p->nSample = p->mxSample-1;
  66824. }
  66825. /* The "rows less-than" for the rowid column must be greater than that
  66826. ** for the last sample in the p->a[] array. Otherwise, the samples would
  66827. ** be out of order. */
  66828. #ifdef SQLITE_ENABLE_STAT4
  66829. assert( p->nSample==0
  66830. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  66831. #endif
  66832. /* Insert the new sample */
  66833. pSample = &p->a[p->nSample];
  66834. sampleCopy(p, pSample, pNew);
  66835. p->nSample++;
  66836. /* Zero the first nEqZero entries in the anEq[] array. */
  66837. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  66838. #ifdef SQLITE_ENABLE_STAT4
  66839. find_new_min:
  66840. #endif
  66841. if( p->nSample>=p->mxSample ){
  66842. int iMin = -1;
  66843. for(i=0; i<p->mxSample; i++){
  66844. if( p->a[i].isPSample ) continue;
  66845. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  66846. iMin = i;
  66847. }
  66848. }
  66849. assert( iMin>=0 );
  66850. p->iMin = iMin;
  66851. }
  66852. }
  66853. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  66854. /*
  66855. ** Field iChng of the index being scanned has changed. So at this point
  66856. ** p->current contains a sample that reflects the previous row of the
  66857. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  66858. ** correct at this point.
  66859. */
  66860. static void samplePushPrevious(Stat4Accum *p, int iChng){
  66861. #ifdef SQLITE_ENABLE_STAT4
  66862. int i;
  66863. /* Check if any samples from the aBest[] array should be pushed
  66864. ** into IndexSample.a[] at this point. */
  66865. for(i=(p->nCol-2); i>=iChng; i--){
  66866. Stat4Sample *pBest = &p->aBest[i];
  66867. pBest->anEq[i] = p->current.anEq[i];
  66868. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  66869. sampleInsert(p, pBest, i);
  66870. }
  66871. }
  66872. /* Update the anEq[] fields of any samples already collected. */
  66873. for(i=p->nSample-1; i>=0; i--){
  66874. int j;
  66875. for(j=iChng; j<p->nCol; j++){
  66876. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  66877. }
  66878. }
  66879. #endif
  66880. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  66881. if( iChng==0 ){
  66882. tRowcnt nLt = p->current.anLt[0];
  66883. tRowcnt nEq = p->current.anEq[0];
  66884. /* Check if this is to be a periodic sample. If so, add it. */
  66885. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  66886. p->current.isPSample = 1;
  66887. sampleInsert(p, &p->current, 0);
  66888. p->current.isPSample = 0;
  66889. }else
  66890. /* Or if it is a non-periodic sample. Add it in this case too. */
  66891. if( p->nSample<p->mxSample
  66892. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  66893. ){
  66894. sampleInsert(p, &p->current, 0);
  66895. }
  66896. }
  66897. #endif
  66898. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  66899. UNUSED_PARAMETER( p );
  66900. UNUSED_PARAMETER( iChng );
  66901. #endif
  66902. }
  66903. /*
  66904. ** Implementation of the stat_push SQL function: stat_push(P,R,C)
  66905. ** Arguments:
  66906. **
  66907. ** P Pointer to the Stat4Accum object created by stat_init()
  66908. ** C Index of left-most column to differ from previous row
  66909. ** R Rowid for the current row
  66910. **
  66911. ** The SQL function always returns NULL.
  66912. **
  66913. ** The R parameter is only used for STAT3 and STAT4.
  66914. */
  66915. static void statPush(
  66916. sqlite3_context *context,
  66917. int argc,
  66918. sqlite3_value **argv
  66919. ){
  66920. int i;
  66921. /* The three function arguments */
  66922. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  66923. int iChng = sqlite3_value_int(argv[1]);
  66924. UNUSED_PARAMETER( argc );
  66925. UNUSED_PARAMETER( context );
  66926. assert( p->nCol>1 ); /* Includes rowid field */
  66927. assert( iChng<p->nCol );
  66928. if( p->nRow==0 ){
  66929. /* This is the first call to this function. Do initialization. */
  66930. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  66931. }else{
  66932. /* Second and subsequent calls get processed here */
  66933. samplePushPrevious(p, iChng);
  66934. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  66935. ** to the current row of the index. */
  66936. for(i=0; i<iChng; i++){
  66937. p->current.anEq[i]++;
  66938. }
  66939. for(i=iChng; i<p->nCol; i++){
  66940. p->current.anDLt[i]++;
  66941. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66942. p->current.anLt[i] += p->current.anEq[i];
  66943. #endif
  66944. p->current.anEq[i] = 1;
  66945. }
  66946. }
  66947. p->nRow++;
  66948. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66949. p->current.iRowid = sqlite3_value_int64(argv[2]);
  66950. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  66951. #endif
  66952. #ifdef SQLITE_ENABLE_STAT4
  66953. {
  66954. tRowcnt nLt = p->current.anLt[p->nCol-1];
  66955. /* Check if this is to be a periodic sample. If so, add it. */
  66956. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  66957. p->current.isPSample = 1;
  66958. p->current.iCol = 0;
  66959. sampleInsert(p, &p->current, p->nCol-1);
  66960. p->current.isPSample = 0;
  66961. }
  66962. /* Update the aBest[] array. */
  66963. for(i=0; i<(p->nCol-1); i++){
  66964. p->current.iCol = i;
  66965. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  66966. sampleCopy(p, &p->aBest[i], &p->current);
  66967. }
  66968. }
  66969. }
  66970. #endif
  66971. }
  66972. static const FuncDef statPushFuncdef = {
  66973. 2+IsStat34, /* nArg */
  66974. SQLITE_UTF8, /* funcFlags */
  66975. 0, /* pUserData */
  66976. 0, /* pNext */
  66977. statPush, /* xFunc */
  66978. 0, /* xStep */
  66979. 0, /* xFinalize */
  66980. "stat_push", /* zName */
  66981. 0, /* pHash */
  66982. 0 /* pDestructor */
  66983. };
  66984. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  66985. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  66986. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  66987. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  66988. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  66989. /*
  66990. ** Implementation of the stat_get(P,J) SQL function. This routine is
  66991. ** used to query the results. Content is returned for parameter J
  66992. ** which is one of the STAT_GET_xxxx values defined above.
  66993. **
  66994. ** If neither STAT3 nor STAT4 are enabled, then J is always
  66995. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  66996. ** a one-parameter function, stat_get(P), that always returns the
  66997. ** stat1 table entry information.
  66998. */
  66999. static void statGet(
  67000. sqlite3_context *context,
  67001. int argc,
  67002. sqlite3_value **argv
  67003. ){
  67004. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  67005. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67006. /* STAT3 and STAT4 have a parameter on this routine. */
  67007. int eCall = sqlite3_value_int(argv[1]);
  67008. assert( argc==2 );
  67009. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  67010. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  67011. || eCall==STAT_GET_NDLT
  67012. );
  67013. if( eCall==STAT_GET_STAT1 )
  67014. #else
  67015. assert( argc==1 );
  67016. #endif
  67017. {
  67018. /* Return the value to store in the "stat" column of the sqlite_stat1
  67019. ** table for this index.
  67020. **
  67021. ** The value is a string composed of a list of integers describing
  67022. ** the index. The first integer in the list is the total number of
  67023. ** entries in the index. There is one additional integer in the list
  67024. ** for each indexed column. This additional integer is an estimate of
  67025. ** the number of rows matched by a stabbing query on the index using
  67026. ** a key with the corresponding number of fields. In other words,
  67027. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  67028. ** "100 10 2", then SQLite estimates that:
  67029. **
  67030. ** * the index contains 100 rows,
  67031. ** * "WHERE a=?" matches 10 rows, and
  67032. ** * "WHERE a=? AND b=?" matches 2 rows.
  67033. **
  67034. ** If D is the count of distinct values and K is the total number of
  67035. ** rows, then each estimate is computed as:
  67036. **
  67037. ** I = (K+D-1)/D
  67038. */
  67039. char *z;
  67040. int i;
  67041. char *zRet = sqlite3MallocZero(p->nCol * 25);
  67042. if( zRet==0 ){
  67043. sqlite3_result_error_nomem(context);
  67044. return;
  67045. }
  67046. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  67047. z = zRet + sqlite3Strlen30(zRet);
  67048. for(i=0; i<(p->nCol-1); i++){
  67049. u64 nDistinct = p->current.anDLt[i] + 1;
  67050. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  67051. sqlite3_snprintf(24, z, " %llu", iVal);
  67052. z += sqlite3Strlen30(z);
  67053. assert( p->current.anEq[i] );
  67054. }
  67055. assert( z[0]=='\0' && z>zRet );
  67056. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  67057. }
  67058. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67059. else if( eCall==STAT_GET_ROWID ){
  67060. if( p->iGet<0 ){
  67061. samplePushPrevious(p, 0);
  67062. p->iGet = 0;
  67063. }
  67064. if( p->iGet<p->nSample ){
  67065. sqlite3_result_int64(context, p->a[p->iGet].iRowid);
  67066. }
  67067. }else{
  67068. tRowcnt *aCnt = 0;
  67069. assert( p->iGet<p->nSample );
  67070. switch( eCall ){
  67071. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  67072. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  67073. default: {
  67074. aCnt = p->a[p->iGet].anDLt;
  67075. p->iGet++;
  67076. break;
  67077. }
  67078. }
  67079. if( IsStat3 ){
  67080. sqlite3_result_int64(context, (i64)aCnt[0]);
  67081. }else{
  67082. char *zRet = sqlite3MallocZero(p->nCol * 25);
  67083. if( zRet==0 ){
  67084. sqlite3_result_error_nomem(context);
  67085. }else{
  67086. int i;
  67087. char *z = zRet;
  67088. for(i=0; i<p->nCol; i++){
  67089. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  67090. z += sqlite3Strlen30(z);
  67091. }
  67092. assert( z[0]=='\0' && z>zRet );
  67093. z[-1] = '\0';
  67094. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  67095. }
  67096. }
  67097. }
  67098. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67099. #ifndef SQLITE_DEBUG
  67100. UNUSED_PARAMETER( argc );
  67101. #endif
  67102. }
  67103. static const FuncDef statGetFuncdef = {
  67104. 1+IsStat34, /* nArg */
  67105. SQLITE_UTF8, /* funcFlags */
  67106. 0, /* pUserData */
  67107. 0, /* pNext */
  67108. statGet, /* xFunc */
  67109. 0, /* xStep */
  67110. 0, /* xFinalize */
  67111. "stat_get", /* zName */
  67112. 0, /* pHash */
  67113. 0 /* pDestructor */
  67114. };
  67115. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  67116. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  67117. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67118. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  67119. #elif SQLITE_DEBUG
  67120. assert( iParam==STAT_GET_STAT1 );
  67121. #else
  67122. UNUSED_PARAMETER( iParam );
  67123. #endif
  67124. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  67125. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  67126. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  67127. }
  67128. /*
  67129. ** Generate code to do an analysis of all indices associated with
  67130. ** a single table.
  67131. */
  67132. static void analyzeOneTable(
  67133. Parse *pParse, /* Parser context */
  67134. Table *pTab, /* Table whose indices are to be analyzed */
  67135. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  67136. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  67137. int iMem, /* Available memory locations begin here */
  67138. int iTab /* Next available cursor */
  67139. ){
  67140. sqlite3 *db = pParse->db; /* Database handle */
  67141. Index *pIdx; /* An index to being analyzed */
  67142. int iIdxCur; /* Cursor open on index being analyzed */
  67143. int iTabCur; /* Table cursor */
  67144. Vdbe *v; /* The virtual machine being built up */
  67145. int i; /* Loop counter */
  67146. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  67147. int iDb; /* Index of database containing pTab */
  67148. u8 needTableCnt = 1; /* True to count the table */
  67149. int regNewRowid = iMem++; /* Rowid for the inserted record */
  67150. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  67151. int regChng = iMem++; /* Index of changed index field */
  67152. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67153. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  67154. #endif
  67155. int regTemp = iMem++; /* Temporary use register */
  67156. int regTabname = iMem++; /* Register containing table name */
  67157. int regIdxname = iMem++; /* Register containing index name */
  67158. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  67159. int regPrev = iMem; /* MUST BE LAST (see below) */
  67160. pParse->nMem = MAX(pParse->nMem, iMem);
  67161. v = sqlite3GetVdbe(pParse);
  67162. if( v==0 || NEVER(pTab==0) ){
  67163. return;
  67164. }
  67165. if( pTab->tnum==0 ){
  67166. /* Do not gather statistics on views or virtual tables */
  67167. return;
  67168. }
  67169. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  67170. /* Do not gather statistics on system tables */
  67171. return;
  67172. }
  67173. assert( sqlite3BtreeHoldsAllMutexes(db) );
  67174. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67175. assert( iDb>=0 );
  67176. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67177. #ifndef SQLITE_OMIT_AUTHORIZATION
  67178. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  67179. db->aDb[iDb].zName ) ){
  67180. return;
  67181. }
  67182. #endif
  67183. /* Establish a read-lock on the table at the shared-cache level.
  67184. ** Open a read-only cursor on the table. Also allocate a cursor number
  67185. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  67186. ** this time though. */
  67187. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  67188. iTabCur = iTab++;
  67189. iIdxCur = iTab++;
  67190. pParse->nTab = MAX(pParse->nTab, iTab);
  67191. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  67192. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  67193. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  67194. int nCol; /* Number of columns indexed by pIdx */
  67195. KeyInfo *pKey; /* KeyInfo structure for pIdx */
  67196. int *aGotoChng; /* Array of jump instruction addresses */
  67197. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  67198. int addrGotoChng0; /* Address of "Goto addr_chng_0" */
  67199. int addrNextRow; /* Address of "next_row:" */
  67200. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  67201. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  67202. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  67203. nCol = pIdx->nColumn;
  67204. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
  67205. if( aGotoChng==0 ) continue;
  67206. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  67207. /* Populate the register containing the index name. */
  67208. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  67209. /*
  67210. ** Pseudo-code for loop that calls stat_push():
  67211. **
  67212. ** Rewind csr
  67213. ** if eof(csr) goto end_of_scan;
  67214. ** regChng = 0
  67215. ** goto chng_addr_0;
  67216. **
  67217. ** next_row:
  67218. ** regChng = 0
  67219. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  67220. ** regChng = 1
  67221. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  67222. ** ...
  67223. ** regChng = N
  67224. ** goto chng_addr_N
  67225. **
  67226. ** chng_addr_0:
  67227. ** regPrev(0) = idx(0)
  67228. ** chng_addr_1:
  67229. ** regPrev(1) = idx(1)
  67230. ** ...
  67231. **
  67232. ** chng_addr_N:
  67233. ** regRowid = idx(rowid)
  67234. ** stat_push(P, regChng, regRowid)
  67235. ** Next csr
  67236. ** if !eof(csr) goto next_row;
  67237. **
  67238. ** end_of_scan:
  67239. */
  67240. /* Make sure there are enough memory cells allocated to accommodate
  67241. ** the regPrev array and a trailing rowid (the rowid slot is required
  67242. ** when building a record to insert into the sample column of
  67243. ** the sqlite_stat4 table. */
  67244. pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
  67245. /* Open a read-only cursor on the index being analyzed. */
  67246. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  67247. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  67248. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  67249. VdbeComment((v, "%s", pIdx->zName));
  67250. /* Invoke the stat_init() function. The arguments are:
  67251. **
  67252. ** (1) the number of columns in the index including the rowid,
  67253. ** (2) the number of rows in the index,
  67254. **
  67255. ** The second argument is only used for STAT3 and STAT4
  67256. */
  67257. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67258. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
  67259. #endif
  67260. sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
  67261. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  67262. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  67263. sqlite3VdbeChangeP5(v, 1+IsStat34);
  67264. /* Implementation of the following:
  67265. **
  67266. ** Rewind csr
  67267. ** if eof(csr) goto end_of_scan;
  67268. ** regChng = 0
  67269. ** goto next_push_0;
  67270. **
  67271. */
  67272. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  67273. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  67274. addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  67275. /*
  67276. ** next_row:
  67277. ** regChng = 0
  67278. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  67279. ** regChng = 1
  67280. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  67281. ** ...
  67282. ** regChng = N
  67283. ** goto chng_addr_N
  67284. */
  67285. addrNextRow = sqlite3VdbeCurrentAddr(v);
  67286. for(i=0; i<nCol; i++){
  67287. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  67288. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  67289. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  67290. aGotoChng[i] =
  67291. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  67292. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  67293. }
  67294. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  67295. aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  67296. /*
  67297. ** chng_addr_0:
  67298. ** regPrev(0) = idx(0)
  67299. ** chng_addr_1:
  67300. ** regPrev(1) = idx(1)
  67301. ** ...
  67302. */
  67303. sqlite3VdbeJumpHere(v, addrGotoChng0);
  67304. for(i=0; i<nCol; i++){
  67305. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  67306. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  67307. }
  67308. /*
  67309. ** chng_addr_N:
  67310. ** regRowid = idx(rowid) // STAT34 only
  67311. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  67312. ** Next csr
  67313. ** if !eof(csr) goto next_row;
  67314. */
  67315. sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
  67316. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67317. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  67318. assert( regRowid==(regStat4+2) );
  67319. #endif
  67320. assert( regChng==(regStat4+1) );
  67321. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  67322. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  67323. sqlite3VdbeChangeP5(v, 2+IsStat34);
  67324. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
  67325. /* Add the entry to the stat1 table. */
  67326. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  67327. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  67328. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  67329. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  67330. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  67331. /* Add the entries to the stat3 or stat4 table. */
  67332. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67333. {
  67334. int regEq = regStat1;
  67335. int regLt = regStat1+1;
  67336. int regDLt = regStat1+2;
  67337. int regSample = regStat1+3;
  67338. int regCol = regStat1+4;
  67339. int regSampleRowid = regCol + nCol;
  67340. int addrNext;
  67341. int addrIsNull;
  67342. pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  67343. addrNext = sqlite3VdbeCurrentAddr(v);
  67344. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  67345. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  67346. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  67347. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  67348. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  67349. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
  67350. #ifdef SQLITE_ENABLE_STAT3
  67351. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  67352. pIdx->aiColumn[0], regSample);
  67353. #else
  67354. for(i=0; i<nCol; i++){
  67355. int iCol = pIdx->aiColumn[i];
  67356. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  67357. }
  67358. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  67359. #endif
  67360. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
  67361. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  67362. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  67363. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  67364. sqlite3VdbeJumpHere(v, addrIsNull);
  67365. }
  67366. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67367. /* End of analysis */
  67368. sqlite3VdbeJumpHere(v, addrRewind);
  67369. sqlite3DbFree(db, aGotoChng);
  67370. }
  67371. /* Create a single sqlite_stat1 entry containing NULL as the index
  67372. ** name and the row count as the content.
  67373. */
  67374. if( pOnlyIdx==0 && needTableCnt ){
  67375. VdbeComment((v, "%s", pTab->zName));
  67376. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  67377. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  67378. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  67379. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  67380. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  67381. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  67382. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  67383. sqlite3VdbeJumpHere(v, jZeroRows);
  67384. }
  67385. }
  67386. /*
  67387. ** Generate code that will cause the most recent index analysis to
  67388. ** be loaded into internal hash tables where is can be used.
  67389. */
  67390. static void loadAnalysis(Parse *pParse, int iDb){
  67391. Vdbe *v = sqlite3GetVdbe(pParse);
  67392. if( v ){
  67393. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  67394. }
  67395. }
  67396. /*
  67397. ** Generate code that will do an analysis of an entire database
  67398. */
  67399. static void analyzeDatabase(Parse *pParse, int iDb){
  67400. sqlite3 *db = pParse->db;
  67401. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  67402. HashElem *k;
  67403. int iStatCur;
  67404. int iMem;
  67405. int iTab;
  67406. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67407. iStatCur = pParse->nTab;
  67408. pParse->nTab += 3;
  67409. openStatTable(pParse, iDb, iStatCur, 0, 0);
  67410. iMem = pParse->nMem+1;
  67411. iTab = pParse->nTab;
  67412. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67413. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  67414. Table *pTab = (Table*)sqliteHashData(k);
  67415. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  67416. }
  67417. loadAnalysis(pParse, iDb);
  67418. }
  67419. /*
  67420. ** Generate code that will do an analysis of a single table in
  67421. ** a database. If pOnlyIdx is not NULL then it is a single index
  67422. ** in pTab that should be analyzed.
  67423. */
  67424. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  67425. int iDb;
  67426. int iStatCur;
  67427. assert( pTab!=0 );
  67428. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  67429. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  67430. sqlite3BeginWriteOperation(pParse, 0, iDb);
  67431. iStatCur = pParse->nTab;
  67432. pParse->nTab += 3;
  67433. if( pOnlyIdx ){
  67434. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  67435. }else{
  67436. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  67437. }
  67438. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  67439. loadAnalysis(pParse, iDb);
  67440. }
  67441. /*
  67442. ** Generate code for the ANALYZE command. The parser calls this routine
  67443. ** when it recognizes an ANALYZE command.
  67444. **
  67445. ** ANALYZE -- 1
  67446. ** ANALYZE <database> -- 2
  67447. ** ANALYZE ?<database>.?<tablename> -- 3
  67448. **
  67449. ** Form 1 causes all indices in all attached databases to be analyzed.
  67450. ** Form 2 analyzes all indices the single database named.
  67451. ** Form 3 analyzes all indices associated with the named table.
  67452. */
  67453. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  67454. sqlite3 *db = pParse->db;
  67455. int iDb;
  67456. int i;
  67457. char *z, *zDb;
  67458. Table *pTab;
  67459. Index *pIdx;
  67460. Token *pTableName;
  67461. /* Read the database schema. If an error occurs, leave an error message
  67462. ** and code in pParse and return NULL. */
  67463. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  67464. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  67465. return;
  67466. }
  67467. assert( pName2!=0 || pName1==0 );
  67468. if( pName1==0 ){
  67469. /* Form 1: Analyze everything */
  67470. for(i=0; i<db->nDb; i++){
  67471. if( i==1 ) continue; /* Do not analyze the TEMP database */
  67472. analyzeDatabase(pParse, i);
  67473. }
  67474. }else if( pName2->n==0 ){
  67475. /* Form 2: Analyze the database or table named */
  67476. iDb = sqlite3FindDb(db, pName1);
  67477. if( iDb>=0 ){
  67478. analyzeDatabase(pParse, iDb);
  67479. }else{
  67480. z = sqlite3NameFromToken(db, pName1);
  67481. if( z ){
  67482. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  67483. analyzeTable(pParse, pIdx->pTable, pIdx);
  67484. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  67485. analyzeTable(pParse, pTab, 0);
  67486. }
  67487. sqlite3DbFree(db, z);
  67488. }
  67489. }
  67490. }else{
  67491. /* Form 3: Analyze the fully qualified table name */
  67492. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  67493. if( iDb>=0 ){
  67494. zDb = db->aDb[iDb].zName;
  67495. z = sqlite3NameFromToken(db, pTableName);
  67496. if( z ){
  67497. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  67498. analyzeTable(pParse, pIdx->pTable, pIdx);
  67499. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  67500. analyzeTable(pParse, pTab, 0);
  67501. }
  67502. sqlite3DbFree(db, z);
  67503. }
  67504. }
  67505. }
  67506. }
  67507. /*
  67508. ** Used to pass information from the analyzer reader through to the
  67509. ** callback routine.
  67510. */
  67511. typedef struct analysisInfo analysisInfo;
  67512. struct analysisInfo {
  67513. sqlite3 *db;
  67514. const char *zDatabase;
  67515. };
  67516. /*
  67517. ** The first argument points to a nul-terminated string containing a
  67518. ** list of space separated integers. Read the first nOut of these into
  67519. ** the array aOut[].
  67520. */
  67521. static void decodeIntArray(
  67522. char *zIntArray, /* String containing int array to decode */
  67523. int nOut, /* Number of slots in aOut[] */
  67524. tRowcnt *aOut, /* Store integers here */
  67525. Index *pIndex /* Handle extra flags for this index, if not NULL */
  67526. ){
  67527. char *z = zIntArray;
  67528. int c;
  67529. int i;
  67530. tRowcnt v;
  67531. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67532. if( z==0 ) z = "";
  67533. #else
  67534. if( NEVER(z==0) ) z = "";
  67535. #endif
  67536. for(i=0; *z && i<nOut; i++){
  67537. v = 0;
  67538. while( (c=z[0])>='0' && c<='9' ){
  67539. v = v*10 + c - '0';
  67540. z++;
  67541. }
  67542. aOut[i] = v;
  67543. if( *z==' ' ) z++;
  67544. }
  67545. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  67546. assert( pIndex!=0 );
  67547. #else
  67548. if( pIndex )
  67549. #endif
  67550. {
  67551. if( strcmp(z, "unordered")==0 ){
  67552. pIndex->bUnordered = 1;
  67553. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  67554. int v32 = 0;
  67555. sqlite3GetInt32(z+3, &v32);
  67556. pIndex->szIdxRow = sqlite3LogEst(v32);
  67557. }
  67558. }
  67559. }
  67560. /*
  67561. ** This callback is invoked once for each index when reading the
  67562. ** sqlite_stat1 table.
  67563. **
  67564. ** argv[0] = name of the table
  67565. ** argv[1] = name of the index (might be NULL)
  67566. ** argv[2] = results of analysis - on integer for each column
  67567. **
  67568. ** Entries for which argv[1]==NULL simply record the number of rows in
  67569. ** the table.
  67570. */
  67571. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  67572. analysisInfo *pInfo = (analysisInfo*)pData;
  67573. Index *pIndex;
  67574. Table *pTable;
  67575. const char *z;
  67576. assert( argc==3 );
  67577. UNUSED_PARAMETER2(NotUsed, argc);
  67578. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  67579. return 0;
  67580. }
  67581. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  67582. if( pTable==0 ){
  67583. return 0;
  67584. }
  67585. if( argv[1] ){
  67586. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  67587. }else{
  67588. pIndex = 0;
  67589. }
  67590. z = argv[2];
  67591. if( pIndex ){
  67592. decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
  67593. if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
  67594. }else{
  67595. Index fakeIdx;
  67596. fakeIdx.szIdxRow = pTable->szTabRow;
  67597. decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
  67598. pTable->szTabRow = fakeIdx.szIdxRow;
  67599. }
  67600. return 0;
  67601. }
  67602. /*
  67603. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  67604. ** and its contents.
  67605. */
  67606. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  67607. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67608. if( pIdx->aSample ){
  67609. int j;
  67610. for(j=0; j<pIdx->nSample; j++){
  67611. IndexSample *p = &pIdx->aSample[j];
  67612. sqlite3DbFree(db, p->p);
  67613. }
  67614. sqlite3DbFree(db, pIdx->aSample);
  67615. }
  67616. if( db && db->pnBytesFreed==0 ){
  67617. pIdx->nSample = 0;
  67618. pIdx->aSample = 0;
  67619. }
  67620. #else
  67621. UNUSED_PARAMETER(db);
  67622. UNUSED_PARAMETER(pIdx);
  67623. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67624. }
  67625. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67626. /*
  67627. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  67628. ** stored in pIdx->aSample[].
  67629. */
  67630. static void initAvgEq(Index *pIdx){
  67631. if( pIdx ){
  67632. IndexSample *aSample = pIdx->aSample;
  67633. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  67634. int iCol;
  67635. for(iCol=0; iCol<pIdx->nColumn; iCol++){
  67636. int i; /* Used to iterate through samples */
  67637. tRowcnt sumEq = 0; /* Sum of the nEq values */
  67638. tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
  67639. tRowcnt avgEq = 0;
  67640. tRowcnt nDLt = pFinal->anDLt[iCol];
  67641. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  67642. ** occur in the stat4 table for this index before pFinal. Set
  67643. ** sumEq to the sum of the nEq values for column iCol for the same
  67644. ** set (adding the value only once where there exist dupicate
  67645. ** prefixes). */
  67646. for(i=0; i<(pIdx->nSample-1); i++){
  67647. if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
  67648. sumEq += aSample[i].anEq[iCol];
  67649. nSum++;
  67650. }
  67651. }
  67652. if( nDLt>nSum ){
  67653. avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
  67654. }
  67655. if( avgEq==0 ) avgEq = 1;
  67656. pIdx->aAvgEq[iCol] = avgEq;
  67657. if( pIdx->nSampleCol==1 ) break;
  67658. }
  67659. }
  67660. }
  67661. /*
  67662. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  67663. ** into the relevant Index.aSample[] arrays.
  67664. **
  67665. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  67666. ** data equivalent to the following (statements are different for stat3,
  67667. ** see the caller of this function for details):
  67668. **
  67669. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  67670. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  67671. **
  67672. ** where %Q is replaced with the database name before the SQL is executed.
  67673. */
  67674. static int loadStatTbl(
  67675. sqlite3 *db, /* Database handle */
  67676. int bStat3, /* Assume single column records only */
  67677. const char *zSql1, /* SQL statement 1 (see above) */
  67678. const char *zSql2, /* SQL statement 2 (see above) */
  67679. const char *zDb /* Database name (e.g. "main") */
  67680. ){
  67681. int rc; /* Result codes from subroutines */
  67682. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  67683. char *zSql; /* Text of the SQL statement */
  67684. Index *pPrevIdx = 0; /* Previous index in the loop */
  67685. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  67686. assert( db->lookaside.bEnabled==0 );
  67687. zSql = sqlite3MPrintf(db, zSql1, zDb);
  67688. if( !zSql ){
  67689. return SQLITE_NOMEM;
  67690. }
  67691. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  67692. sqlite3DbFree(db, zSql);
  67693. if( rc ) return rc;
  67694. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  67695. int nIdxCol = 1; /* Number of columns in stat4 records */
  67696. int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
  67697. char *zIndex; /* Index name */
  67698. Index *pIdx; /* Pointer to the index object */
  67699. int nSample; /* Number of samples */
  67700. int nByte; /* Bytes of space required */
  67701. int i; /* Bytes of space required */
  67702. tRowcnt *pSpace;
  67703. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  67704. if( zIndex==0 ) continue;
  67705. nSample = sqlite3_column_int(pStmt, 1);
  67706. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  67707. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  67708. /* Index.nSample is non-zero at this point if data has already been
  67709. ** loaded from the stat4 table. In this case ignore stat3 data. */
  67710. if( pIdx==0 || pIdx->nSample ) continue;
  67711. if( bStat3==0 ){
  67712. nIdxCol = pIdx->nColumn+1;
  67713. nAvgCol = pIdx->nColumn;
  67714. }
  67715. pIdx->nSampleCol = nIdxCol;
  67716. nByte = sizeof(IndexSample) * nSample;
  67717. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  67718. nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  67719. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  67720. if( pIdx->aSample==0 ){
  67721. sqlite3_finalize(pStmt);
  67722. return SQLITE_NOMEM;
  67723. }
  67724. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  67725. pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
  67726. for(i=0; i<nSample; i++){
  67727. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  67728. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  67729. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  67730. }
  67731. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  67732. }
  67733. rc = sqlite3_finalize(pStmt);
  67734. if( rc ) return rc;
  67735. zSql = sqlite3MPrintf(db, zSql2, zDb);
  67736. if( !zSql ){
  67737. return SQLITE_NOMEM;
  67738. }
  67739. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  67740. sqlite3DbFree(db, zSql);
  67741. if( rc ) return rc;
  67742. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  67743. char *zIndex; /* Index name */
  67744. Index *pIdx; /* Pointer to the index object */
  67745. int nCol = 1; /* Number of columns in index */
  67746. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  67747. if( zIndex==0 ) continue;
  67748. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  67749. if( pIdx==0 ) continue;
  67750. /* This next condition is true if data has already been loaded from
  67751. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  67752. nCol = pIdx->nSampleCol;
  67753. if( bStat3 && nCol>1 ) continue;
  67754. if( pIdx!=pPrevIdx ){
  67755. initAvgEq(pPrevIdx);
  67756. pPrevIdx = pIdx;
  67757. }
  67758. pSample = &pIdx->aSample[pIdx->nSample];
  67759. decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
  67760. decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
  67761. decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
  67762. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  67763. ** This is in case the sample record is corrupted. In that case, the
  67764. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  67765. ** end of the allocated buffer before it realizes it is dealing with
  67766. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  67767. ** a buffer overread. */
  67768. pSample->n = sqlite3_column_bytes(pStmt, 4);
  67769. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  67770. if( pSample->p==0 ){
  67771. sqlite3_finalize(pStmt);
  67772. return SQLITE_NOMEM;
  67773. }
  67774. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  67775. pIdx->nSample++;
  67776. }
  67777. rc = sqlite3_finalize(pStmt);
  67778. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  67779. return rc;
  67780. }
  67781. /*
  67782. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  67783. ** the Index.aSample[] arrays of all indices.
  67784. */
  67785. static int loadStat4(sqlite3 *db, const char *zDb){
  67786. int rc = SQLITE_OK; /* Result codes from subroutines */
  67787. assert( db->lookaside.bEnabled==0 );
  67788. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  67789. rc = loadStatTbl(db, 0,
  67790. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  67791. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  67792. zDb
  67793. );
  67794. }
  67795. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  67796. rc = loadStatTbl(db, 1,
  67797. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  67798. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  67799. zDb
  67800. );
  67801. }
  67802. return rc;
  67803. }
  67804. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  67805. /*
  67806. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  67807. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  67808. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  67809. ** Index.aSample[] arrays.
  67810. **
  67811. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  67812. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  67813. ** during compilation and the sqlite_stat3/4 table is present, no data is
  67814. ** read from it.
  67815. **
  67816. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  67817. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  67818. ** returned. However, in this case, data is read from the sqlite_stat1
  67819. ** table (if it is present) before returning.
  67820. **
  67821. ** If an OOM error occurs, this function always sets db->mallocFailed.
  67822. ** This means if the caller does not care about other errors, the return
  67823. ** code may be ignored.
  67824. */
  67825. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  67826. analysisInfo sInfo;
  67827. HashElem *i;
  67828. char *zSql;
  67829. int rc;
  67830. assert( iDb>=0 && iDb<db->nDb );
  67831. assert( db->aDb[iDb].pBt!=0 );
  67832. /* Clear any prior statistics */
  67833. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67834. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  67835. Index *pIdx = sqliteHashData(i);
  67836. sqlite3DefaultRowEst(pIdx);
  67837. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67838. sqlite3DeleteIndexSamples(db, pIdx);
  67839. pIdx->aSample = 0;
  67840. #endif
  67841. }
  67842. /* Check to make sure the sqlite_stat1 table exists */
  67843. sInfo.db = db;
  67844. sInfo.zDatabase = db->aDb[iDb].zName;
  67845. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  67846. return SQLITE_ERROR;
  67847. }
  67848. /* Load new statistics out of the sqlite_stat1 table */
  67849. zSql = sqlite3MPrintf(db,
  67850. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  67851. if( zSql==0 ){
  67852. rc = SQLITE_NOMEM;
  67853. }else{
  67854. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  67855. sqlite3DbFree(db, zSql);
  67856. }
  67857. /* Load the statistics from the sqlite_stat4 table. */
  67858. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67859. if( rc==SQLITE_OK ){
  67860. int lookasideEnabled = db->lookaside.bEnabled;
  67861. db->lookaside.bEnabled = 0;
  67862. rc = loadStat4(db, sInfo.zDatabase);
  67863. db->lookaside.bEnabled = lookasideEnabled;
  67864. }
  67865. #endif
  67866. if( rc==SQLITE_NOMEM ){
  67867. db->mallocFailed = 1;
  67868. }
  67869. return rc;
  67870. }
  67871. #endif /* SQLITE_OMIT_ANALYZE */
  67872. /************** End of analyze.c *********************************************/
  67873. /************** Begin file attach.c ******************************************/
  67874. /*
  67875. ** 2003 April 6
  67876. **
  67877. ** The author disclaims copyright to this source code. In place of
  67878. ** a legal notice, here is a blessing:
  67879. **
  67880. ** May you do good and not evil.
  67881. ** May you find forgiveness for yourself and forgive others.
  67882. ** May you share freely, never taking more than you give.
  67883. **
  67884. *************************************************************************
  67885. ** This file contains code used to implement the ATTACH and DETACH commands.
  67886. */
  67887. #ifndef SQLITE_OMIT_ATTACH
  67888. /*
  67889. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  67890. ** is slightly different from resolving a normal SQL expression, because simple
  67891. ** identifiers are treated as strings, not possible column names or aliases.
  67892. **
  67893. ** i.e. if the parser sees:
  67894. **
  67895. ** ATTACH DATABASE abc AS def
  67896. **
  67897. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  67898. ** looking for columns of the same name.
  67899. **
  67900. ** This only applies to the root node of pExpr, so the statement:
  67901. **
  67902. ** ATTACH DATABASE abc||def AS 'db2'
  67903. **
  67904. ** will fail because neither abc or def can be resolved.
  67905. */
  67906. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  67907. {
  67908. int rc = SQLITE_OK;
  67909. if( pExpr ){
  67910. if( pExpr->op!=TK_ID ){
  67911. rc = sqlite3ResolveExprNames(pName, pExpr);
  67912. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  67913. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  67914. return SQLITE_ERROR;
  67915. }
  67916. }else{
  67917. pExpr->op = TK_STRING;
  67918. }
  67919. }
  67920. return rc;
  67921. }
  67922. /*
  67923. ** An SQL user-function registered to do the work of an ATTACH statement. The
  67924. ** three arguments to the function come directly from an attach statement:
  67925. **
  67926. ** ATTACH DATABASE x AS y KEY z
  67927. **
  67928. ** SELECT sqlite_attach(x, y, z)
  67929. **
  67930. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  67931. ** third argument.
  67932. */
  67933. static void attachFunc(
  67934. sqlite3_context *context,
  67935. int NotUsed,
  67936. sqlite3_value **argv
  67937. ){
  67938. int i;
  67939. int rc = 0;
  67940. sqlite3 *db = sqlite3_context_db_handle(context);
  67941. const char *zName;
  67942. const char *zFile;
  67943. char *zPath = 0;
  67944. char *zErr = 0;
  67945. unsigned int flags;
  67946. Db *aNew;
  67947. char *zErrDyn = 0;
  67948. sqlite3_vfs *pVfs;
  67949. UNUSED_PARAMETER(NotUsed);
  67950. zFile = (const char *)sqlite3_value_text(argv[0]);
  67951. zName = (const char *)sqlite3_value_text(argv[1]);
  67952. if( zFile==0 ) zFile = "";
  67953. if( zName==0 ) zName = "";
  67954. /* Check for the following errors:
  67955. **
  67956. ** * Too many attached databases,
  67957. ** * Transaction currently open
  67958. ** * Specified database name already being used.
  67959. */
  67960. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  67961. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  67962. db->aLimit[SQLITE_LIMIT_ATTACHED]
  67963. );
  67964. goto attach_error;
  67965. }
  67966. if( !db->autoCommit ){
  67967. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  67968. goto attach_error;
  67969. }
  67970. for(i=0; i<db->nDb; i++){
  67971. char *z = db->aDb[i].zName;
  67972. assert( z && zName );
  67973. if( sqlite3StrICmp(z, zName)==0 ){
  67974. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  67975. goto attach_error;
  67976. }
  67977. }
  67978. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  67979. ** hash tables.
  67980. */
  67981. if( db->aDb==db->aDbStatic ){
  67982. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  67983. if( aNew==0 ) return;
  67984. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  67985. }else{
  67986. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  67987. if( aNew==0 ) return;
  67988. }
  67989. db->aDb = aNew;
  67990. aNew = &db->aDb[db->nDb];
  67991. memset(aNew, 0, sizeof(*aNew));
  67992. /* Open the database file. If the btree is successfully opened, use
  67993. ** it to obtain the database schema. At this point the schema may
  67994. ** or may not be initialized.
  67995. */
  67996. flags = db->openFlags;
  67997. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  67998. if( rc!=SQLITE_OK ){
  67999. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  68000. sqlite3_result_error(context, zErr, -1);
  68001. sqlite3_free(zErr);
  68002. return;
  68003. }
  68004. assert( pVfs );
  68005. flags |= SQLITE_OPEN_MAIN_DB;
  68006. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  68007. sqlite3_free( zPath );
  68008. db->nDb++;
  68009. if( rc==SQLITE_CONSTRAINT ){
  68010. rc = SQLITE_ERROR;
  68011. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  68012. }else if( rc==SQLITE_OK ){
  68013. Pager *pPager;
  68014. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  68015. if( !aNew->pSchema ){
  68016. rc = SQLITE_NOMEM;
  68017. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  68018. zErrDyn = sqlite3MPrintf(db,
  68019. "attached databases must use the same text encoding as main database");
  68020. rc = SQLITE_ERROR;
  68021. }
  68022. pPager = sqlite3BtreePager(aNew->pBt);
  68023. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  68024. sqlite3BtreeSecureDelete(aNew->pBt,
  68025. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  68026. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  68027. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  68028. #endif
  68029. }
  68030. aNew->safety_level = 3;
  68031. aNew->zName = sqlite3DbStrDup(db, zName);
  68032. if( rc==SQLITE_OK && aNew->zName==0 ){
  68033. rc = SQLITE_NOMEM;
  68034. }
  68035. #ifdef SQLITE_HAS_CODEC
  68036. if( rc==SQLITE_OK ){
  68037. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  68038. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  68039. int nKey;
  68040. char *zKey;
  68041. int t = sqlite3_value_type(argv[2]);
  68042. switch( t ){
  68043. case SQLITE_INTEGER:
  68044. case SQLITE_FLOAT:
  68045. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  68046. rc = SQLITE_ERROR;
  68047. break;
  68048. case SQLITE_TEXT:
  68049. case SQLITE_BLOB:
  68050. nKey = sqlite3_value_bytes(argv[2]);
  68051. zKey = (char *)sqlite3_value_blob(argv[2]);
  68052. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  68053. break;
  68054. case SQLITE_NULL:
  68055. /* No key specified. Use the key from the main database */
  68056. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  68057. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  68058. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  68059. }
  68060. break;
  68061. }
  68062. }
  68063. #endif
  68064. /* If the file was opened successfully, read the schema for the new database.
  68065. ** If this fails, or if opening the file failed, then close the file and
  68066. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  68067. ** we found it.
  68068. */
  68069. if( rc==SQLITE_OK ){
  68070. sqlite3BtreeEnterAll(db);
  68071. rc = sqlite3Init(db, &zErrDyn);
  68072. sqlite3BtreeLeaveAll(db);
  68073. }
  68074. if( rc ){
  68075. int iDb = db->nDb - 1;
  68076. assert( iDb>=2 );
  68077. if( db->aDb[iDb].pBt ){
  68078. sqlite3BtreeClose(db->aDb[iDb].pBt);
  68079. db->aDb[iDb].pBt = 0;
  68080. db->aDb[iDb].pSchema = 0;
  68081. }
  68082. sqlite3ResetAllSchemasOfConnection(db);
  68083. db->nDb = iDb;
  68084. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  68085. db->mallocFailed = 1;
  68086. sqlite3DbFree(db, zErrDyn);
  68087. zErrDyn = sqlite3MPrintf(db, "out of memory");
  68088. }else if( zErrDyn==0 ){
  68089. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  68090. }
  68091. goto attach_error;
  68092. }
  68093. return;
  68094. attach_error:
  68095. /* Return an error if we get here */
  68096. if( zErrDyn ){
  68097. sqlite3_result_error(context, zErrDyn, -1);
  68098. sqlite3DbFree(db, zErrDyn);
  68099. }
  68100. if( rc ) sqlite3_result_error_code(context, rc);
  68101. }
  68102. /*
  68103. ** An SQL user-function registered to do the work of an DETACH statement. The
  68104. ** three arguments to the function come directly from a detach statement:
  68105. **
  68106. ** DETACH DATABASE x
  68107. **
  68108. ** SELECT sqlite_detach(x)
  68109. */
  68110. static void detachFunc(
  68111. sqlite3_context *context,
  68112. int NotUsed,
  68113. sqlite3_value **argv
  68114. ){
  68115. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  68116. sqlite3 *db = sqlite3_context_db_handle(context);
  68117. int i;
  68118. Db *pDb = 0;
  68119. char zErr[128];
  68120. UNUSED_PARAMETER(NotUsed);
  68121. if( zName==0 ) zName = "";
  68122. for(i=0; i<db->nDb; i++){
  68123. pDb = &db->aDb[i];
  68124. if( pDb->pBt==0 ) continue;
  68125. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  68126. }
  68127. if( i>=db->nDb ){
  68128. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  68129. goto detach_error;
  68130. }
  68131. if( i<2 ){
  68132. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  68133. goto detach_error;
  68134. }
  68135. if( !db->autoCommit ){
  68136. sqlite3_snprintf(sizeof(zErr), zErr,
  68137. "cannot DETACH database within transaction");
  68138. goto detach_error;
  68139. }
  68140. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  68141. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  68142. goto detach_error;
  68143. }
  68144. sqlite3BtreeClose(pDb->pBt);
  68145. pDb->pBt = 0;
  68146. pDb->pSchema = 0;
  68147. sqlite3ResetAllSchemasOfConnection(db);
  68148. return;
  68149. detach_error:
  68150. sqlite3_result_error(context, zErr, -1);
  68151. }
  68152. /*
  68153. ** This procedure generates VDBE code for a single invocation of either the
  68154. ** sqlite_detach() or sqlite_attach() SQL user functions.
  68155. */
  68156. static void codeAttach(
  68157. Parse *pParse, /* The parser context */
  68158. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  68159. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  68160. Expr *pAuthArg, /* Expression to pass to authorization callback */
  68161. Expr *pFilename, /* Name of database file */
  68162. Expr *pDbname, /* Name of the database to use internally */
  68163. Expr *pKey /* Database key for encryption extension */
  68164. ){
  68165. int rc;
  68166. NameContext sName;
  68167. Vdbe *v;
  68168. sqlite3* db = pParse->db;
  68169. int regArgs;
  68170. memset(&sName, 0, sizeof(NameContext));
  68171. sName.pParse = pParse;
  68172. if(
  68173. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  68174. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  68175. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  68176. ){
  68177. pParse->nErr++;
  68178. goto attach_end;
  68179. }
  68180. #ifndef SQLITE_OMIT_AUTHORIZATION
  68181. if( pAuthArg ){
  68182. char *zAuthArg;
  68183. if( pAuthArg->op==TK_STRING ){
  68184. zAuthArg = pAuthArg->u.zToken;
  68185. }else{
  68186. zAuthArg = 0;
  68187. }
  68188. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  68189. if(rc!=SQLITE_OK ){
  68190. goto attach_end;
  68191. }
  68192. }
  68193. #endif /* SQLITE_OMIT_AUTHORIZATION */
  68194. v = sqlite3GetVdbe(pParse);
  68195. regArgs = sqlite3GetTempRange(pParse, 4);
  68196. sqlite3ExprCode(pParse, pFilename, regArgs);
  68197. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  68198. sqlite3ExprCode(pParse, pKey, regArgs+2);
  68199. assert( v || db->mallocFailed );
  68200. if( v ){
  68201. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  68202. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  68203. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  68204. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  68205. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  68206. ** statement only). For DETACH, set it to false (expire all existing
  68207. ** statements).
  68208. */
  68209. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  68210. }
  68211. attach_end:
  68212. sqlite3ExprDelete(db, pFilename);
  68213. sqlite3ExprDelete(db, pDbname);
  68214. sqlite3ExprDelete(db, pKey);
  68215. }
  68216. /*
  68217. ** Called by the parser to compile a DETACH statement.
  68218. **
  68219. ** DETACH pDbname
  68220. */
  68221. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  68222. static const FuncDef detach_func = {
  68223. 1, /* nArg */
  68224. SQLITE_UTF8, /* funcFlags */
  68225. 0, /* pUserData */
  68226. 0, /* pNext */
  68227. detachFunc, /* xFunc */
  68228. 0, /* xStep */
  68229. 0, /* xFinalize */
  68230. "sqlite_detach", /* zName */
  68231. 0, /* pHash */
  68232. 0 /* pDestructor */
  68233. };
  68234. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  68235. }
  68236. /*
  68237. ** Called by the parser to compile an ATTACH statement.
  68238. **
  68239. ** ATTACH p AS pDbname KEY pKey
  68240. */
  68241. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  68242. static const FuncDef attach_func = {
  68243. 3, /* nArg */
  68244. SQLITE_UTF8, /* funcFlags */
  68245. 0, /* pUserData */
  68246. 0, /* pNext */
  68247. attachFunc, /* xFunc */
  68248. 0, /* xStep */
  68249. 0, /* xFinalize */
  68250. "sqlite_attach", /* zName */
  68251. 0, /* pHash */
  68252. 0 /* pDestructor */
  68253. };
  68254. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  68255. }
  68256. #endif /* SQLITE_OMIT_ATTACH */
  68257. /*
  68258. ** Initialize a DbFixer structure. This routine must be called prior
  68259. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  68260. */
  68261. SQLITE_PRIVATE void sqlite3FixInit(
  68262. DbFixer *pFix, /* The fixer to be initialized */
  68263. Parse *pParse, /* Error messages will be written here */
  68264. int iDb, /* This is the database that must be used */
  68265. const char *zType, /* "view", "trigger", or "index" */
  68266. const Token *pName /* Name of the view, trigger, or index */
  68267. ){
  68268. sqlite3 *db;
  68269. db = pParse->db;
  68270. assert( db->nDb>iDb );
  68271. pFix->pParse = pParse;
  68272. pFix->zDb = db->aDb[iDb].zName;
  68273. pFix->pSchema = db->aDb[iDb].pSchema;
  68274. pFix->zType = zType;
  68275. pFix->pName = pName;
  68276. pFix->bVarOnly = (iDb==1);
  68277. }
  68278. /*
  68279. ** The following set of routines walk through the parse tree and assign
  68280. ** a specific database to all table references where the database name
  68281. ** was left unspecified in the original SQL statement. The pFix structure
  68282. ** must have been initialized by a prior call to sqlite3FixInit().
  68283. **
  68284. ** These routines are used to make sure that an index, trigger, or
  68285. ** view in one database does not refer to objects in a different database.
  68286. ** (Exception: indices, triggers, and views in the TEMP database are
  68287. ** allowed to refer to anything.) If a reference is explicitly made
  68288. ** to an object in a different database, an error message is added to
  68289. ** pParse->zErrMsg and these routines return non-zero. If everything
  68290. ** checks out, these routines return 0.
  68291. */
  68292. SQLITE_PRIVATE int sqlite3FixSrcList(
  68293. DbFixer *pFix, /* Context of the fixation */
  68294. SrcList *pList /* The Source list to check and modify */
  68295. ){
  68296. int i;
  68297. const char *zDb;
  68298. struct SrcList_item *pItem;
  68299. if( NEVER(pList==0) ) return 0;
  68300. zDb = pFix->zDb;
  68301. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  68302. if( pFix->bVarOnly==0 ){
  68303. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  68304. sqlite3ErrorMsg(pFix->pParse,
  68305. "%s %T cannot reference objects in database %s",
  68306. pFix->zType, pFix->pName, pItem->zDatabase);
  68307. return 1;
  68308. }
  68309. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  68310. pItem->zDatabase = 0;
  68311. pItem->pSchema = pFix->pSchema;
  68312. }
  68313. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  68314. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  68315. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  68316. #endif
  68317. }
  68318. return 0;
  68319. }
  68320. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  68321. SQLITE_PRIVATE int sqlite3FixSelect(
  68322. DbFixer *pFix, /* Context of the fixation */
  68323. Select *pSelect /* The SELECT statement to be fixed to one database */
  68324. ){
  68325. while( pSelect ){
  68326. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  68327. return 1;
  68328. }
  68329. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  68330. return 1;
  68331. }
  68332. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  68333. return 1;
  68334. }
  68335. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  68336. return 1;
  68337. }
  68338. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  68339. return 1;
  68340. }
  68341. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  68342. return 1;
  68343. }
  68344. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  68345. return 1;
  68346. }
  68347. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  68348. return 1;
  68349. }
  68350. pSelect = pSelect->pPrior;
  68351. }
  68352. return 0;
  68353. }
  68354. SQLITE_PRIVATE int sqlite3FixExpr(
  68355. DbFixer *pFix, /* Context of the fixation */
  68356. Expr *pExpr /* The expression to be fixed to one database */
  68357. ){
  68358. while( pExpr ){
  68359. if( pExpr->op==TK_VARIABLE ){
  68360. if( pFix->pParse->db->init.busy ){
  68361. pExpr->op = TK_NULL;
  68362. }else{
  68363. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  68364. return 1;
  68365. }
  68366. }
  68367. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  68368. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  68369. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  68370. }else{
  68371. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  68372. }
  68373. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  68374. return 1;
  68375. }
  68376. pExpr = pExpr->pLeft;
  68377. }
  68378. return 0;
  68379. }
  68380. SQLITE_PRIVATE int sqlite3FixExprList(
  68381. DbFixer *pFix, /* Context of the fixation */
  68382. ExprList *pList /* The expression to be fixed to one database */
  68383. ){
  68384. int i;
  68385. struct ExprList_item *pItem;
  68386. if( pList==0 ) return 0;
  68387. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  68388. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  68389. return 1;
  68390. }
  68391. }
  68392. return 0;
  68393. }
  68394. #endif
  68395. #ifndef SQLITE_OMIT_TRIGGER
  68396. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  68397. DbFixer *pFix, /* Context of the fixation */
  68398. TriggerStep *pStep /* The trigger step be fixed to one database */
  68399. ){
  68400. while( pStep ){
  68401. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  68402. return 1;
  68403. }
  68404. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  68405. return 1;
  68406. }
  68407. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  68408. return 1;
  68409. }
  68410. pStep = pStep->pNext;
  68411. }
  68412. return 0;
  68413. }
  68414. #endif
  68415. /************** End of attach.c **********************************************/
  68416. /************** Begin file auth.c ********************************************/
  68417. /*
  68418. ** 2003 January 11
  68419. **
  68420. ** The author disclaims copyright to this source code. In place of
  68421. ** a legal notice, here is a blessing:
  68422. **
  68423. ** May you do good and not evil.
  68424. ** May you find forgiveness for yourself and forgive others.
  68425. ** May you share freely, never taking more than you give.
  68426. **
  68427. *************************************************************************
  68428. ** This file contains code used to implement the sqlite3_set_authorizer()
  68429. ** API. This facility is an optional feature of the library. Embedded
  68430. ** systems that do not need this facility may omit it by recompiling
  68431. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  68432. */
  68433. /*
  68434. ** All of the code in this file may be omitted by defining a single
  68435. ** macro.
  68436. */
  68437. #ifndef SQLITE_OMIT_AUTHORIZATION
  68438. /*
  68439. ** Set or clear the access authorization function.
  68440. **
  68441. ** The access authorization function is be called during the compilation
  68442. ** phase to verify that the user has read and/or write access permission on
  68443. ** various fields of the database. The first argument to the auth function
  68444. ** is a copy of the 3rd argument to this routine. The second argument
  68445. ** to the auth function is one of these constants:
  68446. **
  68447. ** SQLITE_CREATE_INDEX
  68448. ** SQLITE_CREATE_TABLE
  68449. ** SQLITE_CREATE_TEMP_INDEX
  68450. ** SQLITE_CREATE_TEMP_TABLE
  68451. ** SQLITE_CREATE_TEMP_TRIGGER
  68452. ** SQLITE_CREATE_TEMP_VIEW
  68453. ** SQLITE_CREATE_TRIGGER
  68454. ** SQLITE_CREATE_VIEW
  68455. ** SQLITE_DELETE
  68456. ** SQLITE_DROP_INDEX
  68457. ** SQLITE_DROP_TABLE
  68458. ** SQLITE_DROP_TEMP_INDEX
  68459. ** SQLITE_DROP_TEMP_TABLE
  68460. ** SQLITE_DROP_TEMP_TRIGGER
  68461. ** SQLITE_DROP_TEMP_VIEW
  68462. ** SQLITE_DROP_TRIGGER
  68463. ** SQLITE_DROP_VIEW
  68464. ** SQLITE_INSERT
  68465. ** SQLITE_PRAGMA
  68466. ** SQLITE_READ
  68467. ** SQLITE_SELECT
  68468. ** SQLITE_TRANSACTION
  68469. ** SQLITE_UPDATE
  68470. **
  68471. ** The third and fourth arguments to the auth function are the name of
  68472. ** the table and the column that are being accessed. The auth function
  68473. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  68474. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  68475. ** means that the SQL statement will never-run - the sqlite3_exec() call
  68476. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  68477. ** should run but attempts to read the specified column will return NULL
  68478. ** and attempts to write the column will be ignored.
  68479. **
  68480. ** Setting the auth function to NULL disables this hook. The default
  68481. ** setting of the auth function is NULL.
  68482. */
  68483. SQLITE_API int sqlite3_set_authorizer(
  68484. sqlite3 *db,
  68485. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  68486. void *pArg
  68487. ){
  68488. sqlite3_mutex_enter(db->mutex);
  68489. db->xAuth = xAuth;
  68490. db->pAuthArg = pArg;
  68491. sqlite3ExpirePreparedStatements(db);
  68492. sqlite3_mutex_leave(db->mutex);
  68493. return SQLITE_OK;
  68494. }
  68495. /*
  68496. ** Write an error message into pParse->zErrMsg that explains that the
  68497. ** user-supplied authorization function returned an illegal value.
  68498. */
  68499. static void sqliteAuthBadReturnCode(Parse *pParse){
  68500. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  68501. pParse->rc = SQLITE_ERROR;
  68502. }
  68503. /*
  68504. ** Invoke the authorization callback for permission to read column zCol from
  68505. ** table zTab in database zDb. This function assumes that an authorization
  68506. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  68507. **
  68508. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  68509. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  68510. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  68511. */
  68512. SQLITE_PRIVATE int sqlite3AuthReadCol(
  68513. Parse *pParse, /* The parser context */
  68514. const char *zTab, /* Table name */
  68515. const char *zCol, /* Column name */
  68516. int iDb /* Index of containing database. */
  68517. ){
  68518. sqlite3 *db = pParse->db; /* Database handle */
  68519. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  68520. int rc; /* Auth callback return code */
  68521. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  68522. if( rc==SQLITE_DENY ){
  68523. if( db->nDb>2 || iDb!=0 ){
  68524. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  68525. }else{
  68526. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  68527. }
  68528. pParse->rc = SQLITE_AUTH;
  68529. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  68530. sqliteAuthBadReturnCode(pParse);
  68531. }
  68532. return rc;
  68533. }
  68534. /*
  68535. ** The pExpr should be a TK_COLUMN expression. The table referred to
  68536. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  68537. ** Check to see if it is OK to read this particular column.
  68538. **
  68539. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  68540. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  68541. ** then generate an error.
  68542. */
  68543. SQLITE_PRIVATE void sqlite3AuthRead(
  68544. Parse *pParse, /* The parser context */
  68545. Expr *pExpr, /* The expression to check authorization on */
  68546. Schema *pSchema, /* The schema of the expression */
  68547. SrcList *pTabList /* All table that pExpr might refer to */
  68548. ){
  68549. sqlite3 *db = pParse->db;
  68550. Table *pTab = 0; /* The table being read */
  68551. const char *zCol; /* Name of the column of the table */
  68552. int iSrc; /* Index in pTabList->a[] of table being read */
  68553. int iDb; /* The index of the database the expression refers to */
  68554. int iCol; /* Index of column in table */
  68555. if( db->xAuth==0 ) return;
  68556. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  68557. if( iDb<0 ){
  68558. /* An attempt to read a column out of a subquery or other
  68559. ** temporary table. */
  68560. return;
  68561. }
  68562. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  68563. if( pExpr->op==TK_TRIGGER ){
  68564. pTab = pParse->pTriggerTab;
  68565. }else{
  68566. assert( pTabList );
  68567. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  68568. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  68569. pTab = pTabList->a[iSrc].pTab;
  68570. break;
  68571. }
  68572. }
  68573. }
  68574. iCol = pExpr->iColumn;
  68575. if( NEVER(pTab==0) ) return;
  68576. if( iCol>=0 ){
  68577. assert( iCol<pTab->nCol );
  68578. zCol = pTab->aCol[iCol].zName;
  68579. }else if( pTab->iPKey>=0 ){
  68580. assert( pTab->iPKey<pTab->nCol );
  68581. zCol = pTab->aCol[pTab->iPKey].zName;
  68582. }else{
  68583. zCol = "ROWID";
  68584. }
  68585. assert( iDb>=0 && iDb<db->nDb );
  68586. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  68587. pExpr->op = TK_NULL;
  68588. }
  68589. }
  68590. /*
  68591. ** Do an authorization check using the code and arguments given. Return
  68592. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  68593. ** is returned, then the error count and error message in pParse are
  68594. ** modified appropriately.
  68595. */
  68596. SQLITE_PRIVATE int sqlite3AuthCheck(
  68597. Parse *pParse,
  68598. int code,
  68599. const char *zArg1,
  68600. const char *zArg2,
  68601. const char *zArg3
  68602. ){
  68603. sqlite3 *db = pParse->db;
  68604. int rc;
  68605. /* Don't do any authorization checks if the database is initialising
  68606. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  68607. */
  68608. if( db->init.busy || IN_DECLARE_VTAB ){
  68609. return SQLITE_OK;
  68610. }
  68611. if( db->xAuth==0 ){
  68612. return SQLITE_OK;
  68613. }
  68614. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  68615. if( rc==SQLITE_DENY ){
  68616. sqlite3ErrorMsg(pParse, "not authorized");
  68617. pParse->rc = SQLITE_AUTH;
  68618. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  68619. rc = SQLITE_DENY;
  68620. sqliteAuthBadReturnCode(pParse);
  68621. }
  68622. return rc;
  68623. }
  68624. /*
  68625. ** Push an authorization context. After this routine is called, the
  68626. ** zArg3 argument to authorization callbacks will be zContext until
  68627. ** popped. Or if pParse==0, this routine is a no-op.
  68628. */
  68629. SQLITE_PRIVATE void sqlite3AuthContextPush(
  68630. Parse *pParse,
  68631. AuthContext *pContext,
  68632. const char *zContext
  68633. ){
  68634. assert( pParse );
  68635. pContext->pParse = pParse;
  68636. pContext->zAuthContext = pParse->zAuthContext;
  68637. pParse->zAuthContext = zContext;
  68638. }
  68639. /*
  68640. ** Pop an authorization context that was previously pushed
  68641. ** by sqlite3AuthContextPush
  68642. */
  68643. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  68644. if( pContext->pParse ){
  68645. pContext->pParse->zAuthContext = pContext->zAuthContext;
  68646. pContext->pParse = 0;
  68647. }
  68648. }
  68649. #endif /* SQLITE_OMIT_AUTHORIZATION */
  68650. /************** End of auth.c ************************************************/
  68651. /************** Begin file build.c *******************************************/
  68652. /*
  68653. ** 2001 September 15
  68654. **
  68655. ** The author disclaims copyright to this source code. In place of
  68656. ** a legal notice, here is a blessing:
  68657. **
  68658. ** May you do good and not evil.
  68659. ** May you find forgiveness for yourself and forgive others.
  68660. ** May you share freely, never taking more than you give.
  68661. **
  68662. *************************************************************************
  68663. ** This file contains C code routines that are called by the SQLite parser
  68664. ** when syntax rules are reduced. The routines in this file handle the
  68665. ** following kinds of SQL syntax:
  68666. **
  68667. ** CREATE TABLE
  68668. ** DROP TABLE
  68669. ** CREATE INDEX
  68670. ** DROP INDEX
  68671. ** creating ID lists
  68672. ** BEGIN TRANSACTION
  68673. ** COMMIT
  68674. ** ROLLBACK
  68675. */
  68676. /*
  68677. ** This routine is called when a new SQL statement is beginning to
  68678. ** be parsed. Initialize the pParse structure as needed.
  68679. */
  68680. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  68681. pParse->explain = (u8)explainFlag;
  68682. pParse->nVar = 0;
  68683. }
  68684. #ifndef SQLITE_OMIT_SHARED_CACHE
  68685. /*
  68686. ** The TableLock structure is only used by the sqlite3TableLock() and
  68687. ** codeTableLocks() functions.
  68688. */
  68689. struct TableLock {
  68690. int iDb; /* The database containing the table to be locked */
  68691. int iTab; /* The root page of the table to be locked */
  68692. u8 isWriteLock; /* True for write lock. False for a read lock */
  68693. const char *zName; /* Name of the table */
  68694. };
  68695. /*
  68696. ** Record the fact that we want to lock a table at run-time.
  68697. **
  68698. ** The table to be locked has root page iTab and is found in database iDb.
  68699. ** A read or a write lock can be taken depending on isWritelock.
  68700. **
  68701. ** This routine just records the fact that the lock is desired. The
  68702. ** code to make the lock occur is generated by a later call to
  68703. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  68704. */
  68705. SQLITE_PRIVATE void sqlite3TableLock(
  68706. Parse *pParse, /* Parsing context */
  68707. int iDb, /* Index of the database containing the table to lock */
  68708. int iTab, /* Root page number of the table to be locked */
  68709. u8 isWriteLock, /* True for a write lock */
  68710. const char *zName /* Name of the table to be locked */
  68711. ){
  68712. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  68713. int i;
  68714. int nBytes;
  68715. TableLock *p;
  68716. assert( iDb>=0 );
  68717. for(i=0; i<pToplevel->nTableLock; i++){
  68718. p = &pToplevel->aTableLock[i];
  68719. if( p->iDb==iDb && p->iTab==iTab ){
  68720. p->isWriteLock = (p->isWriteLock || isWriteLock);
  68721. return;
  68722. }
  68723. }
  68724. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  68725. pToplevel->aTableLock =
  68726. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  68727. if( pToplevel->aTableLock ){
  68728. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  68729. p->iDb = iDb;
  68730. p->iTab = iTab;
  68731. p->isWriteLock = isWriteLock;
  68732. p->zName = zName;
  68733. }else{
  68734. pToplevel->nTableLock = 0;
  68735. pToplevel->db->mallocFailed = 1;
  68736. }
  68737. }
  68738. /*
  68739. ** Code an OP_TableLock instruction for each table locked by the
  68740. ** statement (configured by calls to sqlite3TableLock()).
  68741. */
  68742. static void codeTableLocks(Parse *pParse){
  68743. int i;
  68744. Vdbe *pVdbe;
  68745. pVdbe = sqlite3GetVdbe(pParse);
  68746. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  68747. for(i=0; i<pParse->nTableLock; i++){
  68748. TableLock *p = &pParse->aTableLock[i];
  68749. int p1 = p->iDb;
  68750. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  68751. p->zName, P4_STATIC);
  68752. }
  68753. }
  68754. #else
  68755. #define codeTableLocks(x)
  68756. #endif
  68757. /*
  68758. ** This routine is called after a single SQL statement has been
  68759. ** parsed and a VDBE program to execute that statement has been
  68760. ** prepared. This routine puts the finishing touches on the
  68761. ** VDBE program and resets the pParse structure for the next
  68762. ** parse.
  68763. **
  68764. ** Note that if an error occurred, it might be the case that
  68765. ** no VDBE code was generated.
  68766. */
  68767. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  68768. sqlite3 *db;
  68769. Vdbe *v;
  68770. assert( pParse->pToplevel==0 );
  68771. db = pParse->db;
  68772. if( db->mallocFailed ) return;
  68773. if( pParse->nested ) return;
  68774. if( pParse->nErr ) return;
  68775. /* Begin by generating some termination code at the end of the
  68776. ** vdbe program
  68777. */
  68778. v = sqlite3GetVdbe(pParse);
  68779. assert( !pParse->isMultiWrite
  68780. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  68781. if( v ){
  68782. sqlite3VdbeAddOp0(v, OP_Halt);
  68783. /* The cookie mask contains one bit for each database file open.
  68784. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  68785. ** set for each database that is used. Generate code to start a
  68786. ** transaction on each used database and to verify the schema cookie
  68787. ** on each used database.
  68788. */
  68789. if( pParse->cookieGoto>0 ){
  68790. yDbMask mask;
  68791. int iDb;
  68792. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  68793. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  68794. if( (mask & pParse->cookieMask)==0 ) continue;
  68795. sqlite3VdbeUsesBtree(v, iDb);
  68796. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  68797. if( db->init.busy==0 ){
  68798. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  68799. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  68800. iDb, pParse->cookieValue[iDb],
  68801. db->aDb[iDb].pSchema->iGeneration);
  68802. }
  68803. }
  68804. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68805. {
  68806. int i;
  68807. for(i=0; i<pParse->nVtabLock; i++){
  68808. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  68809. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  68810. }
  68811. pParse->nVtabLock = 0;
  68812. }
  68813. #endif
  68814. /* Once all the cookies have been verified and transactions opened,
  68815. ** obtain the required table-locks. This is a no-op unless the
  68816. ** shared-cache feature is enabled.
  68817. */
  68818. codeTableLocks(pParse);
  68819. /* Initialize any AUTOINCREMENT data structures required.
  68820. */
  68821. sqlite3AutoincrementBegin(pParse);
  68822. /* Finally, jump back to the beginning of the executable code. */
  68823. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  68824. }
  68825. }
  68826. /* Get the VDBE program ready for execution
  68827. */
  68828. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  68829. #ifdef SQLITE_DEBUG
  68830. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  68831. sqlite3VdbeTrace(v, trace);
  68832. #endif
  68833. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  68834. /* A minimum of one cursor is required if autoincrement is used
  68835. * See ticket [a696379c1f08866] */
  68836. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  68837. sqlite3VdbeMakeReady(v, pParse);
  68838. pParse->rc = SQLITE_DONE;
  68839. pParse->colNamesSet = 0;
  68840. }else{
  68841. pParse->rc = SQLITE_ERROR;
  68842. }
  68843. pParse->nTab = 0;
  68844. pParse->nMem = 0;
  68845. pParse->nSet = 0;
  68846. pParse->nVar = 0;
  68847. pParse->cookieMask = 0;
  68848. pParse->cookieGoto = 0;
  68849. }
  68850. /*
  68851. ** Run the parser and code generator recursively in order to generate
  68852. ** code for the SQL statement given onto the end of the pParse context
  68853. ** currently under construction. When the parser is run recursively
  68854. ** this way, the final OP_Halt is not appended and other initialization
  68855. ** and finalization steps are omitted because those are handling by the
  68856. ** outermost parser.
  68857. **
  68858. ** Not everything is nestable. This facility is designed to permit
  68859. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  68860. ** care if you decide to try to use this routine for some other purposes.
  68861. */
  68862. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  68863. va_list ap;
  68864. char *zSql;
  68865. char *zErrMsg = 0;
  68866. sqlite3 *db = pParse->db;
  68867. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  68868. char saveBuf[SAVE_SZ];
  68869. if( pParse->nErr ) return;
  68870. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  68871. va_start(ap, zFormat);
  68872. zSql = sqlite3VMPrintf(db, zFormat, ap);
  68873. va_end(ap);
  68874. if( zSql==0 ){
  68875. return; /* A malloc must have failed */
  68876. }
  68877. pParse->nested++;
  68878. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  68879. memset(&pParse->nVar, 0, SAVE_SZ);
  68880. sqlite3RunParser(pParse, zSql, &zErrMsg);
  68881. sqlite3DbFree(db, zErrMsg);
  68882. sqlite3DbFree(db, zSql);
  68883. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  68884. pParse->nested--;
  68885. }
  68886. /*
  68887. ** Locate the in-memory structure that describes a particular database
  68888. ** table given the name of that table and (optionally) the name of the
  68889. ** database containing the table. Return NULL if not found.
  68890. **
  68891. ** If zDatabase is 0, all databases are searched for the table and the
  68892. ** first matching table is returned. (No checking for duplicate table
  68893. ** names is done.) The search order is TEMP first, then MAIN, then any
  68894. ** auxiliary databases added using the ATTACH command.
  68895. **
  68896. ** See also sqlite3LocateTable().
  68897. */
  68898. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  68899. Table *p = 0;
  68900. int i;
  68901. int nName;
  68902. assert( zName!=0 );
  68903. nName = sqlite3Strlen30(zName);
  68904. /* All mutexes are required for schema access. Make sure we hold them. */
  68905. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  68906. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  68907. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  68908. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  68909. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  68910. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  68911. if( p ) break;
  68912. }
  68913. return p;
  68914. }
  68915. /*
  68916. ** Locate the in-memory structure that describes a particular database
  68917. ** table given the name of that table and (optionally) the name of the
  68918. ** database containing the table. Return NULL if not found. Also leave an
  68919. ** error message in pParse->zErrMsg.
  68920. **
  68921. ** The difference between this routine and sqlite3FindTable() is that this
  68922. ** routine leaves an error message in pParse->zErrMsg where
  68923. ** sqlite3FindTable() does not.
  68924. */
  68925. SQLITE_PRIVATE Table *sqlite3LocateTable(
  68926. Parse *pParse, /* context in which to report errors */
  68927. int isView, /* True if looking for a VIEW rather than a TABLE */
  68928. const char *zName, /* Name of the table we are looking for */
  68929. const char *zDbase /* Name of the database. Might be NULL */
  68930. ){
  68931. Table *p;
  68932. /* Read the database schema. If an error occurs, leave an error message
  68933. ** and code in pParse and return NULL. */
  68934. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  68935. return 0;
  68936. }
  68937. p = sqlite3FindTable(pParse->db, zName, zDbase);
  68938. if( p==0 ){
  68939. const char *zMsg = isView ? "no such view" : "no such table";
  68940. if( zDbase ){
  68941. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  68942. }else{
  68943. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  68944. }
  68945. pParse->checkSchema = 1;
  68946. }
  68947. return p;
  68948. }
  68949. /*
  68950. ** Locate the table identified by *p.
  68951. **
  68952. ** This is a wrapper around sqlite3LocateTable(). The difference between
  68953. ** sqlite3LocateTable() and this function is that this function restricts
  68954. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  68955. ** non-NULL if it is part of a view or trigger program definition. See
  68956. ** sqlite3FixSrcList() for details.
  68957. */
  68958. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  68959. Parse *pParse,
  68960. int isView,
  68961. struct SrcList_item *p
  68962. ){
  68963. const char *zDb;
  68964. assert( p->pSchema==0 || p->zDatabase==0 );
  68965. if( p->pSchema ){
  68966. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  68967. zDb = pParse->db->aDb[iDb].zName;
  68968. }else{
  68969. zDb = p->zDatabase;
  68970. }
  68971. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  68972. }
  68973. /*
  68974. ** Locate the in-memory structure that describes
  68975. ** a particular index given the name of that index
  68976. ** and the name of the database that contains the index.
  68977. ** Return NULL if not found.
  68978. **
  68979. ** If zDatabase is 0, all databases are searched for the
  68980. ** table and the first matching index is returned. (No checking
  68981. ** for duplicate index names is done.) The search order is
  68982. ** TEMP first, then MAIN, then any auxiliary databases added
  68983. ** using the ATTACH command.
  68984. */
  68985. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  68986. Index *p = 0;
  68987. int i;
  68988. int nName = sqlite3Strlen30(zName);
  68989. /* All mutexes are required for schema access. Make sure we hold them. */
  68990. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  68991. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  68992. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  68993. Schema *pSchema = db->aDb[j].pSchema;
  68994. assert( pSchema );
  68995. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  68996. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  68997. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  68998. if( p ) break;
  68999. }
  69000. return p;
  69001. }
  69002. /*
  69003. ** Reclaim the memory used by an index
  69004. */
  69005. static void freeIndex(sqlite3 *db, Index *p){
  69006. #ifndef SQLITE_OMIT_ANALYZE
  69007. sqlite3DeleteIndexSamples(db, p);
  69008. #endif
  69009. sqlite3ExprDelete(db, p->pPartIdxWhere);
  69010. sqlite3DbFree(db, p->zColAff);
  69011. sqlite3DbFree(db, p);
  69012. }
  69013. /*
  69014. ** For the index called zIdxName which is found in the database iDb,
  69015. ** unlike that index from its Table then remove the index from
  69016. ** the index hash table and free all memory structures associated
  69017. ** with the index.
  69018. */
  69019. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  69020. Index *pIndex;
  69021. int len;
  69022. Hash *pHash;
  69023. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69024. pHash = &db->aDb[iDb].pSchema->idxHash;
  69025. len = sqlite3Strlen30(zIdxName);
  69026. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  69027. if( ALWAYS(pIndex) ){
  69028. if( pIndex->pTable->pIndex==pIndex ){
  69029. pIndex->pTable->pIndex = pIndex->pNext;
  69030. }else{
  69031. Index *p;
  69032. /* Justification of ALWAYS(); The index must be on the list of
  69033. ** indices. */
  69034. p = pIndex->pTable->pIndex;
  69035. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  69036. if( ALWAYS(p && p->pNext==pIndex) ){
  69037. p->pNext = pIndex->pNext;
  69038. }
  69039. }
  69040. freeIndex(db, pIndex);
  69041. }
  69042. db->flags |= SQLITE_InternChanges;
  69043. }
  69044. /*
  69045. ** Look through the list of open database files in db->aDb[] and if
  69046. ** any have been closed, remove them from the list. Reallocate the
  69047. ** db->aDb[] structure to a smaller size, if possible.
  69048. **
  69049. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  69050. ** are never candidates for being collapsed.
  69051. */
  69052. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  69053. int i, j;
  69054. for(i=j=2; i<db->nDb; i++){
  69055. struct Db *pDb = &db->aDb[i];
  69056. if( pDb->pBt==0 ){
  69057. sqlite3DbFree(db, pDb->zName);
  69058. pDb->zName = 0;
  69059. continue;
  69060. }
  69061. if( j<i ){
  69062. db->aDb[j] = db->aDb[i];
  69063. }
  69064. j++;
  69065. }
  69066. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  69067. db->nDb = j;
  69068. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  69069. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  69070. sqlite3DbFree(db, db->aDb);
  69071. db->aDb = db->aDbStatic;
  69072. }
  69073. }
  69074. /*
  69075. ** Reset the schema for the database at index iDb. Also reset the
  69076. ** TEMP schema.
  69077. */
  69078. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  69079. Db *pDb;
  69080. assert( iDb<db->nDb );
  69081. /* Case 1: Reset the single schema identified by iDb */
  69082. pDb = &db->aDb[iDb];
  69083. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69084. assert( pDb->pSchema!=0 );
  69085. sqlite3SchemaClear(pDb->pSchema);
  69086. /* If any database other than TEMP is reset, then also reset TEMP
  69087. ** since TEMP might be holding triggers that reference tables in the
  69088. ** other database.
  69089. */
  69090. if( iDb!=1 ){
  69091. pDb = &db->aDb[1];
  69092. assert( pDb->pSchema!=0 );
  69093. sqlite3SchemaClear(pDb->pSchema);
  69094. }
  69095. return;
  69096. }
  69097. /*
  69098. ** Erase all schema information from all attached databases (including
  69099. ** "main" and "temp") for a single database connection.
  69100. */
  69101. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  69102. int i;
  69103. sqlite3BtreeEnterAll(db);
  69104. for(i=0; i<db->nDb; i++){
  69105. Db *pDb = &db->aDb[i];
  69106. if( pDb->pSchema ){
  69107. sqlite3SchemaClear(pDb->pSchema);
  69108. }
  69109. }
  69110. db->flags &= ~SQLITE_InternChanges;
  69111. sqlite3VtabUnlockList(db);
  69112. sqlite3BtreeLeaveAll(db);
  69113. sqlite3CollapseDatabaseArray(db);
  69114. }
  69115. /*
  69116. ** This routine is called when a commit occurs.
  69117. */
  69118. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  69119. db->flags &= ~SQLITE_InternChanges;
  69120. }
  69121. /*
  69122. ** Delete memory allocated for the column names of a table or view (the
  69123. ** Table.aCol[] array).
  69124. */
  69125. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  69126. int i;
  69127. Column *pCol;
  69128. assert( pTable!=0 );
  69129. if( (pCol = pTable->aCol)!=0 ){
  69130. for(i=0; i<pTable->nCol; i++, pCol++){
  69131. sqlite3DbFree(db, pCol->zName);
  69132. sqlite3ExprDelete(db, pCol->pDflt);
  69133. sqlite3DbFree(db, pCol->zDflt);
  69134. sqlite3DbFree(db, pCol->zType);
  69135. sqlite3DbFree(db, pCol->zColl);
  69136. }
  69137. sqlite3DbFree(db, pTable->aCol);
  69138. }
  69139. }
  69140. /*
  69141. ** Remove the memory data structures associated with the given
  69142. ** Table. No changes are made to disk by this routine.
  69143. **
  69144. ** This routine just deletes the data structure. It does not unlink
  69145. ** the table data structure from the hash table. But it does destroy
  69146. ** memory structures of the indices and foreign keys associated with
  69147. ** the table.
  69148. **
  69149. ** The db parameter is optional. It is needed if the Table object
  69150. ** contains lookaside memory. (Table objects in the schema do not use
  69151. ** lookaside memory, but some ephemeral Table objects do.) Or the
  69152. ** db parameter can be used with db->pnBytesFreed to measure the memory
  69153. ** used by the Table object.
  69154. */
  69155. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  69156. Index *pIndex, *pNext;
  69157. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  69158. assert( !pTable || pTable->nRef>0 );
  69159. /* Do not delete the table until the reference count reaches zero. */
  69160. if( !pTable ) return;
  69161. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  69162. /* Record the number of outstanding lookaside allocations in schema Tables
  69163. ** prior to doing any free() operations. Since schema Tables do not use
  69164. ** lookaside, this number should not change. */
  69165. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  69166. db->lookaside.nOut : 0 );
  69167. /* Delete all indices associated with this table. */
  69168. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  69169. pNext = pIndex->pNext;
  69170. assert( pIndex->pSchema==pTable->pSchema );
  69171. if( !db || db->pnBytesFreed==0 ){
  69172. char *zName = pIndex->zName;
  69173. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  69174. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  69175. );
  69176. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  69177. assert( pOld==pIndex || pOld==0 );
  69178. }
  69179. freeIndex(db, pIndex);
  69180. }
  69181. /* Delete any foreign keys attached to this table. */
  69182. sqlite3FkDelete(db, pTable);
  69183. /* Delete the Table structure itself.
  69184. */
  69185. sqliteDeleteColumnNames(db, pTable);
  69186. sqlite3DbFree(db, pTable->zName);
  69187. sqlite3DbFree(db, pTable->zColAff);
  69188. sqlite3SelectDelete(db, pTable->pSelect);
  69189. #ifndef SQLITE_OMIT_CHECK
  69190. sqlite3ExprListDelete(db, pTable->pCheck);
  69191. #endif
  69192. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69193. sqlite3VtabClear(db, pTable);
  69194. #endif
  69195. sqlite3DbFree(db, pTable);
  69196. /* Verify that no lookaside memory was used by schema tables */
  69197. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  69198. }
  69199. /*
  69200. ** Unlink the given table from the hash tables and the delete the
  69201. ** table structure with all its indices and foreign keys.
  69202. */
  69203. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  69204. Table *p;
  69205. Db *pDb;
  69206. assert( db!=0 );
  69207. assert( iDb>=0 && iDb<db->nDb );
  69208. assert( zTabName );
  69209. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69210. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  69211. pDb = &db->aDb[iDb];
  69212. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  69213. sqlite3Strlen30(zTabName),0);
  69214. sqlite3DeleteTable(db, p);
  69215. db->flags |= SQLITE_InternChanges;
  69216. }
  69217. /*
  69218. ** Given a token, return a string that consists of the text of that
  69219. ** token. Space to hold the returned string
  69220. ** is obtained from sqliteMalloc() and must be freed by the calling
  69221. ** function.
  69222. **
  69223. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  69224. ** surround the body of the token are removed.
  69225. **
  69226. ** Tokens are often just pointers into the original SQL text and so
  69227. ** are not \000 terminated and are not persistent. The returned string
  69228. ** is \000 terminated and is persistent.
  69229. */
  69230. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  69231. char *zName;
  69232. if( pName ){
  69233. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  69234. sqlite3Dequote(zName);
  69235. }else{
  69236. zName = 0;
  69237. }
  69238. return zName;
  69239. }
  69240. /*
  69241. ** Open the sqlite_master table stored in database number iDb for
  69242. ** writing. The table is opened using cursor 0.
  69243. */
  69244. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  69245. Vdbe *v = sqlite3GetVdbe(p);
  69246. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  69247. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  69248. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  69249. if( p->nTab==0 ){
  69250. p->nTab = 1;
  69251. }
  69252. }
  69253. /*
  69254. ** Parameter zName points to a nul-terminated buffer containing the name
  69255. ** of a database ("main", "temp" or the name of an attached db). This
  69256. ** function returns the index of the named database in db->aDb[], or
  69257. ** -1 if the named db cannot be found.
  69258. */
  69259. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  69260. int i = -1; /* Database number */
  69261. if( zName ){
  69262. Db *pDb;
  69263. int n = sqlite3Strlen30(zName);
  69264. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  69265. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  69266. 0==sqlite3StrICmp(pDb->zName, zName) ){
  69267. break;
  69268. }
  69269. }
  69270. }
  69271. return i;
  69272. }
  69273. /*
  69274. ** The token *pName contains the name of a database (either "main" or
  69275. ** "temp" or the name of an attached db). This routine returns the
  69276. ** index of the named database in db->aDb[], or -1 if the named db
  69277. ** does not exist.
  69278. */
  69279. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  69280. int i; /* Database number */
  69281. char *zName; /* Name we are searching for */
  69282. zName = sqlite3NameFromToken(db, pName);
  69283. i = sqlite3FindDbName(db, zName);
  69284. sqlite3DbFree(db, zName);
  69285. return i;
  69286. }
  69287. /* The table or view or trigger name is passed to this routine via tokens
  69288. ** pName1 and pName2. If the table name was fully qualified, for example:
  69289. **
  69290. ** CREATE TABLE xxx.yyy (...);
  69291. **
  69292. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  69293. ** the table name is not fully qualified, i.e.:
  69294. **
  69295. ** CREATE TABLE yyy(...);
  69296. **
  69297. ** Then pName1 is set to "yyy" and pName2 is "".
  69298. **
  69299. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  69300. ** pName2) that stores the unqualified table name. The index of the
  69301. ** database "xxx" is returned.
  69302. */
  69303. SQLITE_PRIVATE int sqlite3TwoPartName(
  69304. Parse *pParse, /* Parsing and code generating context */
  69305. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  69306. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  69307. Token **pUnqual /* Write the unqualified object name here */
  69308. ){
  69309. int iDb; /* Database holding the object */
  69310. sqlite3 *db = pParse->db;
  69311. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  69312. if( db->init.busy ) {
  69313. sqlite3ErrorMsg(pParse, "corrupt database");
  69314. pParse->nErr++;
  69315. return -1;
  69316. }
  69317. *pUnqual = pName2;
  69318. iDb = sqlite3FindDb(db, pName1);
  69319. if( iDb<0 ){
  69320. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  69321. pParse->nErr++;
  69322. return -1;
  69323. }
  69324. }else{
  69325. assert( db->init.iDb==0 || db->init.busy );
  69326. iDb = db->init.iDb;
  69327. *pUnqual = pName1;
  69328. }
  69329. return iDb;
  69330. }
  69331. /*
  69332. ** This routine is used to check if the UTF-8 string zName is a legal
  69333. ** unqualified name for a new schema object (table, index, view or
  69334. ** trigger). All names are legal except those that begin with the string
  69335. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  69336. ** is reserved for internal use.
  69337. */
  69338. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  69339. if( !pParse->db->init.busy && pParse->nested==0
  69340. && (pParse->db->flags & SQLITE_WriteSchema)==0
  69341. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  69342. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  69343. return SQLITE_ERROR;
  69344. }
  69345. return SQLITE_OK;
  69346. }
  69347. /*
  69348. ** Begin constructing a new table representation in memory. This is
  69349. ** the first of several action routines that get called in response
  69350. ** to a CREATE TABLE statement. In particular, this routine is called
  69351. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  69352. ** flag is true if the table should be stored in the auxiliary database
  69353. ** file instead of in the main database file. This is normally the case
  69354. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  69355. ** CREATE and TABLE.
  69356. **
  69357. ** The new table record is initialized and put in pParse->pNewTable.
  69358. ** As more of the CREATE TABLE statement is parsed, additional action
  69359. ** routines will be called to add more information to this record.
  69360. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  69361. ** is called to complete the construction of the new table record.
  69362. */
  69363. SQLITE_PRIVATE void sqlite3StartTable(
  69364. Parse *pParse, /* Parser context */
  69365. Token *pName1, /* First part of the name of the table or view */
  69366. Token *pName2, /* Second part of the name of the table or view */
  69367. int isTemp, /* True if this is a TEMP table */
  69368. int isView, /* True if this is a VIEW */
  69369. int isVirtual, /* True if this is a VIRTUAL table */
  69370. int noErr /* Do nothing if table already exists */
  69371. ){
  69372. Table *pTable;
  69373. char *zName = 0; /* The name of the new table */
  69374. sqlite3 *db = pParse->db;
  69375. Vdbe *v;
  69376. int iDb; /* Database number to create the table in */
  69377. Token *pName; /* Unqualified name of the table to create */
  69378. /* The table or view name to create is passed to this routine via tokens
  69379. ** pName1 and pName2. If the table name was fully qualified, for example:
  69380. **
  69381. ** CREATE TABLE xxx.yyy (...);
  69382. **
  69383. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  69384. ** the table name is not fully qualified, i.e.:
  69385. **
  69386. ** CREATE TABLE yyy(...);
  69387. **
  69388. ** Then pName1 is set to "yyy" and pName2 is "".
  69389. **
  69390. ** The call below sets the pName pointer to point at the token (pName1 or
  69391. ** pName2) that stores the unqualified table name. The variable iDb is
  69392. ** set to the index of the database that the table or view is to be
  69393. ** created in.
  69394. */
  69395. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  69396. if( iDb<0 ) return;
  69397. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  69398. /* If creating a temp table, the name may not be qualified. Unless
  69399. ** the database name is "temp" anyway. */
  69400. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  69401. return;
  69402. }
  69403. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  69404. pParse->sNameToken = *pName;
  69405. zName = sqlite3NameFromToken(db, pName);
  69406. if( zName==0 ) return;
  69407. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  69408. goto begin_table_error;
  69409. }
  69410. if( db->init.iDb==1 ) isTemp = 1;
  69411. #ifndef SQLITE_OMIT_AUTHORIZATION
  69412. assert( (isTemp & 1)==isTemp );
  69413. {
  69414. int code;
  69415. char *zDb = db->aDb[iDb].zName;
  69416. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  69417. goto begin_table_error;
  69418. }
  69419. if( isView ){
  69420. if( !OMIT_TEMPDB && isTemp ){
  69421. code = SQLITE_CREATE_TEMP_VIEW;
  69422. }else{
  69423. code = SQLITE_CREATE_VIEW;
  69424. }
  69425. }else{
  69426. if( !OMIT_TEMPDB && isTemp ){
  69427. code = SQLITE_CREATE_TEMP_TABLE;
  69428. }else{
  69429. code = SQLITE_CREATE_TABLE;
  69430. }
  69431. }
  69432. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  69433. goto begin_table_error;
  69434. }
  69435. }
  69436. #endif
  69437. /* Make sure the new table name does not collide with an existing
  69438. ** index or table name in the same database. Issue an error message if
  69439. ** it does. The exception is if the statement being parsed was passed
  69440. ** to an sqlite3_declare_vtab() call. In that case only the column names
  69441. ** and types will be used, so there is no need to test for namespace
  69442. ** collisions.
  69443. */
  69444. if( !IN_DECLARE_VTAB ){
  69445. char *zDb = db->aDb[iDb].zName;
  69446. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  69447. goto begin_table_error;
  69448. }
  69449. pTable = sqlite3FindTable(db, zName, zDb);
  69450. if( pTable ){
  69451. if( !noErr ){
  69452. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  69453. }else{
  69454. assert( !db->init.busy );
  69455. sqlite3CodeVerifySchema(pParse, iDb);
  69456. }
  69457. goto begin_table_error;
  69458. }
  69459. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  69460. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  69461. goto begin_table_error;
  69462. }
  69463. }
  69464. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  69465. if( pTable==0 ){
  69466. db->mallocFailed = 1;
  69467. pParse->rc = SQLITE_NOMEM;
  69468. pParse->nErr++;
  69469. goto begin_table_error;
  69470. }
  69471. pTable->zName = zName;
  69472. pTable->iPKey = -1;
  69473. pTable->pSchema = db->aDb[iDb].pSchema;
  69474. pTable->nRef = 1;
  69475. pTable->nRowEst = 1048576;
  69476. assert( pParse->pNewTable==0 );
  69477. pParse->pNewTable = pTable;
  69478. /* If this is the magic sqlite_sequence table used by autoincrement,
  69479. ** then record a pointer to this table in the main database structure
  69480. ** so that INSERT can find the table easily.
  69481. */
  69482. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69483. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  69484. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69485. pTable->pSchema->pSeqTab = pTable;
  69486. }
  69487. #endif
  69488. /* Begin generating the code that will insert the table record into
  69489. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  69490. ** and allocate the record number for the table entry now. Before any
  69491. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  69492. ** indices to be created and the table record must come before the
  69493. ** indices. Hence, the record number for the table must be allocated
  69494. ** now.
  69495. */
  69496. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  69497. int j1;
  69498. int fileFormat;
  69499. int reg1, reg2, reg3;
  69500. sqlite3BeginWriteOperation(pParse, 0, iDb);
  69501. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69502. if( isVirtual ){
  69503. sqlite3VdbeAddOp0(v, OP_VBegin);
  69504. }
  69505. #endif
  69506. /* If the file format and encoding in the database have not been set,
  69507. ** set them now.
  69508. */
  69509. reg1 = pParse->regRowid = ++pParse->nMem;
  69510. reg2 = pParse->regRoot = ++pParse->nMem;
  69511. reg3 = ++pParse->nMem;
  69512. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  69513. sqlite3VdbeUsesBtree(v, iDb);
  69514. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  69515. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  69516. 1 : SQLITE_MAX_FILE_FORMAT;
  69517. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  69518. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  69519. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  69520. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  69521. sqlite3VdbeJumpHere(v, j1);
  69522. /* This just creates a place-holder record in the sqlite_master table.
  69523. ** The record created does not contain anything yet. It will be replaced
  69524. ** by the real entry in code generated at sqlite3EndTable().
  69525. **
  69526. ** The rowid for the new entry is left in register pParse->regRowid.
  69527. ** The root page number of the new table is left in reg pParse->regRoot.
  69528. ** The rowid and root page number values are needed by the code that
  69529. ** sqlite3EndTable will generate.
  69530. */
  69531. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  69532. if( isView || isVirtual ){
  69533. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  69534. }else
  69535. #endif
  69536. {
  69537. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  69538. }
  69539. sqlite3OpenMasterTable(pParse, iDb);
  69540. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  69541. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  69542. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  69543. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  69544. sqlite3VdbeAddOp0(v, OP_Close);
  69545. }
  69546. /* Normal (non-error) return. */
  69547. return;
  69548. /* If an error occurs, we jump here */
  69549. begin_table_error:
  69550. sqlite3DbFree(db, zName);
  69551. return;
  69552. }
  69553. /*
  69554. ** This macro is used to compare two strings in a case-insensitive manner.
  69555. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  69556. ** produces larger code.
  69557. **
  69558. ** WARNING: This macro is not compatible with the strcmp() family. It
  69559. ** returns true if the two strings are equal, otherwise false.
  69560. */
  69561. #define STRICMP(x, y) (\
  69562. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  69563. sqlite3UpperToLower[*(unsigned char *)(y)] \
  69564. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  69565. /*
  69566. ** Add a new column to the table currently being constructed.
  69567. **
  69568. ** The parser calls this routine once for each column declaration
  69569. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  69570. ** first to get things going. Then this routine is called for each
  69571. ** column.
  69572. */
  69573. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  69574. Table *p;
  69575. int i;
  69576. char *z;
  69577. Column *pCol;
  69578. sqlite3 *db = pParse->db;
  69579. if( (p = pParse->pNewTable)==0 ) return;
  69580. #if SQLITE_MAX_COLUMN
  69581. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  69582. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  69583. return;
  69584. }
  69585. #endif
  69586. z = sqlite3NameFromToken(db, pName);
  69587. if( z==0 ) return;
  69588. for(i=0; i<p->nCol; i++){
  69589. if( STRICMP(z, p->aCol[i].zName) ){
  69590. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  69591. sqlite3DbFree(db, z);
  69592. return;
  69593. }
  69594. }
  69595. if( (p->nCol & 0x7)==0 ){
  69596. Column *aNew;
  69597. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  69598. if( aNew==0 ){
  69599. sqlite3DbFree(db, z);
  69600. return;
  69601. }
  69602. p->aCol = aNew;
  69603. }
  69604. pCol = &p->aCol[p->nCol];
  69605. memset(pCol, 0, sizeof(p->aCol[0]));
  69606. pCol->zName = z;
  69607. /* If there is no type specified, columns have the default affinity
  69608. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  69609. ** be called next to set pCol->affinity correctly.
  69610. */
  69611. pCol->affinity = SQLITE_AFF_NONE;
  69612. pCol->szEst = 1;
  69613. p->nCol++;
  69614. }
  69615. /*
  69616. ** This routine is called by the parser while in the middle of
  69617. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  69618. ** been seen on a column. This routine sets the notNull flag on
  69619. ** the column currently under construction.
  69620. */
  69621. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  69622. Table *p;
  69623. p = pParse->pNewTable;
  69624. if( p==0 || NEVER(p->nCol<1) ) return;
  69625. p->aCol[p->nCol-1].notNull = (u8)onError;
  69626. }
  69627. /*
  69628. ** Scan the column type name zType (length nType) and return the
  69629. ** associated affinity type.
  69630. **
  69631. ** This routine does a case-independent search of zType for the
  69632. ** substrings in the following table. If one of the substrings is
  69633. ** found, the corresponding affinity is returned. If zType contains
  69634. ** more than one of the substrings, entries toward the top of
  69635. ** the table take priority. For example, if zType is 'BLOBINT',
  69636. ** SQLITE_AFF_INTEGER is returned.
  69637. **
  69638. ** Substring | Affinity
  69639. ** --------------------------------
  69640. ** 'INT' | SQLITE_AFF_INTEGER
  69641. ** 'CHAR' | SQLITE_AFF_TEXT
  69642. ** 'CLOB' | SQLITE_AFF_TEXT
  69643. ** 'TEXT' | SQLITE_AFF_TEXT
  69644. ** 'BLOB' | SQLITE_AFF_NONE
  69645. ** 'REAL' | SQLITE_AFF_REAL
  69646. ** 'FLOA' | SQLITE_AFF_REAL
  69647. ** 'DOUB' | SQLITE_AFF_REAL
  69648. **
  69649. ** If none of the substrings in the above table are found,
  69650. ** SQLITE_AFF_NUMERIC is returned.
  69651. */
  69652. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  69653. u32 h = 0;
  69654. char aff = SQLITE_AFF_NUMERIC;
  69655. const char *zChar = 0;
  69656. if( zIn==0 ) return aff;
  69657. while( zIn[0] ){
  69658. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  69659. zIn++;
  69660. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  69661. aff = SQLITE_AFF_TEXT;
  69662. zChar = zIn;
  69663. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  69664. aff = SQLITE_AFF_TEXT;
  69665. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  69666. aff = SQLITE_AFF_TEXT;
  69667. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  69668. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  69669. aff = SQLITE_AFF_NONE;
  69670. if( zIn[0]=='(' ) zChar = zIn;
  69671. #ifndef SQLITE_OMIT_FLOATING_POINT
  69672. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  69673. && aff==SQLITE_AFF_NUMERIC ){
  69674. aff = SQLITE_AFF_REAL;
  69675. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  69676. && aff==SQLITE_AFF_NUMERIC ){
  69677. aff = SQLITE_AFF_REAL;
  69678. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  69679. && aff==SQLITE_AFF_NUMERIC ){
  69680. aff = SQLITE_AFF_REAL;
  69681. #endif
  69682. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  69683. aff = SQLITE_AFF_INTEGER;
  69684. break;
  69685. }
  69686. }
  69687. /* If pszEst is not NULL, store an estimate of the field size. The
  69688. ** estimate is scaled so that the size of an integer is 1. */
  69689. if( pszEst ){
  69690. *pszEst = 1; /* default size is approx 4 bytes */
  69691. if( aff<=SQLITE_AFF_NONE ){
  69692. if( zChar ){
  69693. while( zChar[0] ){
  69694. if( sqlite3Isdigit(zChar[0]) ){
  69695. int v = 0;
  69696. sqlite3GetInt32(zChar, &v);
  69697. v = v/4 + 1;
  69698. if( v>255 ) v = 255;
  69699. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  69700. break;
  69701. }
  69702. zChar++;
  69703. }
  69704. }else{
  69705. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  69706. }
  69707. }
  69708. }
  69709. return aff;
  69710. }
  69711. /*
  69712. ** This routine is called by the parser while in the middle of
  69713. ** parsing a CREATE TABLE statement. The pFirst token is the first
  69714. ** token in the sequence of tokens that describe the type of the
  69715. ** column currently under construction. pLast is the last token
  69716. ** in the sequence. Use this information to construct a string
  69717. ** that contains the typename of the column and store that string
  69718. ** in zType.
  69719. */
  69720. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  69721. Table *p;
  69722. Column *pCol;
  69723. p = pParse->pNewTable;
  69724. if( p==0 || NEVER(p->nCol<1) ) return;
  69725. pCol = &p->aCol[p->nCol-1];
  69726. assert( pCol->zType==0 );
  69727. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  69728. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  69729. }
  69730. /*
  69731. ** The expression is the default value for the most recently added column
  69732. ** of the table currently under construction.
  69733. **
  69734. ** Default value expressions must be constant. Raise an exception if this
  69735. ** is not the case.
  69736. **
  69737. ** This routine is called by the parser while in the middle of
  69738. ** parsing a CREATE TABLE statement.
  69739. */
  69740. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  69741. Table *p;
  69742. Column *pCol;
  69743. sqlite3 *db = pParse->db;
  69744. p = pParse->pNewTable;
  69745. if( p!=0 ){
  69746. pCol = &(p->aCol[p->nCol-1]);
  69747. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  69748. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  69749. pCol->zName);
  69750. }else{
  69751. /* A copy of pExpr is used instead of the original, as pExpr contains
  69752. ** tokens that point to volatile memory. The 'span' of the expression
  69753. ** is required by pragma table_info.
  69754. */
  69755. sqlite3ExprDelete(db, pCol->pDflt);
  69756. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  69757. sqlite3DbFree(db, pCol->zDflt);
  69758. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  69759. (int)(pSpan->zEnd - pSpan->zStart));
  69760. }
  69761. }
  69762. sqlite3ExprDelete(db, pSpan->pExpr);
  69763. }
  69764. /*
  69765. ** Designate the PRIMARY KEY for the table. pList is a list of names
  69766. ** of columns that form the primary key. If pList is NULL, then the
  69767. ** most recently added column of the table is the primary key.
  69768. **
  69769. ** A table can have at most one primary key. If the table already has
  69770. ** a primary key (and this is the second primary key) then create an
  69771. ** error.
  69772. **
  69773. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  69774. ** then we will try to use that column as the rowid. Set the Table.iPKey
  69775. ** field of the table under construction to be the index of the
  69776. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  69777. ** no INTEGER PRIMARY KEY.
  69778. **
  69779. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  69780. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  69781. */
  69782. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  69783. Parse *pParse, /* Parsing context */
  69784. ExprList *pList, /* List of field names to be indexed */
  69785. int onError, /* What to do with a uniqueness conflict */
  69786. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  69787. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  69788. ){
  69789. Table *pTab = pParse->pNewTable;
  69790. char *zType = 0;
  69791. int iCol = -1, i;
  69792. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  69793. if( pTab->tabFlags & TF_HasPrimaryKey ){
  69794. sqlite3ErrorMsg(pParse,
  69795. "table \"%s\" has more than one primary key", pTab->zName);
  69796. goto primary_key_exit;
  69797. }
  69798. pTab->tabFlags |= TF_HasPrimaryKey;
  69799. if( pList==0 ){
  69800. iCol = pTab->nCol - 1;
  69801. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  69802. }else{
  69803. for(i=0; i<pList->nExpr; i++){
  69804. for(iCol=0; iCol<pTab->nCol; iCol++){
  69805. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  69806. break;
  69807. }
  69808. }
  69809. if( iCol<pTab->nCol ){
  69810. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  69811. }
  69812. }
  69813. if( pList->nExpr>1 ) iCol = -1;
  69814. }
  69815. if( iCol>=0 && iCol<pTab->nCol ){
  69816. zType = pTab->aCol[iCol].zType;
  69817. }
  69818. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  69819. && sortOrder==SQLITE_SO_ASC ){
  69820. pTab->iPKey = iCol;
  69821. pTab->keyConf = (u8)onError;
  69822. assert( autoInc==0 || autoInc==1 );
  69823. pTab->tabFlags |= autoInc*TF_Autoincrement;
  69824. }else if( autoInc ){
  69825. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69826. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  69827. "INTEGER PRIMARY KEY");
  69828. #endif
  69829. }else{
  69830. Index *p;
  69831. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  69832. 0, sortOrder, 0);
  69833. if( p ){
  69834. p->autoIndex = 2;
  69835. }
  69836. pList = 0;
  69837. }
  69838. primary_key_exit:
  69839. sqlite3ExprListDelete(pParse->db, pList);
  69840. return;
  69841. }
  69842. /*
  69843. ** Add a new CHECK constraint to the table currently under construction.
  69844. */
  69845. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  69846. Parse *pParse, /* Parsing context */
  69847. Expr *pCheckExpr /* The check expression */
  69848. ){
  69849. #ifndef SQLITE_OMIT_CHECK
  69850. Table *pTab = pParse->pNewTable;
  69851. if( pTab && !IN_DECLARE_VTAB ){
  69852. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  69853. if( pParse->constraintName.n ){
  69854. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  69855. }
  69856. }else
  69857. #endif
  69858. {
  69859. sqlite3ExprDelete(pParse->db, pCheckExpr);
  69860. }
  69861. }
  69862. /*
  69863. ** Set the collation function of the most recently parsed table column
  69864. ** to the CollSeq given.
  69865. */
  69866. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  69867. Table *p;
  69868. int i;
  69869. char *zColl; /* Dequoted name of collation sequence */
  69870. sqlite3 *db;
  69871. if( (p = pParse->pNewTable)==0 ) return;
  69872. i = p->nCol-1;
  69873. db = pParse->db;
  69874. zColl = sqlite3NameFromToken(db, pToken);
  69875. if( !zColl ) return;
  69876. if( sqlite3LocateCollSeq(pParse, zColl) ){
  69877. Index *pIdx;
  69878. sqlite3DbFree(db, p->aCol[i].zColl);
  69879. p->aCol[i].zColl = zColl;
  69880. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  69881. ** then an index may have been created on this column before the
  69882. ** collation type was added. Correct this if it is the case.
  69883. */
  69884. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  69885. assert( pIdx->nColumn==1 );
  69886. if( pIdx->aiColumn[0]==i ){
  69887. pIdx->azColl[0] = p->aCol[i].zColl;
  69888. }
  69889. }
  69890. }else{
  69891. sqlite3DbFree(db, zColl);
  69892. }
  69893. }
  69894. /*
  69895. ** This function returns the collation sequence for database native text
  69896. ** encoding identified by the string zName, length nName.
  69897. **
  69898. ** If the requested collation sequence is not available, or not available
  69899. ** in the database native encoding, the collation factory is invoked to
  69900. ** request it. If the collation factory does not supply such a sequence,
  69901. ** and the sequence is available in another text encoding, then that is
  69902. ** returned instead.
  69903. **
  69904. ** If no versions of the requested collations sequence are available, or
  69905. ** another error occurs, NULL is returned and an error message written into
  69906. ** pParse.
  69907. **
  69908. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  69909. ** invokes the collation factory if the named collation cannot be found
  69910. ** and generates an error message.
  69911. **
  69912. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  69913. */
  69914. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  69915. sqlite3 *db = pParse->db;
  69916. u8 enc = ENC(db);
  69917. u8 initbusy = db->init.busy;
  69918. CollSeq *pColl;
  69919. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  69920. if( !initbusy && (!pColl || !pColl->xCmp) ){
  69921. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  69922. }
  69923. return pColl;
  69924. }
  69925. /*
  69926. ** Generate code that will increment the schema cookie.
  69927. **
  69928. ** The schema cookie is used to determine when the schema for the
  69929. ** database changes. After each schema change, the cookie value
  69930. ** changes. When a process first reads the schema it records the
  69931. ** cookie. Thereafter, whenever it goes to access the database,
  69932. ** it checks the cookie to make sure the schema has not changed
  69933. ** since it was last read.
  69934. **
  69935. ** This plan is not completely bullet-proof. It is possible for
  69936. ** the schema to change multiple times and for the cookie to be
  69937. ** set back to prior value. But schema changes are infrequent
  69938. ** and the probability of hitting the same cookie value is only
  69939. ** 1 chance in 2^32. So we're safe enough.
  69940. */
  69941. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  69942. int r1 = sqlite3GetTempReg(pParse);
  69943. sqlite3 *db = pParse->db;
  69944. Vdbe *v = pParse->pVdbe;
  69945. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69946. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  69947. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  69948. sqlite3ReleaseTempReg(pParse, r1);
  69949. }
  69950. /*
  69951. ** Measure the number of characters needed to output the given
  69952. ** identifier. The number returned includes any quotes used
  69953. ** but does not include the null terminator.
  69954. **
  69955. ** The estimate is conservative. It might be larger that what is
  69956. ** really needed.
  69957. */
  69958. static int identLength(const char *z){
  69959. int n;
  69960. for(n=0; *z; n++, z++){
  69961. if( *z=='"' ){ n++; }
  69962. }
  69963. return n + 2;
  69964. }
  69965. /*
  69966. ** The first parameter is a pointer to an output buffer. The second
  69967. ** parameter is a pointer to an integer that contains the offset at
  69968. ** which to write into the output buffer. This function copies the
  69969. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  69970. ** to the specified offset in the buffer and updates *pIdx to refer
  69971. ** to the first byte after the last byte written before returning.
  69972. **
  69973. ** If the string zSignedIdent consists entirely of alpha-numeric
  69974. ** characters, does not begin with a digit and is not an SQL keyword,
  69975. ** then it is copied to the output buffer exactly as it is. Otherwise,
  69976. ** it is quoted using double-quotes.
  69977. */
  69978. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  69979. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  69980. int i, j, needQuote;
  69981. i = *pIdx;
  69982. for(j=0; zIdent[j]; j++){
  69983. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  69984. }
  69985. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  69986. if( !needQuote ){
  69987. needQuote = zIdent[j];
  69988. }
  69989. if( needQuote ) z[i++] = '"';
  69990. for(j=0; zIdent[j]; j++){
  69991. z[i++] = zIdent[j];
  69992. if( zIdent[j]=='"' ) z[i++] = '"';
  69993. }
  69994. if( needQuote ) z[i++] = '"';
  69995. z[i] = 0;
  69996. *pIdx = i;
  69997. }
  69998. /*
  69999. ** Generate a CREATE TABLE statement appropriate for the given
  70000. ** table. Memory to hold the text of the statement is obtained
  70001. ** from sqliteMalloc() and must be freed by the calling function.
  70002. */
  70003. static char *createTableStmt(sqlite3 *db, Table *p){
  70004. int i, k, n;
  70005. char *zStmt;
  70006. char *zSep, *zSep2, *zEnd;
  70007. Column *pCol;
  70008. n = 0;
  70009. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  70010. n += identLength(pCol->zName) + 5;
  70011. }
  70012. n += identLength(p->zName);
  70013. if( n<50 ){
  70014. zSep = "";
  70015. zSep2 = ",";
  70016. zEnd = ")";
  70017. }else{
  70018. zSep = "\n ";
  70019. zSep2 = ",\n ";
  70020. zEnd = "\n)";
  70021. }
  70022. n += 35 + 6*p->nCol;
  70023. zStmt = sqlite3DbMallocRaw(0, n);
  70024. if( zStmt==0 ){
  70025. db->mallocFailed = 1;
  70026. return 0;
  70027. }
  70028. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  70029. k = sqlite3Strlen30(zStmt);
  70030. identPut(zStmt, &k, p->zName);
  70031. zStmt[k++] = '(';
  70032. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  70033. static const char * const azType[] = {
  70034. /* SQLITE_AFF_TEXT */ " TEXT",
  70035. /* SQLITE_AFF_NONE */ "",
  70036. /* SQLITE_AFF_NUMERIC */ " NUM",
  70037. /* SQLITE_AFF_INTEGER */ " INT",
  70038. /* SQLITE_AFF_REAL */ " REAL"
  70039. };
  70040. int len;
  70041. const char *zType;
  70042. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  70043. k += sqlite3Strlen30(&zStmt[k]);
  70044. zSep = zSep2;
  70045. identPut(zStmt, &k, pCol->zName);
  70046. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  70047. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  70048. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  70049. testcase( pCol->affinity==SQLITE_AFF_NONE );
  70050. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  70051. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  70052. testcase( pCol->affinity==SQLITE_AFF_REAL );
  70053. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  70054. len = sqlite3Strlen30(zType);
  70055. assert( pCol->affinity==SQLITE_AFF_NONE
  70056. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  70057. memcpy(&zStmt[k], zType, len);
  70058. k += len;
  70059. assert( k<=n );
  70060. }
  70061. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  70062. return zStmt;
  70063. }
  70064. /*
  70065. ** Estimate the total row width for a table.
  70066. */
  70067. static void estimateTableWidth(Table *pTab){
  70068. unsigned wTable = 0;
  70069. const Column *pTabCol;
  70070. int i;
  70071. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  70072. wTable += pTabCol->szEst;
  70073. }
  70074. if( pTab->iPKey<0 ) wTable++;
  70075. pTab->szTabRow = sqlite3LogEst(wTable*4);
  70076. }
  70077. /*
  70078. ** Estimate the average size of a row for an index.
  70079. */
  70080. static void estimateIndexWidth(Index *pIdx){
  70081. unsigned wIndex = 1;
  70082. int i;
  70083. const Column *aCol = pIdx->pTable->aCol;
  70084. for(i=0; i<pIdx->nColumn; i++){
  70085. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  70086. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  70087. }
  70088. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  70089. }
  70090. /*
  70091. ** This routine is called to report the final ")" that terminates
  70092. ** a CREATE TABLE statement.
  70093. **
  70094. ** The table structure that other action routines have been building
  70095. ** is added to the internal hash tables, assuming no errors have
  70096. ** occurred.
  70097. **
  70098. ** An entry for the table is made in the master table on disk, unless
  70099. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  70100. ** it means we are reading the sqlite_master table because we just
  70101. ** connected to the database or because the sqlite_master table has
  70102. ** recently changed, so the entry for this table already exists in
  70103. ** the sqlite_master table. We do not want to create it again.
  70104. **
  70105. ** If the pSelect argument is not NULL, it means that this routine
  70106. ** was called to create a table generated from a
  70107. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  70108. ** the new table will match the result set of the SELECT.
  70109. */
  70110. SQLITE_PRIVATE void sqlite3EndTable(
  70111. Parse *pParse, /* Parse context */
  70112. Token *pCons, /* The ',' token after the last column defn. */
  70113. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  70114. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  70115. ){
  70116. Table *p; /* The new table */
  70117. sqlite3 *db = pParse->db; /* The database connection */
  70118. int iDb; /* Database in which the table lives */
  70119. Index *pIdx; /* An implied index of the table */
  70120. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  70121. return;
  70122. }
  70123. p = pParse->pNewTable;
  70124. if( p==0 ) return;
  70125. assert( !db->init.busy || !pSelect );
  70126. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  70127. #ifndef SQLITE_OMIT_CHECK
  70128. /* Resolve names in all CHECK constraint expressions.
  70129. */
  70130. if( p->pCheck ){
  70131. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  70132. }
  70133. #endif /* !defined(SQLITE_OMIT_CHECK) */
  70134. /* Estimate the average row size for the table and for all implied indices */
  70135. estimateTableWidth(p);
  70136. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  70137. estimateIndexWidth(pIdx);
  70138. }
  70139. /* If the db->init.busy is 1 it means we are reading the SQL off the
  70140. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  70141. ** So do not write to the disk again. Extract the root page number
  70142. ** for the table from the db->init.newTnum field. (The page number
  70143. ** should have been put there by the sqliteOpenCb routine.)
  70144. */
  70145. if( db->init.busy ){
  70146. p->tnum = db->init.newTnum;
  70147. }
  70148. /* If not initializing, then create a record for the new table
  70149. ** in the SQLITE_MASTER table of the database.
  70150. **
  70151. ** If this is a TEMPORARY table, write the entry into the auxiliary
  70152. ** file instead of into the main database file.
  70153. */
  70154. if( !db->init.busy ){
  70155. int n;
  70156. Vdbe *v;
  70157. char *zType; /* "view" or "table" */
  70158. char *zType2; /* "VIEW" or "TABLE" */
  70159. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  70160. v = sqlite3GetVdbe(pParse);
  70161. if( NEVER(v==0) ) return;
  70162. sqlite3VdbeAddOp1(v, OP_Close, 0);
  70163. /*
  70164. ** Initialize zType for the new view or table.
  70165. */
  70166. if( p->pSelect==0 ){
  70167. /* A regular table */
  70168. zType = "table";
  70169. zType2 = "TABLE";
  70170. #ifndef SQLITE_OMIT_VIEW
  70171. }else{
  70172. /* A view */
  70173. zType = "view";
  70174. zType2 = "VIEW";
  70175. #endif
  70176. }
  70177. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  70178. ** statement to populate the new table. The root-page number for the
  70179. ** new table is in register pParse->regRoot.
  70180. **
  70181. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  70182. ** suitable state to query for the column names and types to be used
  70183. ** by the new table.
  70184. **
  70185. ** A shared-cache write-lock is not required to write to the new table,
  70186. ** as a schema-lock must have already been obtained to create it. Since
  70187. ** a schema-lock excludes all other database users, the write-lock would
  70188. ** be redundant.
  70189. */
  70190. if( pSelect ){
  70191. SelectDest dest;
  70192. Table *pSelTab;
  70193. assert(pParse->nTab==1);
  70194. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  70195. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  70196. pParse->nTab = 2;
  70197. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  70198. sqlite3Select(pParse, pSelect, &dest);
  70199. sqlite3VdbeAddOp1(v, OP_Close, 1);
  70200. if( pParse->nErr==0 ){
  70201. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  70202. if( pSelTab==0 ) return;
  70203. assert( p->aCol==0 );
  70204. p->nCol = pSelTab->nCol;
  70205. p->aCol = pSelTab->aCol;
  70206. pSelTab->nCol = 0;
  70207. pSelTab->aCol = 0;
  70208. sqlite3DeleteTable(db, pSelTab);
  70209. }
  70210. }
  70211. /* Compute the complete text of the CREATE statement */
  70212. if( pSelect ){
  70213. zStmt = createTableStmt(db, p);
  70214. }else{
  70215. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  70216. zStmt = sqlite3MPrintf(db,
  70217. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  70218. );
  70219. }
  70220. /* A slot for the record has already been allocated in the
  70221. ** SQLITE_MASTER table. We just need to update that slot with all
  70222. ** the information we've collected.
  70223. */
  70224. sqlite3NestedParse(pParse,
  70225. "UPDATE %Q.%s "
  70226. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  70227. "WHERE rowid=#%d",
  70228. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  70229. zType,
  70230. p->zName,
  70231. p->zName,
  70232. pParse->regRoot,
  70233. zStmt,
  70234. pParse->regRowid
  70235. );
  70236. sqlite3DbFree(db, zStmt);
  70237. sqlite3ChangeCookie(pParse, iDb);
  70238. #ifndef SQLITE_OMIT_AUTOINCREMENT
  70239. /* Check to see if we need to create an sqlite_sequence table for
  70240. ** keeping track of autoincrement keys.
  70241. */
  70242. if( p->tabFlags & TF_Autoincrement ){
  70243. Db *pDb = &db->aDb[iDb];
  70244. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70245. if( pDb->pSchema->pSeqTab==0 ){
  70246. sqlite3NestedParse(pParse,
  70247. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  70248. pDb->zName
  70249. );
  70250. }
  70251. }
  70252. #endif
  70253. /* Reparse everything to update our internal data structures */
  70254. sqlite3VdbeAddParseSchemaOp(v, iDb,
  70255. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  70256. }
  70257. /* Add the table to the in-memory representation of the database.
  70258. */
  70259. if( db->init.busy ){
  70260. Table *pOld;
  70261. Schema *pSchema = p->pSchema;
  70262. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70263. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  70264. sqlite3Strlen30(p->zName),p);
  70265. if( pOld ){
  70266. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  70267. db->mallocFailed = 1;
  70268. return;
  70269. }
  70270. pParse->pNewTable = 0;
  70271. db->flags |= SQLITE_InternChanges;
  70272. #ifndef SQLITE_OMIT_ALTERTABLE
  70273. if( !p->pSelect ){
  70274. const char *zName = (const char *)pParse->sNameToken.z;
  70275. int nName;
  70276. assert( !pSelect && pCons && pEnd );
  70277. if( pCons->z==0 ){
  70278. pCons = pEnd;
  70279. }
  70280. nName = (int)((const char *)pCons->z - zName);
  70281. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  70282. }
  70283. #endif
  70284. }
  70285. }
  70286. #ifndef SQLITE_OMIT_VIEW
  70287. /*
  70288. ** The parser calls this routine in order to create a new VIEW
  70289. */
  70290. SQLITE_PRIVATE void sqlite3CreateView(
  70291. Parse *pParse, /* The parsing context */
  70292. Token *pBegin, /* The CREATE token that begins the statement */
  70293. Token *pName1, /* The token that holds the name of the view */
  70294. Token *pName2, /* The token that holds the name of the view */
  70295. Select *pSelect, /* A SELECT statement that will become the new view */
  70296. int isTemp, /* TRUE for a TEMPORARY view */
  70297. int noErr /* Suppress error messages if VIEW already exists */
  70298. ){
  70299. Table *p;
  70300. int n;
  70301. const char *z;
  70302. Token sEnd;
  70303. DbFixer sFix;
  70304. Token *pName = 0;
  70305. int iDb;
  70306. sqlite3 *db = pParse->db;
  70307. if( pParse->nVar>0 ){
  70308. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  70309. sqlite3SelectDelete(db, pSelect);
  70310. return;
  70311. }
  70312. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  70313. p = pParse->pNewTable;
  70314. if( p==0 || pParse->nErr ){
  70315. sqlite3SelectDelete(db, pSelect);
  70316. return;
  70317. }
  70318. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  70319. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  70320. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  70321. if( sqlite3FixSelect(&sFix, pSelect) ){
  70322. sqlite3SelectDelete(db, pSelect);
  70323. return;
  70324. }
  70325. /* Make a copy of the entire SELECT statement that defines the view.
  70326. ** This will force all the Expr.token.z values to be dynamically
  70327. ** allocated rather than point to the input string - which means that
  70328. ** they will persist after the current sqlite3_exec() call returns.
  70329. */
  70330. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  70331. sqlite3SelectDelete(db, pSelect);
  70332. if( db->mallocFailed ){
  70333. return;
  70334. }
  70335. if( !db->init.busy ){
  70336. sqlite3ViewGetColumnNames(pParse, p);
  70337. }
  70338. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  70339. ** the end.
  70340. */
  70341. sEnd = pParse->sLastToken;
  70342. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  70343. sEnd.z += sEnd.n;
  70344. }
  70345. sEnd.n = 0;
  70346. n = (int)(sEnd.z - pBegin->z);
  70347. z = pBegin->z;
  70348. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  70349. sEnd.z = &z[n-1];
  70350. sEnd.n = 1;
  70351. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  70352. sqlite3EndTable(pParse, 0, &sEnd, 0);
  70353. return;
  70354. }
  70355. #endif /* SQLITE_OMIT_VIEW */
  70356. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  70357. /*
  70358. ** The Table structure pTable is really a VIEW. Fill in the names of
  70359. ** the columns of the view in the pTable structure. Return the number
  70360. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  70361. */
  70362. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  70363. Table *pSelTab; /* A fake table from which we get the result set */
  70364. Select *pSel; /* Copy of the SELECT that implements the view */
  70365. int nErr = 0; /* Number of errors encountered */
  70366. int n; /* Temporarily holds the number of cursors assigned */
  70367. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  70368. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  70369. assert( pTable );
  70370. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70371. if( sqlite3VtabCallConnect(pParse, pTable) ){
  70372. return SQLITE_ERROR;
  70373. }
  70374. if( IsVirtual(pTable) ) return 0;
  70375. #endif
  70376. #ifndef SQLITE_OMIT_VIEW
  70377. /* A positive nCol means the columns names for this view are
  70378. ** already known.
  70379. */
  70380. if( pTable->nCol>0 ) return 0;
  70381. /* A negative nCol is a special marker meaning that we are currently
  70382. ** trying to compute the column names. If we enter this routine with
  70383. ** a negative nCol, it means two or more views form a loop, like this:
  70384. **
  70385. ** CREATE VIEW one AS SELECT * FROM two;
  70386. ** CREATE VIEW two AS SELECT * FROM one;
  70387. **
  70388. ** Actually, the error above is now caught prior to reaching this point.
  70389. ** But the following test is still important as it does come up
  70390. ** in the following:
  70391. **
  70392. ** CREATE TABLE main.ex1(a);
  70393. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  70394. ** SELECT * FROM temp.ex1;
  70395. */
  70396. if( pTable->nCol<0 ){
  70397. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  70398. return 1;
  70399. }
  70400. assert( pTable->nCol>=0 );
  70401. /* If we get this far, it means we need to compute the table names.
  70402. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  70403. ** "*" elements in the results set of the view and will assign cursors
  70404. ** to the elements of the FROM clause. But we do not want these changes
  70405. ** to be permanent. So the computation is done on a copy of the SELECT
  70406. ** statement that defines the view.
  70407. */
  70408. assert( pTable->pSelect );
  70409. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  70410. if( pSel ){
  70411. u8 enableLookaside = db->lookaside.bEnabled;
  70412. n = pParse->nTab;
  70413. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  70414. pTable->nCol = -1;
  70415. db->lookaside.bEnabled = 0;
  70416. #ifndef SQLITE_OMIT_AUTHORIZATION
  70417. xAuth = db->xAuth;
  70418. db->xAuth = 0;
  70419. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  70420. db->xAuth = xAuth;
  70421. #else
  70422. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  70423. #endif
  70424. db->lookaside.bEnabled = enableLookaside;
  70425. pParse->nTab = n;
  70426. if( pSelTab ){
  70427. assert( pTable->aCol==0 );
  70428. pTable->nCol = pSelTab->nCol;
  70429. pTable->aCol = pSelTab->aCol;
  70430. pSelTab->nCol = 0;
  70431. pSelTab->aCol = 0;
  70432. sqlite3DeleteTable(db, pSelTab);
  70433. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  70434. pTable->pSchema->flags |= DB_UnresetViews;
  70435. }else{
  70436. pTable->nCol = 0;
  70437. nErr++;
  70438. }
  70439. sqlite3SelectDelete(db, pSel);
  70440. } else {
  70441. nErr++;
  70442. }
  70443. #endif /* SQLITE_OMIT_VIEW */
  70444. return nErr;
  70445. }
  70446. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  70447. #ifndef SQLITE_OMIT_VIEW
  70448. /*
  70449. ** Clear the column names from every VIEW in database idx.
  70450. */
  70451. static void sqliteViewResetAll(sqlite3 *db, int idx){
  70452. HashElem *i;
  70453. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  70454. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  70455. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  70456. Table *pTab = sqliteHashData(i);
  70457. if( pTab->pSelect ){
  70458. sqliteDeleteColumnNames(db, pTab);
  70459. pTab->aCol = 0;
  70460. pTab->nCol = 0;
  70461. }
  70462. }
  70463. DbClearProperty(db, idx, DB_UnresetViews);
  70464. }
  70465. #else
  70466. # define sqliteViewResetAll(A,B)
  70467. #endif /* SQLITE_OMIT_VIEW */
  70468. /*
  70469. ** This function is called by the VDBE to adjust the internal schema
  70470. ** used by SQLite when the btree layer moves a table root page. The
  70471. ** root-page of a table or index in database iDb has changed from iFrom
  70472. ** to iTo.
  70473. **
  70474. ** Ticket #1728: The symbol table might still contain information
  70475. ** on tables and/or indices that are the process of being deleted.
  70476. ** If you are unlucky, one of those deleted indices or tables might
  70477. ** have the same rootpage number as the real table or index that is
  70478. ** being moved. So we cannot stop searching after the first match
  70479. ** because the first match might be for one of the deleted indices
  70480. ** or tables and not the table/index that is actually being moved.
  70481. ** We must continue looping until all tables and indices with
  70482. ** rootpage==iFrom have been converted to have a rootpage of iTo
  70483. ** in order to be certain that we got the right one.
  70484. */
  70485. #ifndef SQLITE_OMIT_AUTOVACUUM
  70486. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  70487. HashElem *pElem;
  70488. Hash *pHash;
  70489. Db *pDb;
  70490. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70491. pDb = &db->aDb[iDb];
  70492. pHash = &pDb->pSchema->tblHash;
  70493. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  70494. Table *pTab = sqliteHashData(pElem);
  70495. if( pTab->tnum==iFrom ){
  70496. pTab->tnum = iTo;
  70497. }
  70498. }
  70499. pHash = &pDb->pSchema->idxHash;
  70500. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  70501. Index *pIdx = sqliteHashData(pElem);
  70502. if( pIdx->tnum==iFrom ){
  70503. pIdx->tnum = iTo;
  70504. }
  70505. }
  70506. }
  70507. #endif
  70508. /*
  70509. ** Write code to erase the table with root-page iTable from database iDb.
  70510. ** Also write code to modify the sqlite_master table and internal schema
  70511. ** if a root-page of another table is moved by the btree-layer whilst
  70512. ** erasing iTable (this can happen with an auto-vacuum database).
  70513. */
  70514. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  70515. Vdbe *v = sqlite3GetVdbe(pParse);
  70516. int r1 = sqlite3GetTempReg(pParse);
  70517. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  70518. sqlite3MayAbort(pParse);
  70519. #ifndef SQLITE_OMIT_AUTOVACUUM
  70520. /* OP_Destroy stores an in integer r1. If this integer
  70521. ** is non-zero, then it is the root page number of a table moved to
  70522. ** location iTable. The following code modifies the sqlite_master table to
  70523. ** reflect this.
  70524. **
  70525. ** The "#NNN" in the SQL is a special constant that means whatever value
  70526. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  70527. ** token for additional information.
  70528. */
  70529. sqlite3NestedParse(pParse,
  70530. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  70531. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  70532. #endif
  70533. sqlite3ReleaseTempReg(pParse, r1);
  70534. }
  70535. /*
  70536. ** Write VDBE code to erase table pTab and all associated indices on disk.
  70537. ** Code to update the sqlite_master tables and internal schema definitions
  70538. ** in case a root-page belonging to another table is moved by the btree layer
  70539. ** is also added (this can happen with an auto-vacuum database).
  70540. */
  70541. static void destroyTable(Parse *pParse, Table *pTab){
  70542. #ifdef SQLITE_OMIT_AUTOVACUUM
  70543. Index *pIdx;
  70544. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  70545. destroyRootPage(pParse, pTab->tnum, iDb);
  70546. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70547. destroyRootPage(pParse, pIdx->tnum, iDb);
  70548. }
  70549. #else
  70550. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  70551. ** is not defined), then it is important to call OP_Destroy on the
  70552. ** table and index root-pages in order, starting with the numerically
  70553. ** largest root-page number. This guarantees that none of the root-pages
  70554. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  70555. ** following were coded:
  70556. **
  70557. ** OP_Destroy 4 0
  70558. ** ...
  70559. ** OP_Destroy 5 0
  70560. **
  70561. ** and root page 5 happened to be the largest root-page number in the
  70562. ** database, then root page 5 would be moved to page 4 by the
  70563. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  70564. ** a free-list page.
  70565. */
  70566. int iTab = pTab->tnum;
  70567. int iDestroyed = 0;
  70568. while( 1 ){
  70569. Index *pIdx;
  70570. int iLargest = 0;
  70571. if( iDestroyed==0 || iTab<iDestroyed ){
  70572. iLargest = iTab;
  70573. }
  70574. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70575. int iIdx = pIdx->tnum;
  70576. assert( pIdx->pSchema==pTab->pSchema );
  70577. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  70578. iLargest = iIdx;
  70579. }
  70580. }
  70581. if( iLargest==0 ){
  70582. return;
  70583. }else{
  70584. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  70585. assert( iDb>=0 && iDb<pParse->db->nDb );
  70586. destroyRootPage(pParse, iLargest, iDb);
  70587. iDestroyed = iLargest;
  70588. }
  70589. }
  70590. #endif
  70591. }
  70592. /*
  70593. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  70594. ** after a DROP INDEX or DROP TABLE command.
  70595. */
  70596. static void sqlite3ClearStatTables(
  70597. Parse *pParse, /* The parsing context */
  70598. int iDb, /* The database number */
  70599. const char *zType, /* "idx" or "tbl" */
  70600. const char *zName /* Name of index or table */
  70601. ){
  70602. int i;
  70603. const char *zDbName = pParse->db->aDb[iDb].zName;
  70604. for(i=1; i<=4; i++){
  70605. char zTab[24];
  70606. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  70607. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  70608. sqlite3NestedParse(pParse,
  70609. "DELETE FROM %Q.%s WHERE %s=%Q",
  70610. zDbName, zTab, zType, zName
  70611. );
  70612. }
  70613. }
  70614. }
  70615. /*
  70616. ** Generate code to drop a table.
  70617. */
  70618. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  70619. Vdbe *v;
  70620. sqlite3 *db = pParse->db;
  70621. Trigger *pTrigger;
  70622. Db *pDb = &db->aDb[iDb];
  70623. v = sqlite3GetVdbe(pParse);
  70624. assert( v!=0 );
  70625. sqlite3BeginWriteOperation(pParse, 1, iDb);
  70626. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70627. if( IsVirtual(pTab) ){
  70628. sqlite3VdbeAddOp0(v, OP_VBegin);
  70629. }
  70630. #endif
  70631. /* Drop all triggers associated with the table being dropped. Code
  70632. ** is generated to remove entries from sqlite_master and/or
  70633. ** sqlite_temp_master if required.
  70634. */
  70635. pTrigger = sqlite3TriggerList(pParse, pTab);
  70636. while( pTrigger ){
  70637. assert( pTrigger->pSchema==pTab->pSchema ||
  70638. pTrigger->pSchema==db->aDb[1].pSchema );
  70639. sqlite3DropTriggerPtr(pParse, pTrigger);
  70640. pTrigger = pTrigger->pNext;
  70641. }
  70642. #ifndef SQLITE_OMIT_AUTOINCREMENT
  70643. /* Remove any entries of the sqlite_sequence table associated with
  70644. ** the table being dropped. This is done before the table is dropped
  70645. ** at the btree level, in case the sqlite_sequence table needs to
  70646. ** move as a result of the drop (can happen in auto-vacuum mode).
  70647. */
  70648. if( pTab->tabFlags & TF_Autoincrement ){
  70649. sqlite3NestedParse(pParse,
  70650. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  70651. pDb->zName, pTab->zName
  70652. );
  70653. }
  70654. #endif
  70655. /* Drop all SQLITE_MASTER table and index entries that refer to the
  70656. ** table. The program name loops through the master table and deletes
  70657. ** every row that refers to a table of the same name as the one being
  70658. ** dropped. Triggers are handled separately because a trigger can be
  70659. ** created in the temp database that refers to a table in another
  70660. ** database.
  70661. */
  70662. sqlite3NestedParse(pParse,
  70663. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  70664. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  70665. if( !isView && !IsVirtual(pTab) ){
  70666. destroyTable(pParse, pTab);
  70667. }
  70668. /* Remove the table entry from SQLite's internal schema and modify
  70669. ** the schema cookie.
  70670. */
  70671. if( IsVirtual(pTab) ){
  70672. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  70673. }
  70674. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  70675. sqlite3ChangeCookie(pParse, iDb);
  70676. sqliteViewResetAll(db, iDb);
  70677. }
  70678. /*
  70679. ** This routine is called to do the work of a DROP TABLE statement.
  70680. ** pName is the name of the table to be dropped.
  70681. */
  70682. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  70683. Table *pTab;
  70684. Vdbe *v;
  70685. sqlite3 *db = pParse->db;
  70686. int iDb;
  70687. if( db->mallocFailed ){
  70688. goto exit_drop_table;
  70689. }
  70690. assert( pParse->nErr==0 );
  70691. assert( pName->nSrc==1 );
  70692. if( noErr ) db->suppressErr++;
  70693. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  70694. if( noErr ) db->suppressErr--;
  70695. if( pTab==0 ){
  70696. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  70697. goto exit_drop_table;
  70698. }
  70699. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70700. assert( iDb>=0 && iDb<db->nDb );
  70701. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  70702. ** it is initialized.
  70703. */
  70704. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  70705. goto exit_drop_table;
  70706. }
  70707. #ifndef SQLITE_OMIT_AUTHORIZATION
  70708. {
  70709. int code;
  70710. const char *zTab = SCHEMA_TABLE(iDb);
  70711. const char *zDb = db->aDb[iDb].zName;
  70712. const char *zArg2 = 0;
  70713. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  70714. goto exit_drop_table;
  70715. }
  70716. if( isView ){
  70717. if( !OMIT_TEMPDB && iDb==1 ){
  70718. code = SQLITE_DROP_TEMP_VIEW;
  70719. }else{
  70720. code = SQLITE_DROP_VIEW;
  70721. }
  70722. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70723. }else if( IsVirtual(pTab) ){
  70724. code = SQLITE_DROP_VTABLE;
  70725. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  70726. #endif
  70727. }else{
  70728. if( !OMIT_TEMPDB && iDb==1 ){
  70729. code = SQLITE_DROP_TEMP_TABLE;
  70730. }else{
  70731. code = SQLITE_DROP_TABLE;
  70732. }
  70733. }
  70734. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  70735. goto exit_drop_table;
  70736. }
  70737. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  70738. goto exit_drop_table;
  70739. }
  70740. }
  70741. #endif
  70742. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  70743. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  70744. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  70745. goto exit_drop_table;
  70746. }
  70747. #ifndef SQLITE_OMIT_VIEW
  70748. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  70749. ** on a table.
  70750. */
  70751. if( isView && pTab->pSelect==0 ){
  70752. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  70753. goto exit_drop_table;
  70754. }
  70755. if( !isView && pTab->pSelect ){
  70756. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  70757. goto exit_drop_table;
  70758. }
  70759. #endif
  70760. /* Generate code to remove the table from the master table
  70761. ** on disk.
  70762. */
  70763. v = sqlite3GetVdbe(pParse);
  70764. if( v ){
  70765. sqlite3BeginWriteOperation(pParse, 1, iDb);
  70766. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  70767. sqlite3FkDropTable(pParse, pName, pTab);
  70768. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  70769. }
  70770. exit_drop_table:
  70771. sqlite3SrcListDelete(db, pName);
  70772. }
  70773. /*
  70774. ** This routine is called to create a new foreign key on the table
  70775. ** currently under construction. pFromCol determines which columns
  70776. ** in the current table point to the foreign key. If pFromCol==0 then
  70777. ** connect the key to the last column inserted. pTo is the name of
  70778. ** the table referred to. pToCol is a list of tables in the other
  70779. ** pTo table that the foreign key points to. flags contains all
  70780. ** information about the conflict resolution algorithms specified
  70781. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  70782. **
  70783. ** An FKey structure is created and added to the table currently
  70784. ** under construction in the pParse->pNewTable field.
  70785. **
  70786. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  70787. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  70788. */
  70789. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  70790. Parse *pParse, /* Parsing context */
  70791. ExprList *pFromCol, /* Columns in this table that point to other table */
  70792. Token *pTo, /* Name of the other table */
  70793. ExprList *pToCol, /* Columns in the other table */
  70794. int flags /* Conflict resolution algorithms. */
  70795. ){
  70796. sqlite3 *db = pParse->db;
  70797. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70798. FKey *pFKey = 0;
  70799. FKey *pNextTo;
  70800. Table *p = pParse->pNewTable;
  70801. int nByte;
  70802. int i;
  70803. int nCol;
  70804. char *z;
  70805. assert( pTo!=0 );
  70806. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  70807. if( pFromCol==0 ){
  70808. int iCol = p->nCol-1;
  70809. if( NEVER(iCol<0) ) goto fk_end;
  70810. if( pToCol && pToCol->nExpr!=1 ){
  70811. sqlite3ErrorMsg(pParse, "foreign key on %s"
  70812. " should reference only one column of table %T",
  70813. p->aCol[iCol].zName, pTo);
  70814. goto fk_end;
  70815. }
  70816. nCol = 1;
  70817. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  70818. sqlite3ErrorMsg(pParse,
  70819. "number of columns in foreign key does not match the number of "
  70820. "columns in the referenced table");
  70821. goto fk_end;
  70822. }else{
  70823. nCol = pFromCol->nExpr;
  70824. }
  70825. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  70826. if( pToCol ){
  70827. for(i=0; i<pToCol->nExpr; i++){
  70828. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  70829. }
  70830. }
  70831. pFKey = sqlite3DbMallocZero(db, nByte );
  70832. if( pFKey==0 ){
  70833. goto fk_end;
  70834. }
  70835. pFKey->pFrom = p;
  70836. pFKey->pNextFrom = p->pFKey;
  70837. z = (char*)&pFKey->aCol[nCol];
  70838. pFKey->zTo = z;
  70839. memcpy(z, pTo->z, pTo->n);
  70840. z[pTo->n] = 0;
  70841. sqlite3Dequote(z);
  70842. z += pTo->n+1;
  70843. pFKey->nCol = nCol;
  70844. if( pFromCol==0 ){
  70845. pFKey->aCol[0].iFrom = p->nCol-1;
  70846. }else{
  70847. for(i=0; i<nCol; i++){
  70848. int j;
  70849. for(j=0; j<p->nCol; j++){
  70850. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  70851. pFKey->aCol[i].iFrom = j;
  70852. break;
  70853. }
  70854. }
  70855. if( j>=p->nCol ){
  70856. sqlite3ErrorMsg(pParse,
  70857. "unknown column \"%s\" in foreign key definition",
  70858. pFromCol->a[i].zName);
  70859. goto fk_end;
  70860. }
  70861. }
  70862. }
  70863. if( pToCol ){
  70864. for(i=0; i<nCol; i++){
  70865. int n = sqlite3Strlen30(pToCol->a[i].zName);
  70866. pFKey->aCol[i].zCol = z;
  70867. memcpy(z, pToCol->a[i].zName, n);
  70868. z[n] = 0;
  70869. z += n+1;
  70870. }
  70871. }
  70872. pFKey->isDeferred = 0;
  70873. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  70874. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  70875. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  70876. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  70877. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  70878. );
  70879. if( pNextTo==pFKey ){
  70880. db->mallocFailed = 1;
  70881. goto fk_end;
  70882. }
  70883. if( pNextTo ){
  70884. assert( pNextTo->pPrevTo==0 );
  70885. pFKey->pNextTo = pNextTo;
  70886. pNextTo->pPrevTo = pFKey;
  70887. }
  70888. /* Link the foreign key to the table as the last step.
  70889. */
  70890. p->pFKey = pFKey;
  70891. pFKey = 0;
  70892. fk_end:
  70893. sqlite3DbFree(db, pFKey);
  70894. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  70895. sqlite3ExprListDelete(db, pFromCol);
  70896. sqlite3ExprListDelete(db, pToCol);
  70897. }
  70898. /*
  70899. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  70900. ** clause is seen as part of a foreign key definition. The isDeferred
  70901. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  70902. ** The behavior of the most recently created foreign key is adjusted
  70903. ** accordingly.
  70904. */
  70905. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  70906. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70907. Table *pTab;
  70908. FKey *pFKey;
  70909. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  70910. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  70911. pFKey->isDeferred = (u8)isDeferred;
  70912. #endif
  70913. }
  70914. /*
  70915. ** Generate code that will erase and refill index *pIdx. This is
  70916. ** used to initialize a newly created index or to recompute the
  70917. ** content of an index in response to a REINDEX command.
  70918. **
  70919. ** if memRootPage is not negative, it means that the index is newly
  70920. ** created. The register specified by memRootPage contains the
  70921. ** root page number of the index. If memRootPage is negative, then
  70922. ** the index already exists and must be cleared before being refilled and
  70923. ** the root page number of the index is taken from pIndex->tnum.
  70924. */
  70925. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  70926. Table *pTab = pIndex->pTable; /* The table that is indexed */
  70927. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  70928. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  70929. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  70930. int addr1; /* Address of top of loop */
  70931. int addr2; /* Address to jump to for next iteration */
  70932. int tnum; /* Root page of index */
  70933. int iPartIdxLabel; /* Jump to this label to skip a row */
  70934. Vdbe *v; /* Generate code into this virtual machine */
  70935. KeyInfo *pKey; /* KeyInfo for index */
  70936. int regRecord; /* Register holding assemblied index record */
  70937. sqlite3 *db = pParse->db; /* The database connection */
  70938. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  70939. #ifndef SQLITE_OMIT_AUTHORIZATION
  70940. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  70941. db->aDb[iDb].zName ) ){
  70942. return;
  70943. }
  70944. #endif
  70945. /* Require a write-lock on the table to perform this operation */
  70946. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  70947. v = sqlite3GetVdbe(pParse);
  70948. if( v==0 ) return;
  70949. if( memRootPage>=0 ){
  70950. tnum = memRootPage;
  70951. }else{
  70952. tnum = pIndex->tnum;
  70953. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  70954. }
  70955. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  70956. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  70957. (char *)pKey, P4_KEYINFO_HANDOFF);
  70958. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  70959. /* Open the sorter cursor if we are to use one. */
  70960. iSorter = pParse->nTab++;
  70961. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  70962. /* Open the table. Loop through all rows of the table, inserting index
  70963. ** records into the sorter. */
  70964. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  70965. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  70966. regRecord = sqlite3GetTempReg(pParse);
  70967. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  70968. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  70969. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  70970. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  70971. sqlite3VdbeJumpHere(v, addr1);
  70972. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  70973. if( pIndex->onError!=OE_None ){
  70974. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  70975. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  70976. addr2 = sqlite3VdbeCurrentAddr(v);
  70977. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  70978. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  70979. OE_Abort, "indexed columns are not unique", P4_STATIC
  70980. );
  70981. }else{
  70982. addr2 = sqlite3VdbeCurrentAddr(v);
  70983. }
  70984. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  70985. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  70986. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  70987. sqlite3ReleaseTempReg(pParse, regRecord);
  70988. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  70989. sqlite3VdbeJumpHere(v, addr1);
  70990. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  70991. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  70992. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  70993. }
  70994. /*
  70995. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  70996. ** and pTblList is the name of the table that is to be indexed. Both will
  70997. ** be NULL for a primary key or an index that is created to satisfy a
  70998. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  70999. ** as the table to be indexed. pParse->pNewTable is a table that is
  71000. ** currently being constructed by a CREATE TABLE statement.
  71001. **
  71002. ** pList is a list of columns to be indexed. pList will be NULL if this
  71003. ** is a primary key or unique-constraint on the most recent column added
  71004. ** to the table currently under construction.
  71005. **
  71006. ** If the index is created successfully, return a pointer to the new Index
  71007. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  71008. ** as the tables primary key (Index.autoIndex==2).
  71009. */
  71010. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  71011. Parse *pParse, /* All information about this parse */
  71012. Token *pName1, /* First part of index name. May be NULL */
  71013. Token *pName2, /* Second part of index name. May be NULL */
  71014. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  71015. ExprList *pList, /* A list of columns to be indexed */
  71016. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  71017. Token *pStart, /* The CREATE token that begins this statement */
  71018. Expr *pPIWhere, /* WHERE clause for partial indices */
  71019. int sortOrder, /* Sort order of primary key when pList==NULL */
  71020. int ifNotExist /* Omit error if index already exists */
  71021. ){
  71022. Index *pRet = 0; /* Pointer to return */
  71023. Table *pTab = 0; /* Table to be indexed */
  71024. Index *pIndex = 0; /* The index to be created */
  71025. char *zName = 0; /* Name of the index */
  71026. int nName; /* Number of characters in zName */
  71027. int i, j;
  71028. Token nullId; /* Fake token for an empty ID list */
  71029. DbFixer sFix; /* For assigning database names to pTable */
  71030. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  71031. sqlite3 *db = pParse->db;
  71032. Db *pDb; /* The specific table containing the indexed database */
  71033. int iDb; /* Index of the database that is being written */
  71034. Token *pName = 0; /* Unqualified name of the index to create */
  71035. struct ExprList_item *pListItem; /* For looping over pList */
  71036. const Column *pTabCol; /* A column in the table */
  71037. int nCol; /* Number of columns */
  71038. int nExtra = 0; /* Space allocated for zExtra[] */
  71039. char *zExtra; /* Extra space after the Index object */
  71040. assert( pParse->nErr==0 ); /* Never called with prior errors */
  71041. if( db->mallocFailed || IN_DECLARE_VTAB ){
  71042. goto exit_create_index;
  71043. }
  71044. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  71045. goto exit_create_index;
  71046. }
  71047. /*
  71048. ** Find the table that is to be indexed. Return early if not found.
  71049. */
  71050. if( pTblName!=0 ){
  71051. /* Use the two-part index name to determine the database
  71052. ** to search for the table. 'Fix' the table name to this db
  71053. ** before looking up the table.
  71054. */
  71055. assert( pName1 && pName2 );
  71056. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  71057. if( iDb<0 ) goto exit_create_index;
  71058. assert( pName && pName->z );
  71059. #ifndef SQLITE_OMIT_TEMPDB
  71060. /* If the index name was unqualified, check if the table
  71061. ** is a temp table. If so, set the database to 1. Do not do this
  71062. ** if initialising a database schema.
  71063. */
  71064. if( !db->init.busy ){
  71065. pTab = sqlite3SrcListLookup(pParse, pTblName);
  71066. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  71067. iDb = 1;
  71068. }
  71069. }
  71070. #endif
  71071. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  71072. if( sqlite3FixSrcList(&sFix, pTblName) ){
  71073. /* Because the parser constructs pTblName from a single identifier,
  71074. ** sqlite3FixSrcList can never fail. */
  71075. assert(0);
  71076. }
  71077. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  71078. assert( db->mallocFailed==0 || pTab==0 );
  71079. if( pTab==0 ) goto exit_create_index;
  71080. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  71081. sqlite3ErrorMsg(pParse,
  71082. "cannot create a TEMP index on non-TEMP table \"%s\"",
  71083. pTab->zName);
  71084. goto exit_create_index;
  71085. }
  71086. }else{
  71087. assert( pName==0 );
  71088. assert( pStart==0 );
  71089. pTab = pParse->pNewTable;
  71090. if( !pTab ) goto exit_create_index;
  71091. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  71092. }
  71093. pDb = &db->aDb[iDb];
  71094. assert( pTab!=0 );
  71095. assert( pParse->nErr==0 );
  71096. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  71097. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  71098. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  71099. goto exit_create_index;
  71100. }
  71101. #ifndef SQLITE_OMIT_VIEW
  71102. if( pTab->pSelect ){
  71103. sqlite3ErrorMsg(pParse, "views may not be indexed");
  71104. goto exit_create_index;
  71105. }
  71106. #endif
  71107. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71108. if( IsVirtual(pTab) ){
  71109. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  71110. goto exit_create_index;
  71111. }
  71112. #endif
  71113. /*
  71114. ** Find the name of the index. Make sure there is not already another
  71115. ** index or table with the same name.
  71116. **
  71117. ** Exception: If we are reading the names of permanent indices from the
  71118. ** sqlite_master table (because some other process changed the schema) and
  71119. ** one of the index names collides with the name of a temporary table or
  71120. ** index, then we will continue to process this index.
  71121. **
  71122. ** If pName==0 it means that we are
  71123. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  71124. ** own name.
  71125. */
  71126. if( pName ){
  71127. zName = sqlite3NameFromToken(db, pName);
  71128. if( zName==0 ) goto exit_create_index;
  71129. assert( pName->z!=0 );
  71130. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  71131. goto exit_create_index;
  71132. }
  71133. if( !db->init.busy ){
  71134. if( sqlite3FindTable(db, zName, 0)!=0 ){
  71135. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  71136. goto exit_create_index;
  71137. }
  71138. }
  71139. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  71140. if( !ifNotExist ){
  71141. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  71142. }else{
  71143. assert( !db->init.busy );
  71144. sqlite3CodeVerifySchema(pParse, iDb);
  71145. }
  71146. goto exit_create_index;
  71147. }
  71148. }else{
  71149. int n;
  71150. Index *pLoop;
  71151. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  71152. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  71153. if( zName==0 ){
  71154. goto exit_create_index;
  71155. }
  71156. }
  71157. /* Check for authorization to create an index.
  71158. */
  71159. #ifndef SQLITE_OMIT_AUTHORIZATION
  71160. {
  71161. const char *zDb = pDb->zName;
  71162. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  71163. goto exit_create_index;
  71164. }
  71165. i = SQLITE_CREATE_INDEX;
  71166. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  71167. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  71168. goto exit_create_index;
  71169. }
  71170. }
  71171. #endif
  71172. /* If pList==0, it means this routine was called to make a primary
  71173. ** key out of the last column added to the table under construction.
  71174. ** So create a fake list to simulate this.
  71175. */
  71176. if( pList==0 ){
  71177. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  71178. nullId.n = sqlite3Strlen30((char*)nullId.z);
  71179. pList = sqlite3ExprListAppend(pParse, 0, 0);
  71180. if( pList==0 ) goto exit_create_index;
  71181. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  71182. pList->a[0].sortOrder = (u8)sortOrder;
  71183. }
  71184. /* Figure out how many bytes of space are required to store explicitly
  71185. ** specified collation sequence names.
  71186. */
  71187. for(i=0; i<pList->nExpr; i++){
  71188. Expr *pExpr = pList->a[i].pExpr;
  71189. if( pExpr ){
  71190. assert( pExpr->op==TK_COLLATE );
  71191. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  71192. }
  71193. }
  71194. /*
  71195. ** Allocate the index structure.
  71196. */
  71197. nName = sqlite3Strlen30(zName);
  71198. nCol = pList->nExpr;
  71199. pIndex = sqlite3DbMallocZero(db,
  71200. ROUND8(sizeof(Index)) + /* Index structure */
  71201. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  71202. sizeof(char *)*nCol + /* Index.azColl */
  71203. sizeof(int)*nCol + /* Index.aiColumn */
  71204. sizeof(u8)*nCol + /* Index.aSortOrder */
  71205. nName + 1 + /* Index.zName */
  71206. nExtra /* Collation sequence names */
  71207. );
  71208. if( db->mallocFailed ){
  71209. goto exit_create_index;
  71210. }
  71211. zExtra = (char*)pIndex;
  71212. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  71213. pIndex->azColl = (char**)
  71214. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  71215. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  71216. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  71217. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  71218. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  71219. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  71220. zExtra = (char *)(&pIndex->zName[nName+1]);
  71221. memcpy(pIndex->zName, zName, nName+1);
  71222. pIndex->pTable = pTab;
  71223. pIndex->nColumn = pList->nExpr;
  71224. pIndex->onError = (u8)onError;
  71225. pIndex->uniqNotNull = onError==OE_Abort;
  71226. pIndex->autoIndex = (u8)(pName==0);
  71227. pIndex->pSchema = db->aDb[iDb].pSchema;
  71228. if( pPIWhere ){
  71229. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  71230. pIndex->pPartIdxWhere = pPIWhere;
  71231. pPIWhere = 0;
  71232. }
  71233. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  71234. /* Check to see if we should honor DESC requests on index columns
  71235. */
  71236. if( pDb->pSchema->file_format>=4 ){
  71237. sortOrderMask = -1; /* Honor DESC */
  71238. }else{
  71239. sortOrderMask = 0; /* Ignore DESC */
  71240. }
  71241. /* Scan the names of the columns of the table to be indexed and
  71242. ** load the column indices into the Index structure. Report an error
  71243. ** if any column is not found.
  71244. **
  71245. ** TODO: Add a test to make sure that the same column is not named
  71246. ** more than once within the same index. Only the first instance of
  71247. ** the column will ever be used by the optimizer. Note that using the
  71248. ** same column more than once cannot be an error because that would
  71249. ** break backwards compatibility - it needs to be a warning.
  71250. */
  71251. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  71252. const char *zColName = pListItem->zName;
  71253. int requestedSortOrder;
  71254. char *zColl; /* Collation sequence name */
  71255. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  71256. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  71257. }
  71258. if( j>=pTab->nCol ){
  71259. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  71260. pTab->zName, zColName);
  71261. pParse->checkSchema = 1;
  71262. goto exit_create_index;
  71263. }
  71264. pIndex->aiColumn[i] = j;
  71265. if( pListItem->pExpr ){
  71266. int nColl;
  71267. assert( pListItem->pExpr->op==TK_COLLATE );
  71268. zColl = pListItem->pExpr->u.zToken;
  71269. nColl = sqlite3Strlen30(zColl) + 1;
  71270. assert( nExtra>=nColl );
  71271. memcpy(zExtra, zColl, nColl);
  71272. zColl = zExtra;
  71273. zExtra += nColl;
  71274. nExtra -= nColl;
  71275. }else{
  71276. zColl = pTab->aCol[j].zColl;
  71277. if( !zColl ) zColl = "BINARY";
  71278. }
  71279. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  71280. goto exit_create_index;
  71281. }
  71282. pIndex->azColl[i] = zColl;
  71283. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  71284. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  71285. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  71286. }
  71287. sqlite3DefaultRowEst(pIndex);
  71288. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  71289. if( pTab==pParse->pNewTable ){
  71290. /* This routine has been called to create an automatic index as a
  71291. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  71292. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  71293. ** i.e. one of:
  71294. **
  71295. ** CREATE TABLE t(x PRIMARY KEY, y);
  71296. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  71297. **
  71298. ** Either way, check to see if the table already has such an index. If
  71299. ** so, don't bother creating this one. This only applies to
  71300. ** automatically created indices. Users can do as they wish with
  71301. ** explicit indices.
  71302. **
  71303. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  71304. ** (and thus suppressing the second one) even if they have different
  71305. ** sort orders.
  71306. **
  71307. ** If there are different collating sequences or if the columns of
  71308. ** the constraint occur in different orders, then the constraints are
  71309. ** considered distinct and both result in separate indices.
  71310. */
  71311. Index *pIdx;
  71312. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  71313. int k;
  71314. assert( pIdx->onError!=OE_None );
  71315. assert( pIdx->autoIndex );
  71316. assert( pIndex->onError!=OE_None );
  71317. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  71318. for(k=0; k<pIdx->nColumn; k++){
  71319. const char *z1;
  71320. const char *z2;
  71321. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  71322. z1 = pIdx->azColl[k];
  71323. z2 = pIndex->azColl[k];
  71324. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  71325. }
  71326. if( k==pIdx->nColumn ){
  71327. if( pIdx->onError!=pIndex->onError ){
  71328. /* This constraint creates the same index as a previous
  71329. ** constraint specified somewhere in the CREATE TABLE statement.
  71330. ** However the ON CONFLICT clauses are different. If both this
  71331. ** constraint and the previous equivalent constraint have explicit
  71332. ** ON CONFLICT clauses this is an error. Otherwise, use the
  71333. ** explicitly specified behavior for the index.
  71334. */
  71335. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  71336. sqlite3ErrorMsg(pParse,
  71337. "conflicting ON CONFLICT clauses specified", 0);
  71338. }
  71339. if( pIdx->onError==OE_Default ){
  71340. pIdx->onError = pIndex->onError;
  71341. }
  71342. }
  71343. goto exit_create_index;
  71344. }
  71345. }
  71346. }
  71347. /* Link the new Index structure to its table and to the other
  71348. ** in-memory database structures.
  71349. */
  71350. if( db->init.busy ){
  71351. Index *p;
  71352. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  71353. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  71354. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  71355. pIndex);
  71356. if( p ){
  71357. assert( p==pIndex ); /* Malloc must have failed */
  71358. db->mallocFailed = 1;
  71359. goto exit_create_index;
  71360. }
  71361. db->flags |= SQLITE_InternChanges;
  71362. if( pTblName!=0 ){
  71363. pIndex->tnum = db->init.newTnum;
  71364. }
  71365. }
  71366. /* If the db->init.busy is 0 then create the index on disk. This
  71367. ** involves writing the index into the master table and filling in the
  71368. ** index with the current table contents.
  71369. **
  71370. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  71371. ** command. db->init.busy is 1 when a database is opened and
  71372. ** CREATE INDEX statements are read out of the master table. In
  71373. ** the latter case the index already exists on disk, which is why
  71374. ** we don't want to recreate it.
  71375. **
  71376. ** If pTblName==0 it means this index is generated as a primary key
  71377. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  71378. ** has just been created, it contains no data and the index initialization
  71379. ** step can be skipped.
  71380. */
  71381. else if( pParse->nErr==0 ){
  71382. Vdbe *v;
  71383. char *zStmt;
  71384. int iMem = ++pParse->nMem;
  71385. v = sqlite3GetVdbe(pParse);
  71386. if( v==0 ) goto exit_create_index;
  71387. /* Create the rootpage for the index
  71388. */
  71389. sqlite3BeginWriteOperation(pParse, 1, iDb);
  71390. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  71391. /* Gather the complete text of the CREATE INDEX statement into
  71392. ** the zStmt variable
  71393. */
  71394. if( pStart ){
  71395. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  71396. if( pName->z[n-1]==';' ) n--;
  71397. /* A named index with an explicit CREATE INDEX statement */
  71398. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  71399. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  71400. }else{
  71401. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  71402. /* zStmt = sqlite3MPrintf(""); */
  71403. zStmt = 0;
  71404. }
  71405. /* Add an entry in sqlite_master for this index
  71406. */
  71407. sqlite3NestedParse(pParse,
  71408. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  71409. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  71410. pIndex->zName,
  71411. pTab->zName,
  71412. iMem,
  71413. zStmt
  71414. );
  71415. sqlite3DbFree(db, zStmt);
  71416. /* Fill the index with data and reparse the schema. Code an OP_Expire
  71417. ** to invalidate all pre-compiled statements.
  71418. */
  71419. if( pTblName ){
  71420. sqlite3RefillIndex(pParse, pIndex, iMem);
  71421. sqlite3ChangeCookie(pParse, iDb);
  71422. sqlite3VdbeAddParseSchemaOp(v, iDb,
  71423. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  71424. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  71425. }
  71426. }
  71427. /* When adding an index to the list of indices for a table, make
  71428. ** sure all indices labeled OE_Replace come after all those labeled
  71429. ** OE_Ignore. This is necessary for the correct constraint check
  71430. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  71431. ** UPDATE and INSERT statements.
  71432. */
  71433. if( db->init.busy || pTblName==0 ){
  71434. if( onError!=OE_Replace || pTab->pIndex==0
  71435. || pTab->pIndex->onError==OE_Replace){
  71436. pIndex->pNext = pTab->pIndex;
  71437. pTab->pIndex = pIndex;
  71438. }else{
  71439. Index *pOther = pTab->pIndex;
  71440. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  71441. pOther = pOther->pNext;
  71442. }
  71443. pIndex->pNext = pOther->pNext;
  71444. pOther->pNext = pIndex;
  71445. }
  71446. pRet = pIndex;
  71447. pIndex = 0;
  71448. }
  71449. /* Clean up before exiting */
  71450. exit_create_index:
  71451. if( pIndex ) freeIndex(db, pIndex);
  71452. sqlite3ExprDelete(db, pPIWhere);
  71453. sqlite3ExprListDelete(db, pList);
  71454. sqlite3SrcListDelete(db, pTblName);
  71455. sqlite3DbFree(db, zName);
  71456. return pRet;
  71457. }
  71458. /*
  71459. ** Fill the Index.aiRowEst[] array with default information - information
  71460. ** to be used when we have not run the ANALYZE command.
  71461. **
  71462. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  71463. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  71464. ** number of rows in the table that match any particular value of the
  71465. ** first column of the index. aiRowEst[2] is an estimate of the number
  71466. ** of rows that match any particular combiniation of the first 2 columns
  71467. ** of the index. And so forth. It must always be the case that
  71468. *
  71469. ** aiRowEst[N]<=aiRowEst[N-1]
  71470. ** aiRowEst[N]>=1
  71471. **
  71472. ** Apart from that, we have little to go on besides intuition as to
  71473. ** how aiRowEst[] should be initialized. The numbers generated here
  71474. ** are based on typical values found in actual indices.
  71475. */
  71476. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  71477. tRowcnt *a = pIdx->aiRowEst;
  71478. int i;
  71479. tRowcnt n;
  71480. assert( a!=0 );
  71481. a[0] = pIdx->pTable->nRowEst;
  71482. if( a[0]<10 ) a[0] = 10;
  71483. n = 10;
  71484. for(i=1; i<=pIdx->nColumn; i++){
  71485. a[i] = n;
  71486. if( n>5 ) n--;
  71487. }
  71488. if( pIdx->onError!=OE_None ){
  71489. a[pIdx->nColumn] = 1;
  71490. }
  71491. }
  71492. /*
  71493. ** This routine will drop an existing named index. This routine
  71494. ** implements the DROP INDEX statement.
  71495. */
  71496. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  71497. Index *pIndex;
  71498. Vdbe *v;
  71499. sqlite3 *db = pParse->db;
  71500. int iDb;
  71501. assert( pParse->nErr==0 ); /* Never called with prior errors */
  71502. if( db->mallocFailed ){
  71503. goto exit_drop_index;
  71504. }
  71505. assert( pName->nSrc==1 );
  71506. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  71507. goto exit_drop_index;
  71508. }
  71509. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  71510. if( pIndex==0 ){
  71511. if( !ifExists ){
  71512. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  71513. }else{
  71514. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  71515. }
  71516. pParse->checkSchema = 1;
  71517. goto exit_drop_index;
  71518. }
  71519. if( pIndex->autoIndex ){
  71520. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  71521. "or PRIMARY KEY constraint cannot be dropped", 0);
  71522. goto exit_drop_index;
  71523. }
  71524. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  71525. #ifndef SQLITE_OMIT_AUTHORIZATION
  71526. {
  71527. int code = SQLITE_DROP_INDEX;
  71528. Table *pTab = pIndex->pTable;
  71529. const char *zDb = db->aDb[iDb].zName;
  71530. const char *zTab = SCHEMA_TABLE(iDb);
  71531. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  71532. goto exit_drop_index;
  71533. }
  71534. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  71535. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  71536. goto exit_drop_index;
  71537. }
  71538. }
  71539. #endif
  71540. /* Generate code to remove the index and from the master table */
  71541. v = sqlite3GetVdbe(pParse);
  71542. if( v ){
  71543. sqlite3BeginWriteOperation(pParse, 1, iDb);
  71544. sqlite3NestedParse(pParse,
  71545. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  71546. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  71547. );
  71548. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  71549. sqlite3ChangeCookie(pParse, iDb);
  71550. destroyRootPage(pParse, pIndex->tnum, iDb);
  71551. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  71552. }
  71553. exit_drop_index:
  71554. sqlite3SrcListDelete(db, pName);
  71555. }
  71556. /*
  71557. ** pArray is a pointer to an array of objects. Each object in the
  71558. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  71559. ** to extend the array so that there is space for a new object at the end.
  71560. **
  71561. ** When this function is called, *pnEntry contains the current size of
  71562. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  71563. ** in total).
  71564. **
  71565. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  71566. ** space allocated for the new object is zeroed, *pnEntry updated to
  71567. ** reflect the new size of the array and a pointer to the new allocation
  71568. ** returned. *pIdx is set to the index of the new array entry in this case.
  71569. **
  71570. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  71571. ** unchanged and a copy of pArray returned.
  71572. */
  71573. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  71574. sqlite3 *db, /* Connection to notify of malloc failures */
  71575. void *pArray, /* Array of objects. Might be reallocated */
  71576. int szEntry, /* Size of each object in the array */
  71577. int *pnEntry, /* Number of objects currently in use */
  71578. int *pIdx /* Write the index of a new slot here */
  71579. ){
  71580. char *z;
  71581. int n = *pnEntry;
  71582. if( (n & (n-1))==0 ){
  71583. int sz = (n==0) ? 1 : 2*n;
  71584. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  71585. if( pNew==0 ){
  71586. *pIdx = -1;
  71587. return pArray;
  71588. }
  71589. pArray = pNew;
  71590. }
  71591. z = (char*)pArray;
  71592. memset(&z[n * szEntry], 0, szEntry);
  71593. *pIdx = n;
  71594. ++*pnEntry;
  71595. return pArray;
  71596. }
  71597. /*
  71598. ** Append a new element to the given IdList. Create a new IdList if
  71599. ** need be.
  71600. **
  71601. ** A new IdList is returned, or NULL if malloc() fails.
  71602. */
  71603. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  71604. int i;
  71605. if( pList==0 ){
  71606. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  71607. if( pList==0 ) return 0;
  71608. }
  71609. pList->a = sqlite3ArrayAllocate(
  71610. db,
  71611. pList->a,
  71612. sizeof(pList->a[0]),
  71613. &pList->nId,
  71614. &i
  71615. );
  71616. if( i<0 ){
  71617. sqlite3IdListDelete(db, pList);
  71618. return 0;
  71619. }
  71620. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  71621. return pList;
  71622. }
  71623. /*
  71624. ** Delete an IdList.
  71625. */
  71626. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  71627. int i;
  71628. if( pList==0 ) return;
  71629. for(i=0; i<pList->nId; i++){
  71630. sqlite3DbFree(db, pList->a[i].zName);
  71631. }
  71632. sqlite3DbFree(db, pList->a);
  71633. sqlite3DbFree(db, pList);
  71634. }
  71635. /*
  71636. ** Return the index in pList of the identifier named zId. Return -1
  71637. ** if not found.
  71638. */
  71639. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  71640. int i;
  71641. if( pList==0 ) return -1;
  71642. for(i=0; i<pList->nId; i++){
  71643. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  71644. }
  71645. return -1;
  71646. }
  71647. /*
  71648. ** Expand the space allocated for the given SrcList object by
  71649. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  71650. ** New slots are zeroed.
  71651. **
  71652. ** For example, suppose a SrcList initially contains two entries: A,B.
  71653. ** To append 3 new entries onto the end, do this:
  71654. **
  71655. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  71656. **
  71657. ** After the call above it would contain: A, B, nil, nil, nil.
  71658. ** If the iStart argument had been 1 instead of 2, then the result
  71659. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  71660. ** the iStart value would be 0. The result then would
  71661. ** be: nil, nil, nil, A, B.
  71662. **
  71663. ** If a memory allocation fails the SrcList is unchanged. The
  71664. ** db->mallocFailed flag will be set to true.
  71665. */
  71666. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  71667. sqlite3 *db, /* Database connection to notify of OOM errors */
  71668. SrcList *pSrc, /* The SrcList to be enlarged */
  71669. int nExtra, /* Number of new slots to add to pSrc->a[] */
  71670. int iStart /* Index in pSrc->a[] of first new slot */
  71671. ){
  71672. int i;
  71673. /* Sanity checking on calling parameters */
  71674. assert( iStart>=0 );
  71675. assert( nExtra>=1 );
  71676. assert( pSrc!=0 );
  71677. assert( iStart<=pSrc->nSrc );
  71678. /* Allocate additional space if needed */
  71679. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  71680. SrcList *pNew;
  71681. int nAlloc = pSrc->nSrc+nExtra;
  71682. int nGot;
  71683. pNew = sqlite3DbRealloc(db, pSrc,
  71684. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  71685. if( pNew==0 ){
  71686. assert( db->mallocFailed );
  71687. return pSrc;
  71688. }
  71689. pSrc = pNew;
  71690. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  71691. pSrc->nAlloc = (u8)nGot;
  71692. }
  71693. /* Move existing slots that come after the newly inserted slots
  71694. ** out of the way */
  71695. for(i=pSrc->nSrc-1; i>=iStart; i--){
  71696. pSrc->a[i+nExtra] = pSrc->a[i];
  71697. }
  71698. pSrc->nSrc += (i8)nExtra;
  71699. /* Zero the newly allocated slots */
  71700. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  71701. for(i=iStart; i<iStart+nExtra; i++){
  71702. pSrc->a[i].iCursor = -1;
  71703. }
  71704. /* Return a pointer to the enlarged SrcList */
  71705. return pSrc;
  71706. }
  71707. /*
  71708. ** Append a new table name to the given SrcList. Create a new SrcList if
  71709. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  71710. **
  71711. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  71712. ** SrcList might be the same as the SrcList that was input or it might be
  71713. ** a new one. If an OOM error does occurs, then the prior value of pList
  71714. ** that is input to this routine is automatically freed.
  71715. **
  71716. ** If pDatabase is not null, it means that the table has an optional
  71717. ** database name prefix. Like this: "database.table". The pDatabase
  71718. ** points to the table name and the pTable points to the database name.
  71719. ** The SrcList.a[].zName field is filled with the table name which might
  71720. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  71721. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  71722. ** or with NULL if no database is specified.
  71723. **
  71724. ** In other words, if call like this:
  71725. **
  71726. ** sqlite3SrcListAppend(D,A,B,0);
  71727. **
  71728. ** Then B is a table name and the database name is unspecified. If called
  71729. ** like this:
  71730. **
  71731. ** sqlite3SrcListAppend(D,A,B,C);
  71732. **
  71733. ** Then C is the table name and B is the database name. If C is defined
  71734. ** then so is B. In other words, we never have a case where:
  71735. **
  71736. ** sqlite3SrcListAppend(D,A,0,C);
  71737. **
  71738. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  71739. ** before being added to the SrcList.
  71740. */
  71741. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  71742. sqlite3 *db, /* Connection to notify of malloc failures */
  71743. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  71744. Token *pTable, /* Table to append */
  71745. Token *pDatabase /* Database of the table */
  71746. ){
  71747. struct SrcList_item *pItem;
  71748. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  71749. if( pList==0 ){
  71750. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  71751. if( pList==0 ) return 0;
  71752. pList->nAlloc = 1;
  71753. }
  71754. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  71755. if( db->mallocFailed ){
  71756. sqlite3SrcListDelete(db, pList);
  71757. return 0;
  71758. }
  71759. pItem = &pList->a[pList->nSrc-1];
  71760. if( pDatabase && pDatabase->z==0 ){
  71761. pDatabase = 0;
  71762. }
  71763. if( pDatabase ){
  71764. Token *pTemp = pDatabase;
  71765. pDatabase = pTable;
  71766. pTable = pTemp;
  71767. }
  71768. pItem->zName = sqlite3NameFromToken(db, pTable);
  71769. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  71770. return pList;
  71771. }
  71772. /*
  71773. ** Assign VdbeCursor index numbers to all tables in a SrcList
  71774. */
  71775. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  71776. int i;
  71777. struct SrcList_item *pItem;
  71778. assert(pList || pParse->db->mallocFailed );
  71779. if( pList ){
  71780. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  71781. if( pItem->iCursor>=0 ) break;
  71782. pItem->iCursor = pParse->nTab++;
  71783. if( pItem->pSelect ){
  71784. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  71785. }
  71786. }
  71787. }
  71788. }
  71789. /*
  71790. ** Delete an entire SrcList including all its substructure.
  71791. */
  71792. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  71793. int i;
  71794. struct SrcList_item *pItem;
  71795. if( pList==0 ) return;
  71796. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  71797. sqlite3DbFree(db, pItem->zDatabase);
  71798. sqlite3DbFree(db, pItem->zName);
  71799. sqlite3DbFree(db, pItem->zAlias);
  71800. sqlite3DbFree(db, pItem->zIndex);
  71801. sqlite3DeleteTable(db, pItem->pTab);
  71802. sqlite3SelectDelete(db, pItem->pSelect);
  71803. sqlite3ExprDelete(db, pItem->pOn);
  71804. sqlite3IdListDelete(db, pItem->pUsing);
  71805. }
  71806. sqlite3DbFree(db, pList);
  71807. }
  71808. /*
  71809. ** This routine is called by the parser to add a new term to the
  71810. ** end of a growing FROM clause. The "p" parameter is the part of
  71811. ** the FROM clause that has already been constructed. "p" is NULL
  71812. ** if this is the first term of the FROM clause. pTable and pDatabase
  71813. ** are the name of the table and database named in the FROM clause term.
  71814. ** pDatabase is NULL if the database name qualifier is missing - the
  71815. ** usual case. If the term has a alias, then pAlias points to the
  71816. ** alias token. If the term is a subquery, then pSubquery is the
  71817. ** SELECT statement that the subquery encodes. The pTable and
  71818. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  71819. ** parameters are the content of the ON and USING clauses.
  71820. **
  71821. ** Return a new SrcList which encodes is the FROM with the new
  71822. ** term added.
  71823. */
  71824. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  71825. Parse *pParse, /* Parsing context */
  71826. SrcList *p, /* The left part of the FROM clause already seen */
  71827. Token *pTable, /* Name of the table to add to the FROM clause */
  71828. Token *pDatabase, /* Name of the database containing pTable */
  71829. Token *pAlias, /* The right-hand side of the AS subexpression */
  71830. Select *pSubquery, /* A subquery used in place of a table name */
  71831. Expr *pOn, /* The ON clause of a join */
  71832. IdList *pUsing /* The USING clause of a join */
  71833. ){
  71834. struct SrcList_item *pItem;
  71835. sqlite3 *db = pParse->db;
  71836. if( !p && (pOn || pUsing) ){
  71837. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  71838. (pOn ? "ON" : "USING")
  71839. );
  71840. goto append_from_error;
  71841. }
  71842. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  71843. if( p==0 || NEVER(p->nSrc==0) ){
  71844. goto append_from_error;
  71845. }
  71846. pItem = &p->a[p->nSrc-1];
  71847. assert( pAlias!=0 );
  71848. if( pAlias->n ){
  71849. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  71850. }
  71851. pItem->pSelect = pSubquery;
  71852. pItem->pOn = pOn;
  71853. pItem->pUsing = pUsing;
  71854. return p;
  71855. append_from_error:
  71856. assert( p==0 );
  71857. sqlite3ExprDelete(db, pOn);
  71858. sqlite3IdListDelete(db, pUsing);
  71859. sqlite3SelectDelete(db, pSubquery);
  71860. return 0;
  71861. }
  71862. /*
  71863. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  71864. ** element of the source-list passed as the second argument.
  71865. */
  71866. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  71867. assert( pIndexedBy!=0 );
  71868. if( p && ALWAYS(p->nSrc>0) ){
  71869. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  71870. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  71871. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  71872. /* A "NOT INDEXED" clause was supplied. See parse.y
  71873. ** construct "indexed_opt" for details. */
  71874. pItem->notIndexed = 1;
  71875. }else{
  71876. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  71877. }
  71878. }
  71879. }
  71880. /*
  71881. ** When building up a FROM clause in the parser, the join operator
  71882. ** is initially attached to the left operand. But the code generator
  71883. ** expects the join operator to be on the right operand. This routine
  71884. ** Shifts all join operators from left to right for an entire FROM
  71885. ** clause.
  71886. **
  71887. ** Example: Suppose the join is like this:
  71888. **
  71889. ** A natural cross join B
  71890. **
  71891. ** The operator is "natural cross join". The A and B operands are stored
  71892. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  71893. ** operator with A. This routine shifts that operator over to B.
  71894. */
  71895. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  71896. if( p ){
  71897. int i;
  71898. assert( p->a || p->nSrc==0 );
  71899. for(i=p->nSrc-1; i>0; i--){
  71900. p->a[i].jointype = p->a[i-1].jointype;
  71901. }
  71902. p->a[0].jointype = 0;
  71903. }
  71904. }
  71905. /*
  71906. ** Begin a transaction
  71907. */
  71908. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  71909. sqlite3 *db;
  71910. Vdbe *v;
  71911. int i;
  71912. assert( pParse!=0 );
  71913. db = pParse->db;
  71914. assert( db!=0 );
  71915. /* if( db->aDb[0].pBt==0 ) return; */
  71916. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  71917. return;
  71918. }
  71919. v = sqlite3GetVdbe(pParse);
  71920. if( !v ) return;
  71921. if( type!=TK_DEFERRED ){
  71922. for(i=0; i<db->nDb; i++){
  71923. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  71924. sqlite3VdbeUsesBtree(v, i);
  71925. }
  71926. }
  71927. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  71928. }
  71929. /*
  71930. ** Commit a transaction
  71931. */
  71932. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  71933. Vdbe *v;
  71934. assert( pParse!=0 );
  71935. assert( pParse->db!=0 );
  71936. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  71937. return;
  71938. }
  71939. v = sqlite3GetVdbe(pParse);
  71940. if( v ){
  71941. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  71942. }
  71943. }
  71944. /*
  71945. ** Rollback a transaction
  71946. */
  71947. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  71948. Vdbe *v;
  71949. assert( pParse!=0 );
  71950. assert( pParse->db!=0 );
  71951. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  71952. return;
  71953. }
  71954. v = sqlite3GetVdbe(pParse);
  71955. if( v ){
  71956. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  71957. }
  71958. }
  71959. /*
  71960. ** This function is called by the parser when it parses a command to create,
  71961. ** release or rollback an SQL savepoint.
  71962. */
  71963. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  71964. char *zName = sqlite3NameFromToken(pParse->db, pName);
  71965. if( zName ){
  71966. Vdbe *v = sqlite3GetVdbe(pParse);
  71967. #ifndef SQLITE_OMIT_AUTHORIZATION
  71968. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  71969. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  71970. #endif
  71971. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  71972. sqlite3DbFree(pParse->db, zName);
  71973. return;
  71974. }
  71975. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  71976. }
  71977. }
  71978. /*
  71979. ** Make sure the TEMP database is open and available for use. Return
  71980. ** the number of errors. Leave any error messages in the pParse structure.
  71981. */
  71982. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  71983. sqlite3 *db = pParse->db;
  71984. if( db->aDb[1].pBt==0 && !pParse->explain ){
  71985. int rc;
  71986. Btree *pBt;
  71987. static const int flags =
  71988. SQLITE_OPEN_READWRITE |
  71989. SQLITE_OPEN_CREATE |
  71990. SQLITE_OPEN_EXCLUSIVE |
  71991. SQLITE_OPEN_DELETEONCLOSE |
  71992. SQLITE_OPEN_TEMP_DB;
  71993. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  71994. if( rc!=SQLITE_OK ){
  71995. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  71996. "file for storing temporary tables");
  71997. pParse->rc = rc;
  71998. return 1;
  71999. }
  72000. db->aDb[1].pBt = pBt;
  72001. assert( db->aDb[1].pSchema );
  72002. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  72003. db->mallocFailed = 1;
  72004. return 1;
  72005. }
  72006. }
  72007. return 0;
  72008. }
  72009. /*
  72010. ** Generate VDBE code that will verify the schema cookie and start
  72011. ** a read-transaction for all named database files.
  72012. **
  72013. ** It is important that all schema cookies be verified and all
  72014. ** read transactions be started before anything else happens in
  72015. ** the VDBE program. But this routine can be called after much other
  72016. ** code has been generated. So here is what we do:
  72017. **
  72018. ** The first time this routine is called, we code an OP_Goto that
  72019. ** will jump to a subroutine at the end of the program. Then we
  72020. ** record every database that needs its schema verified in the
  72021. ** pParse->cookieMask field. Later, after all other code has been
  72022. ** generated, the subroutine that does the cookie verifications and
  72023. ** starts the transactions will be coded and the OP_Goto P2 value
  72024. ** will be made to point to that subroutine. The generation of the
  72025. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  72026. **
  72027. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  72028. ** schema on any databases. This can be used to position the OP_Goto
  72029. ** early in the code, before we know if any database tables will be used.
  72030. */
  72031. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  72032. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72033. #ifndef SQLITE_OMIT_TRIGGER
  72034. if( pToplevel!=pParse ){
  72035. /* This branch is taken if a trigger is currently being coded. In this
  72036. ** case, set cookieGoto to a non-zero value to show that this function
  72037. ** has been called. This is used by the sqlite3ExprCodeConstants()
  72038. ** function. */
  72039. pParse->cookieGoto = -1;
  72040. }
  72041. #endif
  72042. if( pToplevel->cookieGoto==0 ){
  72043. Vdbe *v = sqlite3GetVdbe(pToplevel);
  72044. if( v==0 ) return; /* This only happens if there was a prior error */
  72045. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  72046. }
  72047. if( iDb>=0 ){
  72048. sqlite3 *db = pToplevel->db;
  72049. yDbMask mask;
  72050. assert( iDb<db->nDb );
  72051. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  72052. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  72053. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72054. mask = ((yDbMask)1)<<iDb;
  72055. if( (pToplevel->cookieMask & mask)==0 ){
  72056. pToplevel->cookieMask |= mask;
  72057. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  72058. if( !OMIT_TEMPDB && iDb==1 ){
  72059. sqlite3OpenTempDatabase(pToplevel);
  72060. }
  72061. }
  72062. }
  72063. }
  72064. /*
  72065. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  72066. ** attached database. Otherwise, invoke it for the database named zDb only.
  72067. */
  72068. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  72069. sqlite3 *db = pParse->db;
  72070. int i;
  72071. for(i=0; i<db->nDb; i++){
  72072. Db *pDb = &db->aDb[i];
  72073. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  72074. sqlite3CodeVerifySchema(pParse, i);
  72075. }
  72076. }
  72077. }
  72078. /*
  72079. ** Generate VDBE code that prepares for doing an operation that
  72080. ** might change the database.
  72081. **
  72082. ** This routine starts a new transaction if we are not already within
  72083. ** a transaction. If we are already within a transaction, then a checkpoint
  72084. ** is set if the setStatement parameter is true. A checkpoint should
  72085. ** be set for operations that might fail (due to a constraint) part of
  72086. ** the way through and which will need to undo some writes without having to
  72087. ** rollback the whole transaction. For operations where all constraints
  72088. ** can be checked before any changes are made to the database, it is never
  72089. ** necessary to undo a write and the checkpoint should not be set.
  72090. */
  72091. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  72092. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72093. sqlite3CodeVerifySchema(pParse, iDb);
  72094. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  72095. pToplevel->isMultiWrite |= setStatement;
  72096. }
  72097. /*
  72098. ** Indicate that the statement currently under construction might write
  72099. ** more than one entry (example: deleting one row then inserting another,
  72100. ** inserting multiple rows in a table, or inserting a row and index entries.)
  72101. ** If an abort occurs after some of these writes have completed, then it will
  72102. ** be necessary to undo the completed writes.
  72103. */
  72104. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  72105. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72106. pToplevel->isMultiWrite = 1;
  72107. }
  72108. /*
  72109. ** The code generator calls this routine if is discovers that it is
  72110. ** possible to abort a statement prior to completion. In order to
  72111. ** perform this abort without corrupting the database, we need to make
  72112. ** sure that the statement is protected by a statement transaction.
  72113. **
  72114. ** Technically, we only need to set the mayAbort flag if the
  72115. ** isMultiWrite flag was previously set. There is a time dependency
  72116. ** such that the abort must occur after the multiwrite. This makes
  72117. ** some statements involving the REPLACE conflict resolution algorithm
  72118. ** go a little faster. But taking advantage of this time dependency
  72119. ** makes it more difficult to prove that the code is correct (in
  72120. ** particular, it prevents us from writing an effective
  72121. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  72122. ** to take the safe route and skip the optimization.
  72123. */
  72124. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  72125. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  72126. pToplevel->mayAbort = 1;
  72127. }
  72128. /*
  72129. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  72130. ** error. The onError parameter determines which (if any) of the statement
  72131. ** and/or current transaction is rolled back.
  72132. */
  72133. SQLITE_PRIVATE void sqlite3HaltConstraint(
  72134. Parse *pParse, /* Parsing context */
  72135. int errCode, /* extended error code */
  72136. int onError, /* Constraint type */
  72137. char *p4, /* Error message */
  72138. int p4type /* P4_STATIC or P4_TRANSIENT */
  72139. ){
  72140. Vdbe *v = sqlite3GetVdbe(pParse);
  72141. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  72142. if( onError==OE_Abort ){
  72143. sqlite3MayAbort(pParse);
  72144. }
  72145. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  72146. }
  72147. /*
  72148. ** Check to see if pIndex uses the collating sequence pColl. Return
  72149. ** true if it does and false if it does not.
  72150. */
  72151. #ifndef SQLITE_OMIT_REINDEX
  72152. static int collationMatch(const char *zColl, Index *pIndex){
  72153. int i;
  72154. assert( zColl!=0 );
  72155. for(i=0; i<pIndex->nColumn; i++){
  72156. const char *z = pIndex->azColl[i];
  72157. assert( z!=0 );
  72158. if( 0==sqlite3StrICmp(z, zColl) ){
  72159. return 1;
  72160. }
  72161. }
  72162. return 0;
  72163. }
  72164. #endif
  72165. /*
  72166. ** Recompute all indices of pTab that use the collating sequence pColl.
  72167. ** If pColl==0 then recompute all indices of pTab.
  72168. */
  72169. #ifndef SQLITE_OMIT_REINDEX
  72170. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  72171. Index *pIndex; /* An index associated with pTab */
  72172. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  72173. if( zColl==0 || collationMatch(zColl, pIndex) ){
  72174. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  72175. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72176. sqlite3RefillIndex(pParse, pIndex, -1);
  72177. }
  72178. }
  72179. }
  72180. #endif
  72181. /*
  72182. ** Recompute all indices of all tables in all databases where the
  72183. ** indices use the collating sequence pColl. If pColl==0 then recompute
  72184. ** all indices everywhere.
  72185. */
  72186. #ifndef SQLITE_OMIT_REINDEX
  72187. static void reindexDatabases(Parse *pParse, char const *zColl){
  72188. Db *pDb; /* A single database */
  72189. int iDb; /* The database index number */
  72190. sqlite3 *db = pParse->db; /* The database connection */
  72191. HashElem *k; /* For looping over tables in pDb */
  72192. Table *pTab; /* A table in the database */
  72193. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  72194. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  72195. assert( pDb!=0 );
  72196. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  72197. pTab = (Table*)sqliteHashData(k);
  72198. reindexTable(pParse, pTab, zColl);
  72199. }
  72200. }
  72201. }
  72202. #endif
  72203. /*
  72204. ** Generate code for the REINDEX command.
  72205. **
  72206. ** REINDEX -- 1
  72207. ** REINDEX <collation> -- 2
  72208. ** REINDEX ?<database>.?<tablename> -- 3
  72209. ** REINDEX ?<database>.?<indexname> -- 4
  72210. **
  72211. ** Form 1 causes all indices in all attached databases to be rebuilt.
  72212. ** Form 2 rebuilds all indices in all databases that use the named
  72213. ** collating function. Forms 3 and 4 rebuild the named index or all
  72214. ** indices associated with the named table.
  72215. */
  72216. #ifndef SQLITE_OMIT_REINDEX
  72217. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  72218. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  72219. char *z; /* Name of a table or index */
  72220. const char *zDb; /* Name of the database */
  72221. Table *pTab; /* A table in the database */
  72222. Index *pIndex; /* An index associated with pTab */
  72223. int iDb; /* The database index number */
  72224. sqlite3 *db = pParse->db; /* The database connection */
  72225. Token *pObjName; /* Name of the table or index to be reindexed */
  72226. /* Read the database schema. If an error occurs, leave an error message
  72227. ** and code in pParse and return NULL. */
  72228. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  72229. return;
  72230. }
  72231. if( pName1==0 ){
  72232. reindexDatabases(pParse, 0);
  72233. return;
  72234. }else if( NEVER(pName2==0) || pName2->z==0 ){
  72235. char *zColl;
  72236. assert( pName1->z );
  72237. zColl = sqlite3NameFromToken(pParse->db, pName1);
  72238. if( !zColl ) return;
  72239. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  72240. if( pColl ){
  72241. reindexDatabases(pParse, zColl);
  72242. sqlite3DbFree(db, zColl);
  72243. return;
  72244. }
  72245. sqlite3DbFree(db, zColl);
  72246. }
  72247. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  72248. if( iDb<0 ) return;
  72249. z = sqlite3NameFromToken(db, pObjName);
  72250. if( z==0 ) return;
  72251. zDb = db->aDb[iDb].zName;
  72252. pTab = sqlite3FindTable(db, z, zDb);
  72253. if( pTab ){
  72254. reindexTable(pParse, pTab, 0);
  72255. sqlite3DbFree(db, z);
  72256. return;
  72257. }
  72258. pIndex = sqlite3FindIndex(db, z, zDb);
  72259. sqlite3DbFree(db, z);
  72260. if( pIndex ){
  72261. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72262. sqlite3RefillIndex(pParse, pIndex, -1);
  72263. return;
  72264. }
  72265. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  72266. }
  72267. #endif
  72268. /*
  72269. ** Return a dynamicly allocated KeyInfo structure that can be used
  72270. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  72271. **
  72272. ** If successful, a pointer to the new structure is returned. In this case
  72273. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  72274. ** pointer. If an error occurs (out of memory or missing collation
  72275. ** sequence), NULL is returned and the state of pParse updated to reflect
  72276. ** the error.
  72277. */
  72278. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  72279. int i;
  72280. int nCol = pIdx->nColumn;
  72281. KeyInfo *pKey;
  72282. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  72283. if( pKey ){
  72284. for(i=0; i<nCol; i++){
  72285. char *zColl = pIdx->azColl[i];
  72286. assert( zColl );
  72287. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  72288. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  72289. }
  72290. }
  72291. if( pParse->nErr ){
  72292. sqlite3DbFree(pParse->db, pKey);
  72293. pKey = 0;
  72294. }
  72295. return pKey;
  72296. }
  72297. /************** End of build.c ***********************************************/
  72298. /************** Begin file callback.c ****************************************/
  72299. /*
  72300. ** 2005 May 23
  72301. **
  72302. ** The author disclaims copyright to this source code. In place of
  72303. ** a legal notice, here is a blessing:
  72304. **
  72305. ** May you do good and not evil.
  72306. ** May you find forgiveness for yourself and forgive others.
  72307. ** May you share freely, never taking more than you give.
  72308. **
  72309. *************************************************************************
  72310. **
  72311. ** This file contains functions used to access the internal hash tables
  72312. ** of user defined functions and collation sequences.
  72313. */
  72314. /*
  72315. ** Invoke the 'collation needed' callback to request a collation sequence
  72316. ** in the encoding enc of name zName, length nName.
  72317. */
  72318. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  72319. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  72320. if( db->xCollNeeded ){
  72321. char *zExternal = sqlite3DbStrDup(db, zName);
  72322. if( !zExternal ) return;
  72323. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  72324. sqlite3DbFree(db, zExternal);
  72325. }
  72326. #ifndef SQLITE_OMIT_UTF16
  72327. if( db->xCollNeeded16 ){
  72328. char const *zExternal;
  72329. sqlite3_value *pTmp = sqlite3ValueNew(db);
  72330. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  72331. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  72332. if( zExternal ){
  72333. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  72334. }
  72335. sqlite3ValueFree(pTmp);
  72336. }
  72337. #endif
  72338. }
  72339. /*
  72340. ** This routine is called if the collation factory fails to deliver a
  72341. ** collation function in the best encoding but there may be other versions
  72342. ** of this collation function (for other text encodings) available. Use one
  72343. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  72344. ** possible.
  72345. */
  72346. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  72347. CollSeq *pColl2;
  72348. char *z = pColl->zName;
  72349. int i;
  72350. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  72351. for(i=0; i<3; i++){
  72352. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  72353. if( pColl2->xCmp!=0 ){
  72354. memcpy(pColl, pColl2, sizeof(CollSeq));
  72355. pColl->xDel = 0; /* Do not copy the destructor */
  72356. return SQLITE_OK;
  72357. }
  72358. }
  72359. return SQLITE_ERROR;
  72360. }
  72361. /*
  72362. ** This function is responsible for invoking the collation factory callback
  72363. ** or substituting a collation sequence of a different encoding when the
  72364. ** requested collation sequence is not available in the desired encoding.
  72365. **
  72366. ** If it is not NULL, then pColl must point to the database native encoding
  72367. ** collation sequence with name zName, length nName.
  72368. **
  72369. ** The return value is either the collation sequence to be used in database
  72370. ** db for collation type name zName, length nName, or NULL, if no collation
  72371. ** sequence can be found. If no collation is found, leave an error message.
  72372. **
  72373. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  72374. */
  72375. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  72376. Parse *pParse, /* Parsing context */
  72377. u8 enc, /* The desired encoding for the collating sequence */
  72378. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  72379. const char *zName /* Collating sequence name */
  72380. ){
  72381. CollSeq *p;
  72382. sqlite3 *db = pParse->db;
  72383. p = pColl;
  72384. if( !p ){
  72385. p = sqlite3FindCollSeq(db, enc, zName, 0);
  72386. }
  72387. if( !p || !p->xCmp ){
  72388. /* No collation sequence of this type for this encoding is registered.
  72389. ** Call the collation factory to see if it can supply us with one.
  72390. */
  72391. callCollNeeded(db, enc, zName);
  72392. p = sqlite3FindCollSeq(db, enc, zName, 0);
  72393. }
  72394. if( p && !p->xCmp && synthCollSeq(db, p) ){
  72395. p = 0;
  72396. }
  72397. assert( !p || p->xCmp );
  72398. if( p==0 ){
  72399. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  72400. }
  72401. return p;
  72402. }
  72403. /*
  72404. ** This routine is called on a collation sequence before it is used to
  72405. ** check that it is defined. An undefined collation sequence exists when
  72406. ** a database is loaded that contains references to collation sequences
  72407. ** that have not been defined by sqlite3_create_collation() etc.
  72408. **
  72409. ** If required, this routine calls the 'collation needed' callback to
  72410. ** request a definition of the collating sequence. If this doesn't work,
  72411. ** an equivalent collating sequence that uses a text encoding different
  72412. ** from the main database is substituted, if one is available.
  72413. */
  72414. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  72415. if( pColl ){
  72416. const char *zName = pColl->zName;
  72417. sqlite3 *db = pParse->db;
  72418. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  72419. if( !p ){
  72420. return SQLITE_ERROR;
  72421. }
  72422. assert( p==pColl );
  72423. }
  72424. return SQLITE_OK;
  72425. }
  72426. /*
  72427. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  72428. ** specified by zName and nName is not found and parameter 'create' is
  72429. ** true, then create a new entry. Otherwise return NULL.
  72430. **
  72431. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  72432. ** array of three CollSeq structures. The first is the collation sequence
  72433. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  72434. **
  72435. ** Stored immediately after the three collation sequences is a copy of
  72436. ** the collation sequence name. A pointer to this string is stored in
  72437. ** each collation sequence structure.
  72438. */
  72439. static CollSeq *findCollSeqEntry(
  72440. sqlite3 *db, /* Database connection */
  72441. const char *zName, /* Name of the collating sequence */
  72442. int create /* Create a new entry if true */
  72443. ){
  72444. CollSeq *pColl;
  72445. int nName = sqlite3Strlen30(zName);
  72446. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  72447. if( 0==pColl && create ){
  72448. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  72449. if( pColl ){
  72450. CollSeq *pDel = 0;
  72451. pColl[0].zName = (char*)&pColl[3];
  72452. pColl[0].enc = SQLITE_UTF8;
  72453. pColl[1].zName = (char*)&pColl[3];
  72454. pColl[1].enc = SQLITE_UTF16LE;
  72455. pColl[2].zName = (char*)&pColl[3];
  72456. pColl[2].enc = SQLITE_UTF16BE;
  72457. memcpy(pColl[0].zName, zName, nName);
  72458. pColl[0].zName[nName] = 0;
  72459. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  72460. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  72461. ** return the pColl pointer to be deleted (because it wasn't added
  72462. ** to the hash table).
  72463. */
  72464. assert( pDel==0 || pDel==pColl );
  72465. if( pDel!=0 ){
  72466. db->mallocFailed = 1;
  72467. sqlite3DbFree(db, pDel);
  72468. pColl = 0;
  72469. }
  72470. }
  72471. }
  72472. return pColl;
  72473. }
  72474. /*
  72475. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  72476. ** Return the CollSeq* pointer for the collation sequence named zName
  72477. ** for the encoding 'enc' from the database 'db'.
  72478. **
  72479. ** If the entry specified is not found and 'create' is true, then create a
  72480. ** new entry. Otherwise return NULL.
  72481. **
  72482. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  72483. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  72484. ** if necessary and generates an error message if the collating sequence
  72485. ** cannot be found.
  72486. **
  72487. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  72488. */
  72489. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  72490. sqlite3 *db,
  72491. u8 enc,
  72492. const char *zName,
  72493. int create
  72494. ){
  72495. CollSeq *pColl;
  72496. if( zName ){
  72497. pColl = findCollSeqEntry(db, zName, create);
  72498. }else{
  72499. pColl = db->pDfltColl;
  72500. }
  72501. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  72502. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  72503. if( pColl ) pColl += enc-1;
  72504. return pColl;
  72505. }
  72506. /* During the search for the best function definition, this procedure
  72507. ** is called to test how well the function passed as the first argument
  72508. ** matches the request for a function with nArg arguments in a system
  72509. ** that uses encoding enc. The value returned indicates how well the
  72510. ** request is matched. A higher value indicates a better match.
  72511. **
  72512. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  72513. ** is also -1. In other words, we are searching for a function that
  72514. ** takes a variable number of arguments.
  72515. **
  72516. ** If nArg is -2 that means that we are searching for any function
  72517. ** regardless of the number of arguments it uses, so return a positive
  72518. ** match score for any
  72519. **
  72520. ** The returned value is always between 0 and 6, as follows:
  72521. **
  72522. ** 0: Not a match.
  72523. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  72524. ** 2: UTF16 byte order change required and function takes any number of args.
  72525. ** 3: encoding matches and function takes any number of arguments
  72526. ** 4: UTF8/16 conversion required - argument count matches exactly
  72527. ** 5: UTF16 byte order conversion required - argument count matches exactly
  72528. ** 6: Perfect match: encoding and argument count match exactly.
  72529. **
  72530. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  72531. ** a perfect match and any function with both xStep and xFunc NULL is
  72532. ** a non-match.
  72533. */
  72534. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  72535. static int matchQuality(
  72536. FuncDef *p, /* The function we are evaluating for match quality */
  72537. int nArg, /* Desired number of arguments. (-1)==any */
  72538. u8 enc /* Desired text encoding */
  72539. ){
  72540. int match;
  72541. /* nArg of -2 is a special case */
  72542. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  72543. /* Wrong number of arguments means "no match" */
  72544. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  72545. /* Give a better score to a function with a specific number of arguments
  72546. ** than to function that accepts any number of arguments. */
  72547. if( p->nArg==nArg ){
  72548. match = 4;
  72549. }else{
  72550. match = 1;
  72551. }
  72552. /* Bonus points if the text encoding matches */
  72553. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  72554. match += 2; /* Exact encoding match */
  72555. }else if( (enc & p->funcFlags & 2)!=0 ){
  72556. match += 1; /* Both are UTF16, but with different byte orders */
  72557. }
  72558. return match;
  72559. }
  72560. /*
  72561. ** Search a FuncDefHash for a function with the given name. Return
  72562. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  72563. */
  72564. static FuncDef *functionSearch(
  72565. FuncDefHash *pHash, /* Hash table to search */
  72566. int h, /* Hash of the name */
  72567. const char *zFunc, /* Name of function */
  72568. int nFunc /* Number of bytes in zFunc */
  72569. ){
  72570. FuncDef *p;
  72571. for(p=pHash->a[h]; p; p=p->pHash){
  72572. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  72573. return p;
  72574. }
  72575. }
  72576. return 0;
  72577. }
  72578. /*
  72579. ** Insert a new FuncDef into a FuncDefHash hash table.
  72580. */
  72581. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  72582. FuncDefHash *pHash, /* The hash table into which to insert */
  72583. FuncDef *pDef /* The function definition to insert */
  72584. ){
  72585. FuncDef *pOther;
  72586. int nName = sqlite3Strlen30(pDef->zName);
  72587. u8 c1 = (u8)pDef->zName[0];
  72588. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  72589. pOther = functionSearch(pHash, h, pDef->zName, nName);
  72590. if( pOther ){
  72591. assert( pOther!=pDef && pOther->pNext!=pDef );
  72592. pDef->pNext = pOther->pNext;
  72593. pOther->pNext = pDef;
  72594. }else{
  72595. pDef->pNext = 0;
  72596. pDef->pHash = pHash->a[h];
  72597. pHash->a[h] = pDef;
  72598. }
  72599. }
  72600. /*
  72601. ** Locate a user function given a name, a number of arguments and a flag
  72602. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  72603. ** pointer to the FuncDef structure that defines that function, or return
  72604. ** NULL if the function does not exist.
  72605. **
  72606. ** If the createFlag argument is true, then a new (blank) FuncDef
  72607. ** structure is created and liked into the "db" structure if a
  72608. ** no matching function previously existed.
  72609. **
  72610. ** If nArg is -2, then the first valid function found is returned. A
  72611. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  72612. ** case is used to see if zName is a valid function name for some number
  72613. ** of arguments. If nArg is -2, then createFlag must be 0.
  72614. **
  72615. ** If createFlag is false, then a function with the required name and
  72616. ** number of arguments may be returned even if the eTextRep flag does not
  72617. ** match that requested.
  72618. */
  72619. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  72620. sqlite3 *db, /* An open database */
  72621. const char *zName, /* Name of the function. Not null-terminated */
  72622. int nName, /* Number of characters in the name */
  72623. int nArg, /* Number of arguments. -1 means any number */
  72624. u8 enc, /* Preferred text encoding */
  72625. u8 createFlag /* Create new entry if true and does not otherwise exist */
  72626. ){
  72627. FuncDef *p; /* Iterator variable */
  72628. FuncDef *pBest = 0; /* Best match found so far */
  72629. int bestScore = 0; /* Score of best match */
  72630. int h; /* Hash value */
  72631. assert( nArg>=(-2) );
  72632. assert( nArg>=(-1) || createFlag==0 );
  72633. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  72634. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  72635. /* First search for a match amongst the application-defined functions.
  72636. */
  72637. p = functionSearch(&db->aFunc, h, zName, nName);
  72638. while( p ){
  72639. int score = matchQuality(p, nArg, enc);
  72640. if( score>bestScore ){
  72641. pBest = p;
  72642. bestScore = score;
  72643. }
  72644. p = p->pNext;
  72645. }
  72646. /* If no match is found, search the built-in functions.
  72647. **
  72648. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  72649. ** functions even if a prior app-defined function was found. And give
  72650. ** priority to built-in functions.
  72651. **
  72652. ** Except, if createFlag is true, that means that we are trying to
  72653. ** install a new function. Whatever FuncDef structure is returned it will
  72654. ** have fields overwritten with new information appropriate for the
  72655. ** new function. But the FuncDefs for built-in functions are read-only.
  72656. ** So we must not search for built-ins when creating a new function.
  72657. */
  72658. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  72659. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  72660. bestScore = 0;
  72661. p = functionSearch(pHash, h, zName, nName);
  72662. while( p ){
  72663. int score = matchQuality(p, nArg, enc);
  72664. if( score>bestScore ){
  72665. pBest = p;
  72666. bestScore = score;
  72667. }
  72668. p = p->pNext;
  72669. }
  72670. }
  72671. /* If the createFlag parameter is true and the search did not reveal an
  72672. ** exact match for the name, number of arguments and encoding, then add a
  72673. ** new entry to the hash table and return it.
  72674. */
  72675. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  72676. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  72677. pBest->zName = (char *)&pBest[1];
  72678. pBest->nArg = (u16)nArg;
  72679. pBest->funcFlags = enc;
  72680. memcpy(pBest->zName, zName, nName);
  72681. pBest->zName[nName] = 0;
  72682. sqlite3FuncDefInsert(&db->aFunc, pBest);
  72683. }
  72684. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  72685. return pBest;
  72686. }
  72687. return 0;
  72688. }
  72689. /*
  72690. ** Free all resources held by the schema structure. The void* argument points
  72691. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  72692. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  72693. ** of the schema hash tables).
  72694. **
  72695. ** The Schema.cache_size variable is not cleared.
  72696. */
  72697. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  72698. Hash temp1;
  72699. Hash temp2;
  72700. HashElem *pElem;
  72701. Schema *pSchema = (Schema *)p;
  72702. temp1 = pSchema->tblHash;
  72703. temp2 = pSchema->trigHash;
  72704. sqlite3HashInit(&pSchema->trigHash);
  72705. sqlite3HashClear(&pSchema->idxHash);
  72706. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  72707. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  72708. }
  72709. sqlite3HashClear(&temp2);
  72710. sqlite3HashInit(&pSchema->tblHash);
  72711. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  72712. Table *pTab = sqliteHashData(pElem);
  72713. sqlite3DeleteTable(0, pTab);
  72714. }
  72715. sqlite3HashClear(&temp1);
  72716. sqlite3HashClear(&pSchema->fkeyHash);
  72717. pSchema->pSeqTab = 0;
  72718. if( pSchema->flags & DB_SchemaLoaded ){
  72719. pSchema->iGeneration++;
  72720. pSchema->flags &= ~DB_SchemaLoaded;
  72721. }
  72722. }
  72723. /*
  72724. ** Find and return the schema associated with a BTree. Create
  72725. ** a new one if necessary.
  72726. */
  72727. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  72728. Schema * p;
  72729. if( pBt ){
  72730. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  72731. }else{
  72732. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  72733. }
  72734. if( !p ){
  72735. db->mallocFailed = 1;
  72736. }else if ( 0==p->file_format ){
  72737. sqlite3HashInit(&p->tblHash);
  72738. sqlite3HashInit(&p->idxHash);
  72739. sqlite3HashInit(&p->trigHash);
  72740. sqlite3HashInit(&p->fkeyHash);
  72741. p->enc = SQLITE_UTF8;
  72742. }
  72743. return p;
  72744. }
  72745. /************** End of callback.c ********************************************/
  72746. /************** Begin file delete.c ******************************************/
  72747. /*
  72748. ** 2001 September 15
  72749. **
  72750. ** The author disclaims copyright to this source code. In place of
  72751. ** a legal notice, here is a blessing:
  72752. **
  72753. ** May you do good and not evil.
  72754. ** May you find forgiveness for yourself and forgive others.
  72755. ** May you share freely, never taking more than you give.
  72756. **
  72757. *************************************************************************
  72758. ** This file contains C code routines that are called by the parser
  72759. ** in order to generate code for DELETE FROM statements.
  72760. */
  72761. /*
  72762. ** While a SrcList can in general represent multiple tables and subqueries
  72763. ** (as in the FROM clause of a SELECT statement) in this case it contains
  72764. ** the name of a single table, as one might find in an INSERT, DELETE,
  72765. ** or UPDATE statement. Look up that table in the symbol table and
  72766. ** return a pointer. Set an error message and return NULL if the table
  72767. ** name is not found or if any other error occurs.
  72768. **
  72769. ** The following fields are initialized appropriate in pSrc:
  72770. **
  72771. ** pSrc->a[0].pTab Pointer to the Table object
  72772. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  72773. **
  72774. */
  72775. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  72776. struct SrcList_item *pItem = pSrc->a;
  72777. Table *pTab;
  72778. assert( pItem && pSrc->nSrc==1 );
  72779. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  72780. sqlite3DeleteTable(pParse->db, pItem->pTab);
  72781. pItem->pTab = pTab;
  72782. if( pTab ){
  72783. pTab->nRef++;
  72784. }
  72785. if( sqlite3IndexedByLookup(pParse, pItem) ){
  72786. pTab = 0;
  72787. }
  72788. return pTab;
  72789. }
  72790. /*
  72791. ** Check to make sure the given table is writable. If it is not
  72792. ** writable, generate an error message and return 1. If it is
  72793. ** writable return 0;
  72794. */
  72795. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  72796. /* A table is not writable under the following circumstances:
  72797. **
  72798. ** 1) It is a virtual table and no implementation of the xUpdate method
  72799. ** has been provided, or
  72800. ** 2) It is a system table (i.e. sqlite_master), this call is not
  72801. ** part of a nested parse and writable_schema pragma has not
  72802. ** been specified.
  72803. **
  72804. ** In either case leave an error message in pParse and return non-zero.
  72805. */
  72806. if( ( IsVirtual(pTab)
  72807. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  72808. || ( (pTab->tabFlags & TF_Readonly)!=0
  72809. && (pParse->db->flags & SQLITE_WriteSchema)==0
  72810. && pParse->nested==0 )
  72811. ){
  72812. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  72813. return 1;
  72814. }
  72815. #ifndef SQLITE_OMIT_VIEW
  72816. if( !viewOk && pTab->pSelect ){
  72817. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  72818. return 1;
  72819. }
  72820. #endif
  72821. return 0;
  72822. }
  72823. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  72824. /*
  72825. ** Evaluate a view and store its result in an ephemeral table. The
  72826. ** pWhere argument is an optional WHERE clause that restricts the
  72827. ** set of rows in the view that are to be added to the ephemeral table.
  72828. */
  72829. SQLITE_PRIVATE void sqlite3MaterializeView(
  72830. Parse *pParse, /* Parsing context */
  72831. Table *pView, /* View definition */
  72832. Expr *pWhere, /* Optional WHERE clause to be added */
  72833. int iCur /* Cursor number for ephemerial table */
  72834. ){
  72835. SelectDest dest;
  72836. Select *pSel;
  72837. SrcList *pFrom;
  72838. sqlite3 *db = pParse->db;
  72839. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  72840. pWhere = sqlite3ExprDup(db, pWhere, 0);
  72841. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  72842. if( pFrom ){
  72843. assert( pFrom->nSrc==1 );
  72844. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  72845. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  72846. assert( pFrom->a[0].pOn==0 );
  72847. assert( pFrom->a[0].pUsing==0 );
  72848. }
  72849. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  72850. if( pSel ) pSel->selFlags |= SF_Materialize;
  72851. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  72852. sqlite3Select(pParse, pSel, &dest);
  72853. sqlite3SelectDelete(db, pSel);
  72854. }
  72855. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  72856. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  72857. /*
  72858. ** Generate an expression tree to implement the WHERE, ORDER BY,
  72859. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  72860. **
  72861. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  72862. ** \__________________________/
  72863. ** pLimitWhere (pInClause)
  72864. */
  72865. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  72866. Parse *pParse, /* The parser context */
  72867. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  72868. Expr *pWhere, /* The WHERE clause. May be null */
  72869. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  72870. Expr *pLimit, /* The LIMIT clause. May be null */
  72871. Expr *pOffset, /* The OFFSET clause. May be null */
  72872. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  72873. ){
  72874. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  72875. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  72876. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  72877. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  72878. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  72879. Select *pSelect = NULL; /* Complete SELECT tree */
  72880. /* Check that there isn't an ORDER BY without a LIMIT clause.
  72881. */
  72882. if( pOrderBy && (pLimit == 0) ) {
  72883. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  72884. goto limit_where_cleanup_2;
  72885. }
  72886. /* We only need to generate a select expression if there
  72887. ** is a limit/offset term to enforce.
  72888. */
  72889. if( pLimit == 0 ) {
  72890. /* if pLimit is null, pOffset will always be null as well. */
  72891. assert( pOffset == 0 );
  72892. return pWhere;
  72893. }
  72894. /* Generate a select expression tree to enforce the limit/offset
  72895. ** term for the DELETE or UPDATE statement. For example:
  72896. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  72897. ** becomes:
  72898. ** DELETE FROM table_a WHERE rowid IN (
  72899. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  72900. ** );
  72901. */
  72902. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  72903. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  72904. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  72905. if( pEList == 0 ) goto limit_where_cleanup_2;
  72906. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  72907. ** and the SELECT subtree. */
  72908. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  72909. if( pSelectSrc == 0 ) {
  72910. sqlite3ExprListDelete(pParse->db, pEList);
  72911. goto limit_where_cleanup_2;
  72912. }
  72913. /* generate the SELECT expression tree. */
  72914. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  72915. pOrderBy,0,pLimit,pOffset);
  72916. if( pSelect == 0 ) return 0;
  72917. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  72918. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  72919. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  72920. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  72921. if( pInClause == 0 ) goto limit_where_cleanup_1;
  72922. pInClause->x.pSelect = pSelect;
  72923. pInClause->flags |= EP_xIsSelect;
  72924. sqlite3ExprSetHeight(pParse, pInClause);
  72925. return pInClause;
  72926. /* something went wrong. clean up anything allocated. */
  72927. limit_where_cleanup_1:
  72928. sqlite3SelectDelete(pParse->db, pSelect);
  72929. return 0;
  72930. limit_where_cleanup_2:
  72931. sqlite3ExprDelete(pParse->db, pWhere);
  72932. sqlite3ExprListDelete(pParse->db, pOrderBy);
  72933. sqlite3ExprDelete(pParse->db, pLimit);
  72934. sqlite3ExprDelete(pParse->db, pOffset);
  72935. return 0;
  72936. }
  72937. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  72938. /*
  72939. ** Generate code for a DELETE FROM statement.
  72940. **
  72941. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  72942. ** \________/ \________________/
  72943. ** pTabList pWhere
  72944. */
  72945. SQLITE_PRIVATE void sqlite3DeleteFrom(
  72946. Parse *pParse, /* The parser context */
  72947. SrcList *pTabList, /* The table from which we should delete things */
  72948. Expr *pWhere /* The WHERE clause. May be null */
  72949. ){
  72950. Vdbe *v; /* The virtual database engine */
  72951. Table *pTab; /* The table from which records will be deleted */
  72952. const char *zDb; /* Name of database holding pTab */
  72953. int end, addr = 0; /* A couple addresses of generated code */
  72954. int i; /* Loop counter */
  72955. WhereInfo *pWInfo; /* Information about the WHERE clause */
  72956. Index *pIdx; /* For looping over indices of the table */
  72957. int iCur; /* VDBE Cursor number for pTab */
  72958. sqlite3 *db; /* Main database structure */
  72959. AuthContext sContext; /* Authorization context */
  72960. NameContext sNC; /* Name context to resolve expressions in */
  72961. int iDb; /* Database number */
  72962. int memCnt = -1; /* Memory cell used for change counting */
  72963. int rcauth; /* Value returned by authorization callback */
  72964. #ifndef SQLITE_OMIT_TRIGGER
  72965. int isView; /* True if attempting to delete from a view */
  72966. Trigger *pTrigger; /* List of table triggers, if required */
  72967. #endif
  72968. memset(&sContext, 0, sizeof(sContext));
  72969. db = pParse->db;
  72970. if( pParse->nErr || db->mallocFailed ){
  72971. goto delete_from_cleanup;
  72972. }
  72973. assert( pTabList->nSrc==1 );
  72974. /* Locate the table which we want to delete. This table has to be
  72975. ** put in an SrcList structure because some of the subroutines we
  72976. ** will be calling are designed to work with multiple tables and expect
  72977. ** an SrcList* parameter instead of just a Table* parameter.
  72978. */
  72979. pTab = sqlite3SrcListLookup(pParse, pTabList);
  72980. if( pTab==0 ) goto delete_from_cleanup;
  72981. /* Figure out if we have any triggers and if the table being
  72982. ** deleted from is a view
  72983. */
  72984. #ifndef SQLITE_OMIT_TRIGGER
  72985. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  72986. isView = pTab->pSelect!=0;
  72987. #else
  72988. # define pTrigger 0
  72989. # define isView 0
  72990. #endif
  72991. #ifdef SQLITE_OMIT_VIEW
  72992. # undef isView
  72993. # define isView 0
  72994. #endif
  72995. /* If pTab is really a view, make sure it has been initialized.
  72996. */
  72997. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  72998. goto delete_from_cleanup;
  72999. }
  73000. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  73001. goto delete_from_cleanup;
  73002. }
  73003. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73004. assert( iDb<db->nDb );
  73005. zDb = db->aDb[iDb].zName;
  73006. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  73007. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  73008. if( rcauth==SQLITE_DENY ){
  73009. goto delete_from_cleanup;
  73010. }
  73011. assert(!isView || pTrigger);
  73012. /* Assign cursor number to the table and all its indices.
  73013. */
  73014. assert( pTabList->nSrc==1 );
  73015. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  73016. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73017. pParse->nTab++;
  73018. }
  73019. /* Start the view context
  73020. */
  73021. if( isView ){
  73022. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  73023. }
  73024. /* Begin generating code.
  73025. */
  73026. v = sqlite3GetVdbe(pParse);
  73027. if( v==0 ){
  73028. goto delete_from_cleanup;
  73029. }
  73030. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  73031. sqlite3BeginWriteOperation(pParse, 1, iDb);
  73032. /* If we are trying to delete from a view, realize that view into
  73033. ** a ephemeral table.
  73034. */
  73035. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  73036. if( isView ){
  73037. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  73038. }
  73039. #endif
  73040. /* Resolve the column names in the WHERE clause.
  73041. */
  73042. memset(&sNC, 0, sizeof(sNC));
  73043. sNC.pParse = pParse;
  73044. sNC.pSrcList = pTabList;
  73045. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  73046. goto delete_from_cleanup;
  73047. }
  73048. /* Initialize the counter of the number of rows deleted, if
  73049. ** we are counting rows.
  73050. */
  73051. if( db->flags & SQLITE_CountRows ){
  73052. memCnt = ++pParse->nMem;
  73053. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  73054. }
  73055. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  73056. /* Special case: A DELETE without a WHERE clause deletes everything.
  73057. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  73058. ** this optimization caused the row change count (the value returned by
  73059. ** API function sqlite3_count_changes) to be set incorrectly. */
  73060. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  73061. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  73062. ){
  73063. assert( !isView );
  73064. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  73065. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  73066. pTab->zName, P4_STATIC);
  73067. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73068. assert( pIdx->pSchema==pTab->pSchema );
  73069. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  73070. }
  73071. }else
  73072. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  73073. /* The usual case: There is a WHERE clause so we have to scan through
  73074. ** the table and pick which records to delete.
  73075. */
  73076. {
  73077. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  73078. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  73079. int regRowid; /* Actual register containing rowids */
  73080. /* Collect rowids of every row to be deleted.
  73081. */
  73082. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  73083. pWInfo = sqlite3WhereBegin(
  73084. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  73085. );
  73086. if( pWInfo==0 ) goto delete_from_cleanup;
  73087. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  73088. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  73089. if( db->flags & SQLITE_CountRows ){
  73090. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  73091. }
  73092. sqlite3WhereEnd(pWInfo);
  73093. /* Delete every item whose key was written to the list during the
  73094. ** database scan. We have to delete items after the scan is complete
  73095. ** because deleting an item can change the scan order. */
  73096. end = sqlite3VdbeMakeLabel(v);
  73097. /* Unless this is a view, open cursors for the table we are
  73098. ** deleting from and all its indices. If this is a view, then the
  73099. ** only effect this statement has is to fire the INSTEAD OF
  73100. ** triggers. */
  73101. if( !isView ){
  73102. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  73103. }
  73104. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  73105. /* Delete the row */
  73106. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73107. if( IsVirtual(pTab) ){
  73108. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  73109. sqlite3VtabMakeWritable(pParse, pTab);
  73110. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  73111. sqlite3VdbeChangeP5(v, OE_Abort);
  73112. sqlite3MayAbort(pParse);
  73113. }else
  73114. #endif
  73115. {
  73116. int count = (pParse->nested==0); /* True to count changes */
  73117. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  73118. }
  73119. /* End of the delete loop */
  73120. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  73121. sqlite3VdbeResolveLabel(v, end);
  73122. /* Close the cursors open on the table and its indexes. */
  73123. if( !isView && !IsVirtual(pTab) ){
  73124. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  73125. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  73126. }
  73127. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  73128. }
  73129. }
  73130. /* Update the sqlite_sequence table by storing the content of the
  73131. ** maximum rowid counter values recorded while inserting into
  73132. ** autoincrement tables.
  73133. */
  73134. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  73135. sqlite3AutoincrementEnd(pParse);
  73136. }
  73137. /* Return the number of rows that were deleted. If this routine is
  73138. ** generating code because of a call to sqlite3NestedParse(), do not
  73139. ** invoke the callback function.
  73140. */
  73141. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  73142. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  73143. sqlite3VdbeSetNumCols(v, 1);
  73144. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  73145. }
  73146. delete_from_cleanup:
  73147. sqlite3AuthContextPop(&sContext);
  73148. sqlite3SrcListDelete(db, pTabList);
  73149. sqlite3ExprDelete(db, pWhere);
  73150. return;
  73151. }
  73152. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  73153. ** thely may interfere with compilation of other functions in this file
  73154. ** (or in another file, if this file becomes part of the amalgamation). */
  73155. #ifdef isView
  73156. #undef isView
  73157. #endif
  73158. #ifdef pTrigger
  73159. #undef pTrigger
  73160. #endif
  73161. /*
  73162. ** This routine generates VDBE code that causes a single row of a
  73163. ** single table to be deleted.
  73164. **
  73165. ** The VDBE must be in a particular state when this routine is called.
  73166. ** These are the requirements:
  73167. **
  73168. ** 1. A read/write cursor pointing to pTab, the table containing the row
  73169. ** to be deleted, must be opened as cursor number $iCur.
  73170. **
  73171. ** 2. Read/write cursors for all indices of pTab must be open as
  73172. ** cursor number base+i for the i-th index.
  73173. **
  73174. ** 3. The record number of the row to be deleted must be stored in
  73175. ** memory cell iRowid.
  73176. **
  73177. ** This routine generates code to remove both the table record and all
  73178. ** index entries that point to that record.
  73179. */
  73180. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  73181. Parse *pParse, /* Parsing context */
  73182. Table *pTab, /* Table containing the row to be deleted */
  73183. int iCur, /* Cursor number for the table */
  73184. int iRowid, /* Memory cell that contains the rowid to delete */
  73185. int count, /* If non-zero, increment the row change counter */
  73186. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  73187. int onconf /* Default ON CONFLICT policy for triggers */
  73188. ){
  73189. Vdbe *v = pParse->pVdbe; /* Vdbe */
  73190. int iOld = 0; /* First register in OLD.* array */
  73191. int iLabel; /* Label resolved to end of generated code */
  73192. /* Vdbe is guaranteed to have been allocated by this stage. */
  73193. assert( v );
  73194. /* Seek cursor iCur to the row to delete. If this row no longer exists
  73195. ** (this can happen if a trigger program has already deleted it), do
  73196. ** not attempt to delete it or fire any DELETE triggers. */
  73197. iLabel = sqlite3VdbeMakeLabel(v);
  73198. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  73199. /* If there are any triggers to fire, allocate a range of registers to
  73200. ** use for the old.* references in the triggers. */
  73201. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  73202. u32 mask; /* Mask of OLD.* columns in use */
  73203. int iCol; /* Iterator used while populating OLD.* */
  73204. /* TODO: Could use temporary registers here. Also could attempt to
  73205. ** avoid copying the contents of the rowid register. */
  73206. mask = sqlite3TriggerColmask(
  73207. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  73208. );
  73209. mask |= sqlite3FkOldmask(pParse, pTab);
  73210. iOld = pParse->nMem+1;
  73211. pParse->nMem += (1 + pTab->nCol);
  73212. /* Populate the OLD.* pseudo-table register array. These values will be
  73213. ** used by any BEFORE and AFTER triggers that exist. */
  73214. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  73215. for(iCol=0; iCol<pTab->nCol; iCol++){
  73216. if( mask==0xffffffff || mask&(1<<iCol) ){
  73217. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  73218. }
  73219. }
  73220. /* Invoke BEFORE DELETE trigger programs. */
  73221. sqlite3CodeRowTrigger(pParse, pTrigger,
  73222. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  73223. );
  73224. /* Seek the cursor to the row to be deleted again. It may be that
  73225. ** the BEFORE triggers coded above have already removed the row
  73226. ** being deleted. Do not attempt to delete the row a second time, and
  73227. ** do not fire AFTER triggers. */
  73228. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  73229. /* Do FK processing. This call checks that any FK constraints that
  73230. ** refer to this table (i.e. constraints attached to other tables)
  73231. ** are not violated by deleting this row. */
  73232. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  73233. }
  73234. /* Delete the index and table entries. Skip this step if pTab is really
  73235. ** a view (in which case the only effect of the DELETE statement is to
  73236. ** fire the INSTEAD OF triggers). */
  73237. if( pTab->pSelect==0 ){
  73238. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  73239. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  73240. if( count ){
  73241. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  73242. }
  73243. }
  73244. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  73245. ** handle rows (possibly in other tables) that refer via a foreign key
  73246. ** to the row just deleted. */
  73247. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  73248. /* Invoke AFTER DELETE trigger programs. */
  73249. sqlite3CodeRowTrigger(pParse, pTrigger,
  73250. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  73251. );
  73252. /* Jump here if the row had already been deleted before any BEFORE
  73253. ** trigger programs were invoked. Or if a trigger program throws a
  73254. ** RAISE(IGNORE) exception. */
  73255. sqlite3VdbeResolveLabel(v, iLabel);
  73256. }
  73257. /*
  73258. ** This routine generates VDBE code that causes the deletion of all
  73259. ** index entries associated with a single row of a single table.
  73260. **
  73261. ** The VDBE must be in a particular state when this routine is called.
  73262. ** These are the requirements:
  73263. **
  73264. ** 1. A read/write cursor pointing to pTab, the table containing the row
  73265. ** to be deleted, must be opened as cursor number "iCur".
  73266. **
  73267. ** 2. Read/write cursors for all indices of pTab must be open as
  73268. ** cursor number iCur+i for the i-th index.
  73269. **
  73270. ** 3. The "iCur" cursor must be pointing to the row that is to be
  73271. ** deleted.
  73272. */
  73273. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  73274. Parse *pParse, /* Parsing and code generating context */
  73275. Table *pTab, /* Table containing the row to be deleted */
  73276. int iCur, /* Cursor number for the table */
  73277. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  73278. ){
  73279. int i;
  73280. Index *pIdx;
  73281. int r1;
  73282. int iPartIdxLabel;
  73283. Vdbe *v = pParse->pVdbe;
  73284. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  73285. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  73286. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  73287. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  73288. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  73289. }
  73290. }
  73291. /*
  73292. ** Generate code that will assemble an index key and put it in register
  73293. ** regOut. The key with be for index pIdx which is an index on pTab.
  73294. ** iCur is the index of a cursor open on the pTab table and pointing to
  73295. ** the entry that needs indexing.
  73296. **
  73297. ** Return a register number which is the first in a block of
  73298. ** registers that holds the elements of the index key. The
  73299. ** block of registers has already been deallocated by the time
  73300. ** this routine returns.
  73301. **
  73302. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  73303. ** to that label if pIdx is a partial index that should be skipped.
  73304. ** A partial index should be skipped if its WHERE clause evaluates
  73305. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  73306. ** will be set to zero which is an empty label that is ignored by
  73307. ** sqlite3VdbeResolveLabel().
  73308. */
  73309. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  73310. Parse *pParse, /* Parsing context */
  73311. Index *pIdx, /* The index for which to generate a key */
  73312. int iCur, /* Cursor number for the pIdx->pTable table */
  73313. int regOut, /* Write the new index key to this register */
  73314. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  73315. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  73316. ){
  73317. Vdbe *v = pParse->pVdbe;
  73318. int j;
  73319. Table *pTab = pIdx->pTable;
  73320. int regBase;
  73321. int nCol;
  73322. if( piPartIdxLabel ){
  73323. if( pIdx->pPartIdxWhere ){
  73324. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  73325. pParse->iPartIdxTab = iCur;
  73326. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  73327. SQLITE_JUMPIFNULL);
  73328. }else{
  73329. *piPartIdxLabel = 0;
  73330. }
  73331. }
  73332. nCol = pIdx->nColumn;
  73333. regBase = sqlite3GetTempRange(pParse, nCol+1);
  73334. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  73335. for(j=0; j<nCol; j++){
  73336. int idx = pIdx->aiColumn[j];
  73337. if( idx==pTab->iPKey ){
  73338. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  73339. }else{
  73340. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  73341. sqlite3ColumnDefault(v, pTab, idx, -1);
  73342. }
  73343. }
  73344. if( doMakeRec ){
  73345. const char *zAff;
  73346. if( pTab->pSelect
  73347. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  73348. ){
  73349. zAff = 0;
  73350. }else{
  73351. zAff = sqlite3IndexAffinityStr(v, pIdx);
  73352. }
  73353. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  73354. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  73355. }
  73356. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  73357. return regBase;
  73358. }
  73359. /************** End of delete.c **********************************************/
  73360. /************** Begin file func.c ********************************************/
  73361. /*
  73362. ** 2002 February 23
  73363. **
  73364. ** The author disclaims copyright to this source code. In place of
  73365. ** a legal notice, here is a blessing:
  73366. **
  73367. ** May you do good and not evil.
  73368. ** May you find forgiveness for yourself and forgive others.
  73369. ** May you share freely, never taking more than you give.
  73370. **
  73371. *************************************************************************
  73372. ** This file contains the C functions that implement various SQL
  73373. ** functions of SQLite.
  73374. **
  73375. ** There is only one exported symbol in this file - the function
  73376. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  73377. ** All other code has file scope.
  73378. */
  73379. /* #include <stdlib.h> */
  73380. /* #include <assert.h> */
  73381. /*
  73382. ** Return the collating function associated with a function.
  73383. */
  73384. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  73385. return context->pColl;
  73386. }
  73387. /*
  73388. ** Indicate that the accumulator load should be skipped on this
  73389. ** iteration of the aggregate loop.
  73390. */
  73391. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  73392. context->skipFlag = 1;
  73393. }
  73394. /*
  73395. ** Implementation of the non-aggregate min() and max() functions
  73396. */
  73397. static void minmaxFunc(
  73398. sqlite3_context *context,
  73399. int argc,
  73400. sqlite3_value **argv
  73401. ){
  73402. int i;
  73403. int mask; /* 0 for min() or 0xffffffff for max() */
  73404. int iBest;
  73405. CollSeq *pColl;
  73406. assert( argc>1 );
  73407. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  73408. pColl = sqlite3GetFuncCollSeq(context);
  73409. assert( pColl );
  73410. assert( mask==-1 || mask==0 );
  73411. iBest = 0;
  73412. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  73413. for(i=1; i<argc; i++){
  73414. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  73415. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  73416. testcase( mask==0 );
  73417. iBest = i;
  73418. }
  73419. }
  73420. sqlite3_result_value(context, argv[iBest]);
  73421. }
  73422. /*
  73423. ** Return the type of the argument.
  73424. */
  73425. static void typeofFunc(
  73426. sqlite3_context *context,
  73427. int NotUsed,
  73428. sqlite3_value **argv
  73429. ){
  73430. const char *z = 0;
  73431. UNUSED_PARAMETER(NotUsed);
  73432. switch( sqlite3_value_type(argv[0]) ){
  73433. case SQLITE_INTEGER: z = "integer"; break;
  73434. case SQLITE_TEXT: z = "text"; break;
  73435. case SQLITE_FLOAT: z = "real"; break;
  73436. case SQLITE_BLOB: z = "blob"; break;
  73437. default: z = "null"; break;
  73438. }
  73439. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  73440. }
  73441. /*
  73442. ** Implementation of the length() function
  73443. */
  73444. static void lengthFunc(
  73445. sqlite3_context *context,
  73446. int argc,
  73447. sqlite3_value **argv
  73448. ){
  73449. int len;
  73450. assert( argc==1 );
  73451. UNUSED_PARAMETER(argc);
  73452. switch( sqlite3_value_type(argv[0]) ){
  73453. case SQLITE_BLOB:
  73454. case SQLITE_INTEGER:
  73455. case SQLITE_FLOAT: {
  73456. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  73457. break;
  73458. }
  73459. case SQLITE_TEXT: {
  73460. const unsigned char *z = sqlite3_value_text(argv[0]);
  73461. if( z==0 ) return;
  73462. len = 0;
  73463. while( *z ){
  73464. len++;
  73465. SQLITE_SKIP_UTF8(z);
  73466. }
  73467. sqlite3_result_int(context, len);
  73468. break;
  73469. }
  73470. default: {
  73471. sqlite3_result_null(context);
  73472. break;
  73473. }
  73474. }
  73475. }
  73476. /*
  73477. ** Implementation of the abs() function.
  73478. **
  73479. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  73480. ** the numeric argument X.
  73481. */
  73482. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73483. assert( argc==1 );
  73484. UNUSED_PARAMETER(argc);
  73485. switch( sqlite3_value_type(argv[0]) ){
  73486. case SQLITE_INTEGER: {
  73487. i64 iVal = sqlite3_value_int64(argv[0]);
  73488. if( iVal<0 ){
  73489. if( (iVal<<1)==0 ){
  73490. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  73491. ** abs(X) throws an integer overflow error since there is no
  73492. ** equivalent positive 64-bit two complement value. */
  73493. sqlite3_result_error(context, "integer overflow", -1);
  73494. return;
  73495. }
  73496. iVal = -iVal;
  73497. }
  73498. sqlite3_result_int64(context, iVal);
  73499. break;
  73500. }
  73501. case SQLITE_NULL: {
  73502. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  73503. sqlite3_result_null(context);
  73504. break;
  73505. }
  73506. default: {
  73507. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  73508. ** something that can be converted into a number, we have:
  73509. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  73510. ** cannot be converted to a numeric value.
  73511. */
  73512. double rVal = sqlite3_value_double(argv[0]);
  73513. if( rVal<0 ) rVal = -rVal;
  73514. sqlite3_result_double(context, rVal);
  73515. break;
  73516. }
  73517. }
  73518. }
  73519. /*
  73520. ** Implementation of the instr() function.
  73521. **
  73522. ** instr(haystack,needle) finds the first occurrence of needle
  73523. ** in haystack and returns the number of previous characters plus 1,
  73524. ** or 0 if needle does not occur within haystack.
  73525. **
  73526. ** If both haystack and needle are BLOBs, then the result is one more than
  73527. ** the number of bytes in haystack prior to the first occurrence of needle,
  73528. ** or 0 if needle never occurs in haystack.
  73529. */
  73530. static void instrFunc(
  73531. sqlite3_context *context,
  73532. int argc,
  73533. sqlite3_value **argv
  73534. ){
  73535. const unsigned char *zHaystack;
  73536. const unsigned char *zNeedle;
  73537. int nHaystack;
  73538. int nNeedle;
  73539. int typeHaystack, typeNeedle;
  73540. int N = 1;
  73541. int isText;
  73542. UNUSED_PARAMETER(argc);
  73543. typeHaystack = sqlite3_value_type(argv[0]);
  73544. typeNeedle = sqlite3_value_type(argv[1]);
  73545. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  73546. nHaystack = sqlite3_value_bytes(argv[0]);
  73547. nNeedle = sqlite3_value_bytes(argv[1]);
  73548. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  73549. zHaystack = sqlite3_value_blob(argv[0]);
  73550. zNeedle = sqlite3_value_blob(argv[1]);
  73551. isText = 0;
  73552. }else{
  73553. zHaystack = sqlite3_value_text(argv[0]);
  73554. zNeedle = sqlite3_value_text(argv[1]);
  73555. isText = 1;
  73556. }
  73557. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  73558. N++;
  73559. do{
  73560. nHaystack--;
  73561. zHaystack++;
  73562. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  73563. }
  73564. if( nNeedle>nHaystack ) N = 0;
  73565. sqlite3_result_int(context, N);
  73566. }
  73567. /*
  73568. ** Implementation of the substr() function.
  73569. **
  73570. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  73571. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  73572. ** of x. If x is text, then we actually count UTF-8 characters.
  73573. ** If x is a blob, then we count bytes.
  73574. **
  73575. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  73576. **
  73577. ** If p2 is negative, return the p2 characters preceding p1.
  73578. */
  73579. static void substrFunc(
  73580. sqlite3_context *context,
  73581. int argc,
  73582. sqlite3_value **argv
  73583. ){
  73584. const unsigned char *z;
  73585. const unsigned char *z2;
  73586. int len;
  73587. int p0type;
  73588. i64 p1, p2;
  73589. int negP2 = 0;
  73590. assert( argc==3 || argc==2 );
  73591. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  73592. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  73593. ){
  73594. return;
  73595. }
  73596. p0type = sqlite3_value_type(argv[0]);
  73597. p1 = sqlite3_value_int(argv[1]);
  73598. if( p0type==SQLITE_BLOB ){
  73599. len = sqlite3_value_bytes(argv[0]);
  73600. z = sqlite3_value_blob(argv[0]);
  73601. if( z==0 ) return;
  73602. assert( len==sqlite3_value_bytes(argv[0]) );
  73603. }else{
  73604. z = sqlite3_value_text(argv[0]);
  73605. if( z==0 ) return;
  73606. len = 0;
  73607. if( p1<0 ){
  73608. for(z2=z; *z2; len++){
  73609. SQLITE_SKIP_UTF8(z2);
  73610. }
  73611. }
  73612. }
  73613. if( argc==3 ){
  73614. p2 = sqlite3_value_int(argv[2]);
  73615. if( p2<0 ){
  73616. p2 = -p2;
  73617. negP2 = 1;
  73618. }
  73619. }else{
  73620. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  73621. }
  73622. if( p1<0 ){
  73623. p1 += len;
  73624. if( p1<0 ){
  73625. p2 += p1;
  73626. if( p2<0 ) p2 = 0;
  73627. p1 = 0;
  73628. }
  73629. }else if( p1>0 ){
  73630. p1--;
  73631. }else if( p2>0 ){
  73632. p2--;
  73633. }
  73634. if( negP2 ){
  73635. p1 -= p2;
  73636. if( p1<0 ){
  73637. p2 += p1;
  73638. p1 = 0;
  73639. }
  73640. }
  73641. assert( p1>=0 && p2>=0 );
  73642. if( p0type!=SQLITE_BLOB ){
  73643. while( *z && p1 ){
  73644. SQLITE_SKIP_UTF8(z);
  73645. p1--;
  73646. }
  73647. for(z2=z; *z2 && p2; p2--){
  73648. SQLITE_SKIP_UTF8(z2);
  73649. }
  73650. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  73651. }else{
  73652. if( p1+p2>len ){
  73653. p2 = len-p1;
  73654. if( p2<0 ) p2 = 0;
  73655. }
  73656. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  73657. }
  73658. }
  73659. /*
  73660. ** Implementation of the round() function
  73661. */
  73662. #ifndef SQLITE_OMIT_FLOATING_POINT
  73663. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73664. int n = 0;
  73665. double r;
  73666. char *zBuf;
  73667. assert( argc==1 || argc==2 );
  73668. if( argc==2 ){
  73669. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  73670. n = sqlite3_value_int(argv[1]);
  73671. if( n>30 ) n = 30;
  73672. if( n<0 ) n = 0;
  73673. }
  73674. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  73675. r = sqlite3_value_double(argv[0]);
  73676. /* If Y==0 and X will fit in a 64-bit int,
  73677. ** handle the rounding directly,
  73678. ** otherwise use printf.
  73679. */
  73680. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  73681. r = (double)((sqlite_int64)(r+0.5));
  73682. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  73683. r = -(double)((sqlite_int64)((-r)+0.5));
  73684. }else{
  73685. zBuf = sqlite3_mprintf("%.*f",n,r);
  73686. if( zBuf==0 ){
  73687. sqlite3_result_error_nomem(context);
  73688. return;
  73689. }
  73690. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  73691. sqlite3_free(zBuf);
  73692. }
  73693. sqlite3_result_double(context, r);
  73694. }
  73695. #endif
  73696. /*
  73697. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  73698. ** allocation fails, call sqlite3_result_error_nomem() to notify
  73699. ** the database handle that malloc() has failed and return NULL.
  73700. ** If nByte is larger than the maximum string or blob length, then
  73701. ** raise an SQLITE_TOOBIG exception and return NULL.
  73702. */
  73703. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  73704. char *z;
  73705. sqlite3 *db = sqlite3_context_db_handle(context);
  73706. assert( nByte>0 );
  73707. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  73708. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  73709. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73710. sqlite3_result_error_toobig(context);
  73711. z = 0;
  73712. }else{
  73713. z = sqlite3Malloc((int)nByte);
  73714. if( !z ){
  73715. sqlite3_result_error_nomem(context);
  73716. }
  73717. }
  73718. return z;
  73719. }
  73720. /*
  73721. ** Implementation of the upper() and lower() SQL functions.
  73722. */
  73723. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73724. char *z1;
  73725. const char *z2;
  73726. int i, n;
  73727. UNUSED_PARAMETER(argc);
  73728. z2 = (char*)sqlite3_value_text(argv[0]);
  73729. n = sqlite3_value_bytes(argv[0]);
  73730. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  73731. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  73732. if( z2 ){
  73733. z1 = contextMalloc(context, ((i64)n)+1);
  73734. if( z1 ){
  73735. for(i=0; i<n; i++){
  73736. z1[i] = (char)sqlite3Toupper(z2[i]);
  73737. }
  73738. sqlite3_result_text(context, z1, n, sqlite3_free);
  73739. }
  73740. }
  73741. }
  73742. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  73743. char *z1;
  73744. const char *z2;
  73745. int i, n;
  73746. UNUSED_PARAMETER(argc);
  73747. z2 = (char*)sqlite3_value_text(argv[0]);
  73748. n = sqlite3_value_bytes(argv[0]);
  73749. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  73750. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  73751. if( z2 ){
  73752. z1 = contextMalloc(context, ((i64)n)+1);
  73753. if( z1 ){
  73754. for(i=0; i<n; i++){
  73755. z1[i] = sqlite3Tolower(z2[i]);
  73756. }
  73757. sqlite3_result_text(context, z1, n, sqlite3_free);
  73758. }
  73759. }
  73760. }
  73761. /*
  73762. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  73763. ** as VDBE code so that unused argument values do not have to be computed.
  73764. ** However, we still need some kind of function implementation for this
  73765. ** routines in the function table. The noopFunc macro provides this.
  73766. ** noopFunc will never be called so it doesn't matter what the implementation
  73767. ** is. We might as well use the "version()" function as a substitute.
  73768. */
  73769. #define noopFunc versionFunc /* Substitute function - never called */
  73770. /*
  73771. ** Implementation of random(). Return a random integer.
  73772. */
  73773. static void randomFunc(
  73774. sqlite3_context *context,
  73775. int NotUsed,
  73776. sqlite3_value **NotUsed2
  73777. ){
  73778. sqlite_int64 r;
  73779. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73780. sqlite3_randomness(sizeof(r), &r);
  73781. if( r<0 ){
  73782. /* We need to prevent a random number of 0x8000000000000000
  73783. ** (or -9223372036854775808) since when you do abs() of that
  73784. ** number of you get the same value back again. To do this
  73785. ** in a way that is testable, mask the sign bit off of negative
  73786. ** values, resulting in a positive value. Then take the
  73787. ** 2s complement of that positive value. The end result can
  73788. ** therefore be no less than -9223372036854775807.
  73789. */
  73790. r = -(r & LARGEST_INT64);
  73791. }
  73792. sqlite3_result_int64(context, r);
  73793. }
  73794. /*
  73795. ** Implementation of randomblob(N). Return a random blob
  73796. ** that is N bytes long.
  73797. */
  73798. static void randomBlob(
  73799. sqlite3_context *context,
  73800. int argc,
  73801. sqlite3_value **argv
  73802. ){
  73803. int n;
  73804. unsigned char *p;
  73805. assert( argc==1 );
  73806. UNUSED_PARAMETER(argc);
  73807. n = sqlite3_value_int(argv[0]);
  73808. if( n<1 ){
  73809. n = 1;
  73810. }
  73811. p = contextMalloc(context, n);
  73812. if( p ){
  73813. sqlite3_randomness(n, p);
  73814. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  73815. }
  73816. }
  73817. /*
  73818. ** Implementation of the last_insert_rowid() SQL function. The return
  73819. ** value is the same as the sqlite3_last_insert_rowid() API function.
  73820. */
  73821. static void last_insert_rowid(
  73822. sqlite3_context *context,
  73823. int NotUsed,
  73824. sqlite3_value **NotUsed2
  73825. ){
  73826. sqlite3 *db = sqlite3_context_db_handle(context);
  73827. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73828. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  73829. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  73830. ** function. */
  73831. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  73832. }
  73833. /*
  73834. ** Implementation of the changes() SQL function.
  73835. **
  73836. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  73837. ** around the sqlite3_changes() C/C++ function and hence follows the same
  73838. ** rules for counting changes.
  73839. */
  73840. static void changes(
  73841. sqlite3_context *context,
  73842. int NotUsed,
  73843. sqlite3_value **NotUsed2
  73844. ){
  73845. sqlite3 *db = sqlite3_context_db_handle(context);
  73846. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73847. sqlite3_result_int(context, sqlite3_changes(db));
  73848. }
  73849. /*
  73850. ** Implementation of the total_changes() SQL function. The return value is
  73851. ** the same as the sqlite3_total_changes() API function.
  73852. */
  73853. static void total_changes(
  73854. sqlite3_context *context,
  73855. int NotUsed,
  73856. sqlite3_value **NotUsed2
  73857. ){
  73858. sqlite3 *db = sqlite3_context_db_handle(context);
  73859. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73860. /* IMP: R-52756-41993 This function is a wrapper around the
  73861. ** sqlite3_total_changes() C/C++ interface. */
  73862. sqlite3_result_int(context, sqlite3_total_changes(db));
  73863. }
  73864. /*
  73865. ** A structure defining how to do GLOB-style comparisons.
  73866. */
  73867. struct compareInfo {
  73868. u8 matchAll;
  73869. u8 matchOne;
  73870. u8 matchSet;
  73871. u8 noCase;
  73872. };
  73873. /*
  73874. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  73875. ** character is exactly one byte in size. Also, all characters are
  73876. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  73877. ** whereas only characters less than 0x80 do in ASCII.
  73878. */
  73879. #if defined(SQLITE_EBCDIC)
  73880. # define sqlite3Utf8Read(A) (*((*A)++))
  73881. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  73882. #else
  73883. # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  73884. #endif
  73885. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  73886. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  73887. ** case. Thus 'a' LIKE 'A' would be true. */
  73888. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  73889. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  73890. ** is case sensitive causing 'a' LIKE 'A' to be false */
  73891. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  73892. /*
  73893. ** Compare two UTF-8 strings for equality where the first string can
  73894. ** potentially be a "glob" expression. Return true (1) if they
  73895. ** are the same and false (0) if they are different.
  73896. **
  73897. ** Globbing rules:
  73898. **
  73899. ** '*' Matches any sequence of zero or more characters.
  73900. **
  73901. ** '?' Matches exactly one character.
  73902. **
  73903. ** [...] Matches one character from the enclosed list of
  73904. ** characters.
  73905. **
  73906. ** [^...] Matches one character not in the enclosed list.
  73907. **
  73908. ** With the [...] and [^...] matching, a ']' character can be included
  73909. ** in the list by making it the first character after '[' or '^'. A
  73910. ** range of characters can be specified using '-'. Example:
  73911. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  73912. ** it the last character in the list.
  73913. **
  73914. ** This routine is usually quick, but can be N**2 in the worst case.
  73915. **
  73916. ** Hints: to match '*' or '?', put them in "[]". Like this:
  73917. **
  73918. ** abc[*]xyz Matches "abc*xyz" only
  73919. */
  73920. static int patternCompare(
  73921. const u8 *zPattern, /* The glob pattern */
  73922. const u8 *zString, /* The string to compare against the glob */
  73923. const struct compareInfo *pInfo, /* Information about how to do the compare */
  73924. u32 esc /* The escape character */
  73925. ){
  73926. u32 c, c2;
  73927. int invert;
  73928. int seen;
  73929. u8 matchOne = pInfo->matchOne;
  73930. u8 matchAll = pInfo->matchAll;
  73931. u8 matchSet = pInfo->matchSet;
  73932. u8 noCase = pInfo->noCase;
  73933. int prevEscape = 0; /* True if the previous character was 'escape' */
  73934. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  73935. if( c==matchAll && !prevEscape ){
  73936. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  73937. || c == matchOne ){
  73938. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  73939. return 0;
  73940. }
  73941. }
  73942. if( c==0 ){
  73943. return 1;
  73944. }else if( c==esc ){
  73945. c = sqlite3Utf8Read(&zPattern);
  73946. if( c==0 ){
  73947. return 0;
  73948. }
  73949. }else if( c==matchSet ){
  73950. assert( esc==0 ); /* This is GLOB, not LIKE */
  73951. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  73952. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  73953. SQLITE_SKIP_UTF8(zString);
  73954. }
  73955. return *zString!=0;
  73956. }
  73957. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  73958. if( noCase ){
  73959. GlobUpperToLower(c2);
  73960. GlobUpperToLower(c);
  73961. while( c2 != 0 && c2 != c ){
  73962. c2 = sqlite3Utf8Read(&zString);
  73963. GlobUpperToLower(c2);
  73964. }
  73965. }else{
  73966. while( c2 != 0 && c2 != c ){
  73967. c2 = sqlite3Utf8Read(&zString);
  73968. }
  73969. }
  73970. if( c2==0 ) return 0;
  73971. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  73972. }
  73973. return 0;
  73974. }else if( c==matchOne && !prevEscape ){
  73975. if( sqlite3Utf8Read(&zString)==0 ){
  73976. return 0;
  73977. }
  73978. }else if( c==matchSet ){
  73979. u32 prior_c = 0;
  73980. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  73981. seen = 0;
  73982. invert = 0;
  73983. c = sqlite3Utf8Read(&zString);
  73984. if( c==0 ) return 0;
  73985. c2 = sqlite3Utf8Read(&zPattern);
  73986. if( c2=='^' ){
  73987. invert = 1;
  73988. c2 = sqlite3Utf8Read(&zPattern);
  73989. }
  73990. if( c2==']' ){
  73991. if( c==']' ) seen = 1;
  73992. c2 = sqlite3Utf8Read(&zPattern);
  73993. }
  73994. while( c2 && c2!=']' ){
  73995. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  73996. c2 = sqlite3Utf8Read(&zPattern);
  73997. if( c>=prior_c && c<=c2 ) seen = 1;
  73998. prior_c = 0;
  73999. }else{
  74000. if( c==c2 ){
  74001. seen = 1;
  74002. }
  74003. prior_c = c2;
  74004. }
  74005. c2 = sqlite3Utf8Read(&zPattern);
  74006. }
  74007. if( c2==0 || (seen ^ invert)==0 ){
  74008. return 0;
  74009. }
  74010. }else if( esc==c && !prevEscape ){
  74011. prevEscape = 1;
  74012. }else{
  74013. c2 = sqlite3Utf8Read(&zString);
  74014. if( noCase ){
  74015. GlobUpperToLower(c);
  74016. GlobUpperToLower(c2);
  74017. }
  74018. if( c!=c2 ){
  74019. return 0;
  74020. }
  74021. prevEscape = 0;
  74022. }
  74023. }
  74024. return *zString==0;
  74025. }
  74026. /*
  74027. ** The sqlite3_strglob() interface.
  74028. */
  74029. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  74030. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  74031. }
  74032. /*
  74033. ** Count the number of times that the LIKE operator (or GLOB which is
  74034. ** just a variation of LIKE) gets called. This is used for testing
  74035. ** only.
  74036. */
  74037. #ifdef SQLITE_TEST
  74038. SQLITE_API int sqlite3_like_count = 0;
  74039. #endif
  74040. /*
  74041. ** Implementation of the like() SQL function. This function implements
  74042. ** the build-in LIKE operator. The first argument to the function is the
  74043. ** pattern and the second argument is the string. So, the SQL statements:
  74044. **
  74045. ** A LIKE B
  74046. **
  74047. ** is implemented as like(B,A).
  74048. **
  74049. ** This same function (with a different compareInfo structure) computes
  74050. ** the GLOB operator.
  74051. */
  74052. static void likeFunc(
  74053. sqlite3_context *context,
  74054. int argc,
  74055. sqlite3_value **argv
  74056. ){
  74057. const unsigned char *zA, *zB;
  74058. u32 escape = 0;
  74059. int nPat;
  74060. sqlite3 *db = sqlite3_context_db_handle(context);
  74061. zB = sqlite3_value_text(argv[0]);
  74062. zA = sqlite3_value_text(argv[1]);
  74063. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  74064. ** of deep recursion and N*N behavior in patternCompare().
  74065. */
  74066. nPat = sqlite3_value_bytes(argv[0]);
  74067. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  74068. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  74069. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  74070. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  74071. return;
  74072. }
  74073. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  74074. if( argc==3 ){
  74075. /* The escape character string must consist of a single UTF-8 character.
  74076. ** Otherwise, return an error.
  74077. */
  74078. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  74079. if( zEsc==0 ) return;
  74080. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  74081. sqlite3_result_error(context,
  74082. "ESCAPE expression must be a single character", -1);
  74083. return;
  74084. }
  74085. escape = sqlite3Utf8Read(&zEsc);
  74086. }
  74087. if( zA && zB ){
  74088. struct compareInfo *pInfo = sqlite3_user_data(context);
  74089. #ifdef SQLITE_TEST
  74090. sqlite3_like_count++;
  74091. #endif
  74092. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  74093. }
  74094. }
  74095. /*
  74096. ** Implementation of the NULLIF(x,y) function. The result is the first
  74097. ** argument if the arguments are different. The result is NULL if the
  74098. ** arguments are equal to each other.
  74099. */
  74100. static void nullifFunc(
  74101. sqlite3_context *context,
  74102. int NotUsed,
  74103. sqlite3_value **argv
  74104. ){
  74105. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  74106. UNUSED_PARAMETER(NotUsed);
  74107. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  74108. sqlite3_result_value(context, argv[0]);
  74109. }
  74110. }
  74111. /*
  74112. ** Implementation of the sqlite_version() function. The result is the version
  74113. ** of the SQLite library that is running.
  74114. */
  74115. static void versionFunc(
  74116. sqlite3_context *context,
  74117. int NotUsed,
  74118. sqlite3_value **NotUsed2
  74119. ){
  74120. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74121. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  74122. ** sqlite3_libversion() C-interface. */
  74123. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  74124. }
  74125. /*
  74126. ** Implementation of the sqlite_source_id() function. The result is a string
  74127. ** that identifies the particular version of the source code used to build
  74128. ** SQLite.
  74129. */
  74130. static void sourceidFunc(
  74131. sqlite3_context *context,
  74132. int NotUsed,
  74133. sqlite3_value **NotUsed2
  74134. ){
  74135. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74136. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  74137. ** sqlite3_sourceid() C interface. */
  74138. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  74139. }
  74140. /*
  74141. ** Implementation of the sqlite_log() function. This is a wrapper around
  74142. ** sqlite3_log(). The return value is NULL. The function exists purely for
  74143. ** its side-effects.
  74144. */
  74145. static void errlogFunc(
  74146. sqlite3_context *context,
  74147. int argc,
  74148. sqlite3_value **argv
  74149. ){
  74150. UNUSED_PARAMETER(argc);
  74151. UNUSED_PARAMETER(context);
  74152. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  74153. }
  74154. /*
  74155. ** Implementation of the sqlite_compileoption_used() function.
  74156. ** The result is an integer that identifies if the compiler option
  74157. ** was used to build SQLite.
  74158. */
  74159. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74160. static void compileoptionusedFunc(
  74161. sqlite3_context *context,
  74162. int argc,
  74163. sqlite3_value **argv
  74164. ){
  74165. const char *zOptName;
  74166. assert( argc==1 );
  74167. UNUSED_PARAMETER(argc);
  74168. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  74169. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  74170. ** function.
  74171. */
  74172. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  74173. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  74174. }
  74175. }
  74176. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74177. /*
  74178. ** Implementation of the sqlite_compileoption_get() function.
  74179. ** The result is a string that identifies the compiler options
  74180. ** used to build SQLite.
  74181. */
  74182. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74183. static void compileoptiongetFunc(
  74184. sqlite3_context *context,
  74185. int argc,
  74186. sqlite3_value **argv
  74187. ){
  74188. int n;
  74189. assert( argc==1 );
  74190. UNUSED_PARAMETER(argc);
  74191. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  74192. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  74193. */
  74194. n = sqlite3_value_int(argv[0]);
  74195. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  74196. }
  74197. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74198. /* Array for converting from half-bytes (nybbles) into ASCII hex
  74199. ** digits. */
  74200. static const char hexdigits[] = {
  74201. '0', '1', '2', '3', '4', '5', '6', '7',
  74202. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  74203. };
  74204. /*
  74205. ** Implementation of the QUOTE() function. This function takes a single
  74206. ** argument. If the argument is numeric, the return value is the same as
  74207. ** the argument. If the argument is NULL, the return value is the string
  74208. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  74209. ** single-quote escapes.
  74210. */
  74211. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  74212. assert( argc==1 );
  74213. UNUSED_PARAMETER(argc);
  74214. switch( sqlite3_value_type(argv[0]) ){
  74215. case SQLITE_FLOAT: {
  74216. double r1, r2;
  74217. char zBuf[50];
  74218. r1 = sqlite3_value_double(argv[0]);
  74219. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  74220. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  74221. if( r1!=r2 ){
  74222. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  74223. }
  74224. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  74225. break;
  74226. }
  74227. case SQLITE_INTEGER: {
  74228. sqlite3_result_value(context, argv[0]);
  74229. break;
  74230. }
  74231. case SQLITE_BLOB: {
  74232. char *zText = 0;
  74233. char const *zBlob = sqlite3_value_blob(argv[0]);
  74234. int nBlob = sqlite3_value_bytes(argv[0]);
  74235. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  74236. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  74237. if( zText ){
  74238. int i;
  74239. for(i=0; i<nBlob; i++){
  74240. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  74241. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  74242. }
  74243. zText[(nBlob*2)+2] = '\'';
  74244. zText[(nBlob*2)+3] = '\0';
  74245. zText[0] = 'X';
  74246. zText[1] = '\'';
  74247. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  74248. sqlite3_free(zText);
  74249. }
  74250. break;
  74251. }
  74252. case SQLITE_TEXT: {
  74253. int i,j;
  74254. u64 n;
  74255. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  74256. char *z;
  74257. if( zArg==0 ) return;
  74258. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  74259. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  74260. if( z ){
  74261. z[0] = '\'';
  74262. for(i=0, j=1; zArg[i]; i++){
  74263. z[j++] = zArg[i];
  74264. if( zArg[i]=='\'' ){
  74265. z[j++] = '\'';
  74266. }
  74267. }
  74268. z[j++] = '\'';
  74269. z[j] = 0;
  74270. sqlite3_result_text(context, z, j, sqlite3_free);
  74271. }
  74272. break;
  74273. }
  74274. default: {
  74275. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  74276. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  74277. break;
  74278. }
  74279. }
  74280. }
  74281. /*
  74282. ** The unicode() function. Return the integer unicode code-point value
  74283. ** for the first character of the input string.
  74284. */
  74285. static void unicodeFunc(
  74286. sqlite3_context *context,
  74287. int argc,
  74288. sqlite3_value **argv
  74289. ){
  74290. const unsigned char *z = sqlite3_value_text(argv[0]);
  74291. (void)argc;
  74292. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  74293. }
  74294. /*
  74295. ** The char() function takes zero or more arguments, each of which is
  74296. ** an integer. It constructs a string where each character of the string
  74297. ** is the unicode character for the corresponding integer argument.
  74298. */
  74299. static void charFunc(
  74300. sqlite3_context *context,
  74301. int argc,
  74302. sqlite3_value **argv
  74303. ){
  74304. unsigned char *z, *zOut;
  74305. int i;
  74306. zOut = z = sqlite3_malloc( argc*4 );
  74307. if( z==0 ){
  74308. sqlite3_result_error_nomem(context);
  74309. return;
  74310. }
  74311. for(i=0; i<argc; i++){
  74312. sqlite3_int64 x;
  74313. unsigned c;
  74314. x = sqlite3_value_int64(argv[i]);
  74315. if( x<0 || x>0x10ffff ) x = 0xfffd;
  74316. c = (unsigned)(x & 0x1fffff);
  74317. if( c<0x00080 ){
  74318. *zOut++ = (u8)(c&0xFF);
  74319. }else if( c<0x00800 ){
  74320. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  74321. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74322. }else if( c<0x10000 ){
  74323. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  74324. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  74325. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74326. }else{
  74327. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  74328. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  74329. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  74330. *zOut++ = 0x80 + (u8)(c & 0x3F);
  74331. } \
  74332. }
  74333. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  74334. }
  74335. /*
  74336. ** The hex() function. Interpret the argument as a blob. Return
  74337. ** a hexadecimal rendering as text.
  74338. */
  74339. static void hexFunc(
  74340. sqlite3_context *context,
  74341. int argc,
  74342. sqlite3_value **argv
  74343. ){
  74344. int i, n;
  74345. const unsigned char *pBlob;
  74346. char *zHex, *z;
  74347. assert( argc==1 );
  74348. UNUSED_PARAMETER(argc);
  74349. pBlob = sqlite3_value_blob(argv[0]);
  74350. n = sqlite3_value_bytes(argv[0]);
  74351. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  74352. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  74353. if( zHex ){
  74354. for(i=0; i<n; i++, pBlob++){
  74355. unsigned char c = *pBlob;
  74356. *(z++) = hexdigits[(c>>4)&0xf];
  74357. *(z++) = hexdigits[c&0xf];
  74358. }
  74359. *z = 0;
  74360. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  74361. }
  74362. }
  74363. /*
  74364. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  74365. */
  74366. static void zeroblobFunc(
  74367. sqlite3_context *context,
  74368. int argc,
  74369. sqlite3_value **argv
  74370. ){
  74371. i64 n;
  74372. sqlite3 *db = sqlite3_context_db_handle(context);
  74373. assert( argc==1 );
  74374. UNUSED_PARAMETER(argc);
  74375. n = sqlite3_value_int64(argv[0]);
  74376. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74377. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  74378. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74379. sqlite3_result_error_toobig(context);
  74380. }else{
  74381. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  74382. }
  74383. }
  74384. /*
  74385. ** The replace() function. Three arguments are all strings: call
  74386. ** them A, B, and C. The result is also a string which is derived
  74387. ** from A by replacing every occurrence of B with C. The match
  74388. ** must be exact. Collating sequences are not used.
  74389. */
  74390. static void replaceFunc(
  74391. sqlite3_context *context,
  74392. int argc,
  74393. sqlite3_value **argv
  74394. ){
  74395. const unsigned char *zStr; /* The input string A */
  74396. const unsigned char *zPattern; /* The pattern string B */
  74397. const unsigned char *zRep; /* The replacement string C */
  74398. unsigned char *zOut; /* The output */
  74399. int nStr; /* Size of zStr */
  74400. int nPattern; /* Size of zPattern */
  74401. int nRep; /* Size of zRep */
  74402. i64 nOut; /* Maximum size of zOut */
  74403. int loopLimit; /* Last zStr[] that might match zPattern[] */
  74404. int i, j; /* Loop counters */
  74405. assert( argc==3 );
  74406. UNUSED_PARAMETER(argc);
  74407. zStr = sqlite3_value_text(argv[0]);
  74408. if( zStr==0 ) return;
  74409. nStr = sqlite3_value_bytes(argv[0]);
  74410. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  74411. zPattern = sqlite3_value_text(argv[1]);
  74412. if( zPattern==0 ){
  74413. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  74414. || sqlite3_context_db_handle(context)->mallocFailed );
  74415. return;
  74416. }
  74417. if( zPattern[0]==0 ){
  74418. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  74419. sqlite3_result_value(context, argv[0]);
  74420. return;
  74421. }
  74422. nPattern = sqlite3_value_bytes(argv[1]);
  74423. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  74424. zRep = sqlite3_value_text(argv[2]);
  74425. if( zRep==0 ) return;
  74426. nRep = sqlite3_value_bytes(argv[2]);
  74427. assert( zRep==sqlite3_value_text(argv[2]) );
  74428. nOut = nStr + 1;
  74429. assert( nOut<SQLITE_MAX_LENGTH );
  74430. zOut = contextMalloc(context, (i64)nOut);
  74431. if( zOut==0 ){
  74432. return;
  74433. }
  74434. loopLimit = nStr - nPattern;
  74435. for(i=j=0; i<=loopLimit; i++){
  74436. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  74437. zOut[j++] = zStr[i];
  74438. }else{
  74439. u8 *zOld;
  74440. sqlite3 *db = sqlite3_context_db_handle(context);
  74441. nOut += nRep - nPattern;
  74442. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74443. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  74444. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74445. sqlite3_result_error_toobig(context);
  74446. sqlite3_free(zOut);
  74447. return;
  74448. }
  74449. zOld = zOut;
  74450. zOut = sqlite3_realloc(zOut, (int)nOut);
  74451. if( zOut==0 ){
  74452. sqlite3_result_error_nomem(context);
  74453. sqlite3_free(zOld);
  74454. return;
  74455. }
  74456. memcpy(&zOut[j], zRep, nRep);
  74457. j += nRep;
  74458. i += nPattern-1;
  74459. }
  74460. }
  74461. assert( j+nStr-i+1==nOut );
  74462. memcpy(&zOut[j], &zStr[i], nStr-i);
  74463. j += nStr - i;
  74464. assert( j<=nOut );
  74465. zOut[j] = 0;
  74466. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  74467. }
  74468. /*
  74469. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  74470. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  74471. */
  74472. static void trimFunc(
  74473. sqlite3_context *context,
  74474. int argc,
  74475. sqlite3_value **argv
  74476. ){
  74477. const unsigned char *zIn; /* Input string */
  74478. const unsigned char *zCharSet; /* Set of characters to trim */
  74479. int nIn; /* Number of bytes in input */
  74480. int flags; /* 1: trimleft 2: trimright 3: trim */
  74481. int i; /* Loop counter */
  74482. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  74483. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  74484. int nChar; /* Number of characters in zCharSet */
  74485. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  74486. return;
  74487. }
  74488. zIn = sqlite3_value_text(argv[0]);
  74489. if( zIn==0 ) return;
  74490. nIn = sqlite3_value_bytes(argv[0]);
  74491. assert( zIn==sqlite3_value_text(argv[0]) );
  74492. if( argc==1 ){
  74493. static const unsigned char lenOne[] = { 1 };
  74494. static unsigned char * const azOne[] = { (u8*)" " };
  74495. nChar = 1;
  74496. aLen = (u8*)lenOne;
  74497. azChar = (unsigned char **)azOne;
  74498. zCharSet = 0;
  74499. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  74500. return;
  74501. }else{
  74502. const unsigned char *z;
  74503. for(z=zCharSet, nChar=0; *z; nChar++){
  74504. SQLITE_SKIP_UTF8(z);
  74505. }
  74506. if( nChar>0 ){
  74507. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  74508. if( azChar==0 ){
  74509. return;
  74510. }
  74511. aLen = (unsigned char*)&azChar[nChar];
  74512. for(z=zCharSet, nChar=0; *z; nChar++){
  74513. azChar[nChar] = (unsigned char *)z;
  74514. SQLITE_SKIP_UTF8(z);
  74515. aLen[nChar] = (u8)(z - azChar[nChar]);
  74516. }
  74517. }
  74518. }
  74519. if( nChar>0 ){
  74520. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  74521. if( flags & 1 ){
  74522. while( nIn>0 ){
  74523. int len = 0;
  74524. for(i=0; i<nChar; i++){
  74525. len = aLen[i];
  74526. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  74527. }
  74528. if( i>=nChar ) break;
  74529. zIn += len;
  74530. nIn -= len;
  74531. }
  74532. }
  74533. if( flags & 2 ){
  74534. while( nIn>0 ){
  74535. int len = 0;
  74536. for(i=0; i<nChar; i++){
  74537. len = aLen[i];
  74538. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  74539. }
  74540. if( i>=nChar ) break;
  74541. nIn -= len;
  74542. }
  74543. }
  74544. if( zCharSet ){
  74545. sqlite3_free(azChar);
  74546. }
  74547. }
  74548. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  74549. }
  74550. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  74551. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  74552. ** when SQLite is built.
  74553. */
  74554. #ifdef SQLITE_SOUNDEX
  74555. /*
  74556. ** Compute the soundex encoding of a word.
  74557. **
  74558. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  74559. ** soundex encoding of the string X.
  74560. */
  74561. static void soundexFunc(
  74562. sqlite3_context *context,
  74563. int argc,
  74564. sqlite3_value **argv
  74565. ){
  74566. char zResult[8];
  74567. const u8 *zIn;
  74568. int i, j;
  74569. static const unsigned char iCode[] = {
  74570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  74574. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  74575. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  74576. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  74577. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  74578. };
  74579. assert( argc==1 );
  74580. zIn = (u8*)sqlite3_value_text(argv[0]);
  74581. if( zIn==0 ) zIn = (u8*)"";
  74582. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  74583. if( zIn[i] ){
  74584. u8 prevcode = iCode[zIn[i]&0x7f];
  74585. zResult[0] = sqlite3Toupper(zIn[i]);
  74586. for(j=1; j<4 && zIn[i]; i++){
  74587. int code = iCode[zIn[i]&0x7f];
  74588. if( code>0 ){
  74589. if( code!=prevcode ){
  74590. prevcode = code;
  74591. zResult[j++] = code + '0';
  74592. }
  74593. }else{
  74594. prevcode = 0;
  74595. }
  74596. }
  74597. while( j<4 ){
  74598. zResult[j++] = '0';
  74599. }
  74600. zResult[j] = 0;
  74601. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  74602. }else{
  74603. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  74604. ** is NULL or contains no ASCII alphabetic characters. */
  74605. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  74606. }
  74607. }
  74608. #endif /* SQLITE_SOUNDEX */
  74609. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  74610. /*
  74611. ** A function that loads a shared-library extension then returns NULL.
  74612. */
  74613. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  74614. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  74615. const char *zProc;
  74616. sqlite3 *db = sqlite3_context_db_handle(context);
  74617. char *zErrMsg = 0;
  74618. if( argc==2 ){
  74619. zProc = (const char *)sqlite3_value_text(argv[1]);
  74620. }else{
  74621. zProc = 0;
  74622. }
  74623. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  74624. sqlite3_result_error(context, zErrMsg, -1);
  74625. sqlite3_free(zErrMsg);
  74626. }
  74627. }
  74628. #endif
  74629. /*
  74630. ** An instance of the following structure holds the context of a
  74631. ** sum() or avg() aggregate computation.
  74632. */
  74633. typedef struct SumCtx SumCtx;
  74634. struct SumCtx {
  74635. double rSum; /* Floating point sum */
  74636. i64 iSum; /* Integer sum */
  74637. i64 cnt; /* Number of elements summed */
  74638. u8 overflow; /* True if integer overflow seen */
  74639. u8 approx; /* True if non-integer value was input to the sum */
  74640. };
  74641. /*
  74642. ** Routines used to compute the sum, average, and total.
  74643. **
  74644. ** The SUM() function follows the (broken) SQL standard which means
  74645. ** that it returns NULL if it sums over no inputs. TOTAL returns
  74646. ** 0.0 in that case. In addition, TOTAL always returns a float where
  74647. ** SUM might return an integer if it never encounters a floating point
  74648. ** value. TOTAL never fails, but SUM might through an exception if
  74649. ** it overflows an integer.
  74650. */
  74651. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  74652. SumCtx *p;
  74653. int type;
  74654. assert( argc==1 );
  74655. UNUSED_PARAMETER(argc);
  74656. p = sqlite3_aggregate_context(context, sizeof(*p));
  74657. type = sqlite3_value_numeric_type(argv[0]);
  74658. if( p && type!=SQLITE_NULL ){
  74659. p->cnt++;
  74660. if( type==SQLITE_INTEGER ){
  74661. i64 v = sqlite3_value_int64(argv[0]);
  74662. p->rSum += v;
  74663. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  74664. p->overflow = 1;
  74665. }
  74666. }else{
  74667. p->rSum += sqlite3_value_double(argv[0]);
  74668. p->approx = 1;
  74669. }
  74670. }
  74671. }
  74672. static void sumFinalize(sqlite3_context *context){
  74673. SumCtx *p;
  74674. p = sqlite3_aggregate_context(context, 0);
  74675. if( p && p->cnt>0 ){
  74676. if( p->overflow ){
  74677. sqlite3_result_error(context,"integer overflow",-1);
  74678. }else if( p->approx ){
  74679. sqlite3_result_double(context, p->rSum);
  74680. }else{
  74681. sqlite3_result_int64(context, p->iSum);
  74682. }
  74683. }
  74684. }
  74685. static void avgFinalize(sqlite3_context *context){
  74686. SumCtx *p;
  74687. p = sqlite3_aggregate_context(context, 0);
  74688. if( p && p->cnt>0 ){
  74689. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  74690. }
  74691. }
  74692. static void totalFinalize(sqlite3_context *context){
  74693. SumCtx *p;
  74694. p = sqlite3_aggregate_context(context, 0);
  74695. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  74696. sqlite3_result_double(context, p ? p->rSum : (double)0);
  74697. }
  74698. /*
  74699. ** The following structure keeps track of state information for the
  74700. ** count() aggregate function.
  74701. */
  74702. typedef struct CountCtx CountCtx;
  74703. struct CountCtx {
  74704. i64 n;
  74705. };
  74706. /*
  74707. ** Routines to implement the count() aggregate function.
  74708. */
  74709. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  74710. CountCtx *p;
  74711. p = sqlite3_aggregate_context(context, sizeof(*p));
  74712. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  74713. p->n++;
  74714. }
  74715. #ifndef SQLITE_OMIT_DEPRECATED
  74716. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  74717. ** sure it still operates correctly, verify that its count agrees with our
  74718. ** internal count when using count(*) and when the total count can be
  74719. ** expressed as a 32-bit integer. */
  74720. assert( argc==1 || p==0 || p->n>0x7fffffff
  74721. || p->n==sqlite3_aggregate_count(context) );
  74722. #endif
  74723. }
  74724. static void countFinalize(sqlite3_context *context){
  74725. CountCtx *p;
  74726. p = sqlite3_aggregate_context(context, 0);
  74727. sqlite3_result_int64(context, p ? p->n : 0);
  74728. }
  74729. /*
  74730. ** Routines to implement min() and max() aggregate functions.
  74731. */
  74732. static void minmaxStep(
  74733. sqlite3_context *context,
  74734. int NotUsed,
  74735. sqlite3_value **argv
  74736. ){
  74737. Mem *pArg = (Mem *)argv[0];
  74738. Mem *pBest;
  74739. UNUSED_PARAMETER(NotUsed);
  74740. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  74741. if( !pBest ) return;
  74742. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  74743. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  74744. }else if( pBest->flags ){
  74745. int max;
  74746. int cmp;
  74747. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  74748. /* This step function is used for both the min() and max() aggregates,
  74749. ** the only difference between the two being that the sense of the
  74750. ** comparison is inverted. For the max() aggregate, the
  74751. ** sqlite3_user_data() function returns (void *)-1. For min() it
  74752. ** returns (void *)db, where db is the sqlite3* database pointer.
  74753. ** Therefore the next statement sets variable 'max' to 1 for the max()
  74754. ** aggregate, or 0 for min().
  74755. */
  74756. max = sqlite3_user_data(context)!=0;
  74757. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  74758. if( (max && cmp<0) || (!max && cmp>0) ){
  74759. sqlite3VdbeMemCopy(pBest, pArg);
  74760. }else{
  74761. sqlite3SkipAccumulatorLoad(context);
  74762. }
  74763. }else{
  74764. sqlite3VdbeMemCopy(pBest, pArg);
  74765. }
  74766. }
  74767. static void minMaxFinalize(sqlite3_context *context){
  74768. sqlite3_value *pRes;
  74769. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  74770. if( pRes ){
  74771. if( pRes->flags ){
  74772. sqlite3_result_value(context, pRes);
  74773. }
  74774. sqlite3VdbeMemRelease(pRes);
  74775. }
  74776. }
  74777. /*
  74778. ** group_concat(EXPR, ?SEPARATOR?)
  74779. */
  74780. static void groupConcatStep(
  74781. sqlite3_context *context,
  74782. int argc,
  74783. sqlite3_value **argv
  74784. ){
  74785. const char *zVal;
  74786. StrAccum *pAccum;
  74787. const char *zSep;
  74788. int nVal, nSep;
  74789. assert( argc==1 || argc==2 );
  74790. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  74791. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  74792. if( pAccum ){
  74793. sqlite3 *db = sqlite3_context_db_handle(context);
  74794. int firstTerm = pAccum->useMalloc==0;
  74795. pAccum->useMalloc = 2;
  74796. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  74797. if( !firstTerm ){
  74798. if( argc==2 ){
  74799. zSep = (char*)sqlite3_value_text(argv[1]);
  74800. nSep = sqlite3_value_bytes(argv[1]);
  74801. }else{
  74802. zSep = ",";
  74803. nSep = 1;
  74804. }
  74805. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  74806. }
  74807. zVal = (char*)sqlite3_value_text(argv[0]);
  74808. nVal = sqlite3_value_bytes(argv[0]);
  74809. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  74810. }
  74811. }
  74812. static void groupConcatFinalize(sqlite3_context *context){
  74813. StrAccum *pAccum;
  74814. pAccum = sqlite3_aggregate_context(context, 0);
  74815. if( pAccum ){
  74816. if( pAccum->accError==STRACCUM_TOOBIG ){
  74817. sqlite3_result_error_toobig(context);
  74818. }else if( pAccum->accError==STRACCUM_NOMEM ){
  74819. sqlite3_result_error_nomem(context);
  74820. }else{
  74821. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  74822. sqlite3_free);
  74823. }
  74824. }
  74825. }
  74826. /*
  74827. ** This routine does per-connection function registration. Most
  74828. ** of the built-in functions above are part of the global function set.
  74829. ** This routine only deals with those that are not global.
  74830. */
  74831. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  74832. int rc = sqlite3_overload_function(db, "MATCH", 2);
  74833. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  74834. if( rc==SQLITE_NOMEM ){
  74835. db->mallocFailed = 1;
  74836. }
  74837. }
  74838. /*
  74839. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  74840. */
  74841. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  74842. FuncDef *pDef;
  74843. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  74844. 2, SQLITE_UTF8, 0);
  74845. if( ALWAYS(pDef) ){
  74846. pDef->funcFlags |= flagVal;
  74847. }
  74848. }
  74849. /*
  74850. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  74851. ** parameter determines whether or not the LIKE operator is case
  74852. ** sensitive. GLOB is always case sensitive.
  74853. */
  74854. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  74855. struct compareInfo *pInfo;
  74856. if( caseSensitive ){
  74857. pInfo = (struct compareInfo*)&likeInfoAlt;
  74858. }else{
  74859. pInfo = (struct compareInfo*)&likeInfoNorm;
  74860. }
  74861. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  74862. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  74863. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  74864. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  74865. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  74866. setLikeOptFlag(db, "like",
  74867. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  74868. }
  74869. /*
  74870. ** pExpr points to an expression which implements a function. If
  74871. ** it is appropriate to apply the LIKE optimization to that function
  74872. ** then set aWc[0] through aWc[2] to the wildcard characters and
  74873. ** return TRUE. If the function is not a LIKE-style function then
  74874. ** return FALSE.
  74875. */
  74876. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  74877. FuncDef *pDef;
  74878. if( pExpr->op!=TK_FUNCTION
  74879. || !pExpr->x.pList
  74880. || pExpr->x.pList->nExpr!=2
  74881. ){
  74882. return 0;
  74883. }
  74884. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74885. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  74886. sqlite3Strlen30(pExpr->u.zToken),
  74887. 2, SQLITE_UTF8, 0);
  74888. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  74889. return 0;
  74890. }
  74891. /* The memcpy() statement assumes that the wildcard characters are
  74892. ** the first three statements in the compareInfo structure. The
  74893. ** asserts() that follow verify that assumption
  74894. */
  74895. memcpy(aWc, pDef->pUserData, 3);
  74896. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  74897. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  74898. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  74899. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  74900. return 1;
  74901. }
  74902. /*
  74903. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  74904. ** to the global function hash table. This occurs at start-time (as
  74905. ** a consequence of calling sqlite3_initialize()).
  74906. **
  74907. ** After this routine runs
  74908. */
  74909. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  74910. /*
  74911. ** The following array holds FuncDef structures for all of the functions
  74912. ** defined in this file.
  74913. **
  74914. ** The array cannot be constant since changes are made to the
  74915. ** FuncDef.pHash elements at start-time. The elements of this array
  74916. ** are read-only after initialization is complete.
  74917. */
  74918. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  74919. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  74920. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  74921. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  74922. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  74923. FUNCTION(trim, 1, 3, 0, trimFunc ),
  74924. FUNCTION(trim, 2, 3, 0, trimFunc ),
  74925. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  74926. FUNCTION(min, 0, 0, 1, 0 ),
  74927. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  74928. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  74929. FUNCTION(max, 0, 1, 1, 0 ),
  74930. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  74931. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  74932. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  74933. FUNCTION(instr, 2, 0, 0, instrFunc ),
  74934. FUNCTION(substr, 2, 0, 0, substrFunc ),
  74935. FUNCTION(substr, 3, 0, 0, substrFunc ),
  74936. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  74937. FUNCTION(char, -1, 0, 0, charFunc ),
  74938. FUNCTION(abs, 1, 0, 0, absFunc ),
  74939. #ifndef SQLITE_OMIT_FLOATING_POINT
  74940. FUNCTION(round, 1, 0, 0, roundFunc ),
  74941. FUNCTION(round, 2, 0, 0, roundFunc ),
  74942. #endif
  74943. FUNCTION(upper, 1, 0, 0, upperFunc ),
  74944. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  74945. FUNCTION(coalesce, 1, 0, 0, 0 ),
  74946. FUNCTION(coalesce, 0, 0, 0, 0 ),
  74947. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  74948. FUNCTION(hex, 1, 0, 0, hexFunc ),
  74949. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  74950. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  74951. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  74952. FUNCTION(random, 0, 0, 0, randomFunc ),
  74953. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  74954. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  74955. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  74956. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  74957. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  74958. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  74959. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  74960. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  74961. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  74962. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  74963. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  74964. FUNCTION(changes, 0, 0, 0, changes ),
  74965. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  74966. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  74967. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  74968. #ifdef SQLITE_SOUNDEX
  74969. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  74970. #endif
  74971. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  74972. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  74973. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  74974. #endif
  74975. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  74976. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  74977. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  74978. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  74979. {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  74980. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  74981. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  74982. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  74983. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74984. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  74985. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74986. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  74987. #else
  74988. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  74989. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  74990. #endif
  74991. };
  74992. int i;
  74993. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  74994. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  74995. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  74996. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  74997. }
  74998. sqlite3RegisterDateTimeFunctions();
  74999. #ifndef SQLITE_OMIT_ALTERTABLE
  75000. sqlite3AlterFunctions();
  75001. #endif
  75002. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  75003. sqlite3AnalyzeFunctions();
  75004. #endif
  75005. }
  75006. /************** End of func.c ************************************************/
  75007. /************** Begin file fkey.c ********************************************/
  75008. /*
  75009. **
  75010. ** The author disclaims copyright to this source code. In place of
  75011. ** a legal notice, here is a blessing:
  75012. **
  75013. ** May you do good and not evil.
  75014. ** May you find forgiveness for yourself and forgive others.
  75015. ** May you share freely, never taking more than you give.
  75016. **
  75017. *************************************************************************
  75018. ** This file contains code used by the compiler to add foreign key
  75019. ** support to compiled SQL statements.
  75020. */
  75021. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75022. #ifndef SQLITE_OMIT_TRIGGER
  75023. /*
  75024. ** Deferred and Immediate FKs
  75025. ** --------------------------
  75026. **
  75027. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  75028. ** If an immediate foreign key constraint is violated,
  75029. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  75030. ** statement transaction rolled back. If a
  75031. ** deferred foreign key constraint is violated, no action is taken
  75032. ** immediately. However if the application attempts to commit the
  75033. ** transaction before fixing the constraint violation, the attempt fails.
  75034. **
  75035. ** Deferred constraints are implemented using a simple counter associated
  75036. ** with the database handle. The counter is set to zero each time a
  75037. ** database transaction is opened. Each time a statement is executed
  75038. ** that causes a foreign key violation, the counter is incremented. Each
  75039. ** time a statement is executed that removes an existing violation from
  75040. ** the database, the counter is decremented. When the transaction is
  75041. ** committed, the commit fails if the current value of the counter is
  75042. ** greater than zero. This scheme has two big drawbacks:
  75043. **
  75044. ** * When a commit fails due to a deferred foreign key constraint,
  75045. ** there is no way to tell which foreign constraint is not satisfied,
  75046. ** or which row it is not satisfied for.
  75047. **
  75048. ** * If the database contains foreign key violations when the
  75049. ** transaction is opened, this may cause the mechanism to malfunction.
  75050. **
  75051. ** Despite these problems, this approach is adopted as it seems simpler
  75052. ** than the alternatives.
  75053. **
  75054. ** INSERT operations:
  75055. **
  75056. ** I.1) For each FK for which the table is the child table, search
  75057. ** the parent table for a match. If none is found increment the
  75058. ** constraint counter.
  75059. **
  75060. ** I.2) For each FK for which the table is the parent table,
  75061. ** search the child table for rows that correspond to the new
  75062. ** row in the parent table. Decrement the counter for each row
  75063. ** found (as the constraint is now satisfied).
  75064. **
  75065. ** DELETE operations:
  75066. **
  75067. ** D.1) For each FK for which the table is the child table,
  75068. ** search the parent table for a row that corresponds to the
  75069. ** deleted row in the child table. If such a row is not found,
  75070. ** decrement the counter.
  75071. **
  75072. ** D.2) For each FK for which the table is the parent table, search
  75073. ** the child table for rows that correspond to the deleted row
  75074. ** in the parent table. For each found increment the counter.
  75075. **
  75076. ** UPDATE operations:
  75077. **
  75078. ** An UPDATE command requires that all 4 steps above are taken, but only
  75079. ** for FK constraints for which the affected columns are actually
  75080. ** modified (values must be compared at runtime).
  75081. **
  75082. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  75083. ** This simplifies the implementation a bit.
  75084. **
  75085. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  75086. ** resolution is considered to delete rows before the new row is inserted.
  75087. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  75088. ** is thrown, even if the FK constraint would be satisfied after the new
  75089. ** row is inserted.
  75090. **
  75091. ** Immediate constraints are usually handled similarly. The only difference
  75092. ** is that the counter used is stored as part of each individual statement
  75093. ** object (struct Vdbe). If, after the statement has run, its immediate
  75094. ** constraint counter is greater than zero,
  75095. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  75096. ** and the statement transaction is rolled back. An exception is an INSERT
  75097. ** statement that inserts a single row only (no triggers). In this case,
  75098. ** instead of using a counter, an exception is thrown immediately if the
  75099. ** INSERT violates a foreign key constraint. This is necessary as such
  75100. ** an INSERT does not open a statement transaction.
  75101. **
  75102. ** TODO: How should dropping a table be handled? How should renaming a
  75103. ** table be handled?
  75104. **
  75105. **
  75106. ** Query API Notes
  75107. ** ---------------
  75108. **
  75109. ** Before coding an UPDATE or DELETE row operation, the code-generator
  75110. ** for those two operations needs to know whether or not the operation
  75111. ** requires any FK processing and, if so, which columns of the original
  75112. ** row are required by the FK processing VDBE code (i.e. if FKs were
  75113. ** implemented using triggers, which of the old.* columns would be
  75114. ** accessed). No information is required by the code-generator before
  75115. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  75116. ** generation code to query for this information are:
  75117. **
  75118. ** sqlite3FkRequired() - Test to see if FK processing is required.
  75119. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  75120. **
  75121. **
  75122. ** Externally accessible module functions
  75123. ** --------------------------------------
  75124. **
  75125. ** sqlite3FkCheck() - Check for foreign key violations.
  75126. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  75127. ** sqlite3FkDelete() - Delete an FKey structure.
  75128. */
  75129. /*
  75130. ** VDBE Calling Convention
  75131. ** -----------------------
  75132. **
  75133. ** Example:
  75134. **
  75135. ** For the following INSERT statement:
  75136. **
  75137. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  75138. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  75139. **
  75140. ** Register (x): 2 (type integer)
  75141. ** Register (x+1): 1 (type integer)
  75142. ** Register (x+2): NULL (type NULL)
  75143. ** Register (x+3): 3.1 (type real)
  75144. */
  75145. /*
  75146. ** A foreign key constraint requires that the key columns in the parent
  75147. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  75148. ** Given that pParent is the parent table for foreign key constraint pFKey,
  75149. ** search the schema for a unique index on the parent key columns.
  75150. **
  75151. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  75152. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  75153. ** is set to point to the unique index.
  75154. **
  75155. ** If the parent key consists of a single column (the foreign key constraint
  75156. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  75157. ** Otherwise, it is set to point to an allocated array of size N, where
  75158. ** N is the number of columns in the parent key. The first element of the
  75159. ** array is the index of the child table column that is mapped by the FK
  75160. ** constraint to the parent table column stored in the left-most column
  75161. ** of index *ppIdx. The second element of the array is the index of the
  75162. ** child table column that corresponds to the second left-most column of
  75163. ** *ppIdx, and so on.
  75164. **
  75165. ** If the required index cannot be found, either because:
  75166. **
  75167. ** 1) The named parent key columns do not exist, or
  75168. **
  75169. ** 2) The named parent key columns do exist, but are not subject to a
  75170. ** UNIQUE or PRIMARY KEY constraint, or
  75171. **
  75172. ** 3) No parent key columns were provided explicitly as part of the
  75173. ** foreign key definition, and the parent table does not have a
  75174. ** PRIMARY KEY, or
  75175. **
  75176. ** 4) No parent key columns were provided explicitly as part of the
  75177. ** foreign key definition, and the PRIMARY KEY of the parent table
  75178. ** consists of a a different number of columns to the child key in
  75179. ** the child table.
  75180. **
  75181. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  75182. ** into pParse. If an OOM error occurs, non-zero is returned and the
  75183. ** pParse->db->mallocFailed flag is set.
  75184. */
  75185. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  75186. Parse *pParse, /* Parse context to store any error in */
  75187. Table *pParent, /* Parent table of FK constraint pFKey */
  75188. FKey *pFKey, /* Foreign key to find index for */
  75189. Index **ppIdx, /* OUT: Unique index on parent table */
  75190. int **paiCol /* OUT: Map of index columns in pFKey */
  75191. ){
  75192. Index *pIdx = 0; /* Value to return via *ppIdx */
  75193. int *aiCol = 0; /* Value to return via *paiCol */
  75194. int nCol = pFKey->nCol; /* Number of columns in parent key */
  75195. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  75196. /* The caller is responsible for zeroing output parameters. */
  75197. assert( ppIdx && *ppIdx==0 );
  75198. assert( !paiCol || *paiCol==0 );
  75199. assert( pParse );
  75200. /* If this is a non-composite (single column) foreign key, check if it
  75201. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  75202. ** and *paiCol set to zero and return early.
  75203. **
  75204. ** Otherwise, for a composite foreign key (more than one column), allocate
  75205. ** space for the aiCol array (returned via output parameter *paiCol).
  75206. ** Non-composite foreign keys do not require the aiCol array.
  75207. */
  75208. if( nCol==1 ){
  75209. /* The FK maps to the IPK if any of the following are true:
  75210. **
  75211. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  75212. ** mapped to the primary key of table pParent, or
  75213. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  75214. ** PRIMARY KEY.
  75215. */
  75216. if( pParent->iPKey>=0 ){
  75217. if( !zKey ) return 0;
  75218. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  75219. }
  75220. }else if( paiCol ){
  75221. assert( nCol>1 );
  75222. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  75223. if( !aiCol ) return 1;
  75224. *paiCol = aiCol;
  75225. }
  75226. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  75227. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  75228. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  75229. ** of columns. If each indexed column corresponds to a foreign key
  75230. ** column of pFKey, then this index is a winner. */
  75231. if( zKey==0 ){
  75232. /* If zKey is NULL, then this foreign key is implicitly mapped to
  75233. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  75234. ** identified by the test (Index.autoIndex==2). */
  75235. if( pIdx->autoIndex==2 ){
  75236. if( aiCol ){
  75237. int i;
  75238. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  75239. }
  75240. break;
  75241. }
  75242. }else{
  75243. /* If zKey is non-NULL, then this foreign key was declared to
  75244. ** map to an explicit list of columns in table pParent. Check if this
  75245. ** index matches those columns. Also, check that the index uses
  75246. ** the default collation sequences for each column. */
  75247. int i, j;
  75248. for(i=0; i<nCol; i++){
  75249. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  75250. char *zDfltColl; /* Def. collation for column */
  75251. char *zIdxCol; /* Name of indexed column */
  75252. /* If the index uses a collation sequence that is different from
  75253. ** the default collation sequence for the column, this index is
  75254. ** unusable. Bail out early in this case. */
  75255. zDfltColl = pParent->aCol[iCol].zColl;
  75256. if( !zDfltColl ){
  75257. zDfltColl = "BINARY";
  75258. }
  75259. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  75260. zIdxCol = pParent->aCol[iCol].zName;
  75261. for(j=0; j<nCol; j++){
  75262. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  75263. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  75264. break;
  75265. }
  75266. }
  75267. if( j==nCol ) break;
  75268. }
  75269. if( i==nCol ) break; /* pIdx is usable */
  75270. }
  75271. }
  75272. }
  75273. if( !pIdx ){
  75274. if( !pParse->disableTriggers ){
  75275. sqlite3ErrorMsg(pParse,
  75276. "foreign key mismatch - \"%w\" referencing \"%w\"",
  75277. pFKey->pFrom->zName, pFKey->zTo);
  75278. }
  75279. sqlite3DbFree(pParse->db, aiCol);
  75280. return 1;
  75281. }
  75282. *ppIdx = pIdx;
  75283. return 0;
  75284. }
  75285. /*
  75286. ** This function is called when a row is inserted into or deleted from the
  75287. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  75288. ** on the child table of pFKey, this function is invoked twice for each row
  75289. ** affected - once to "delete" the old row, and then again to "insert" the
  75290. ** new row.
  75291. **
  75292. ** Each time it is called, this function generates VDBE code to locate the
  75293. ** row in the parent table that corresponds to the row being inserted into
  75294. ** or deleted from the child table. If the parent row can be found, no
  75295. ** special action is taken. Otherwise, if the parent row can *not* be
  75296. ** found in the parent table:
  75297. **
  75298. ** Operation | FK type | Action taken
  75299. ** --------------------------------------------------------------------------
  75300. ** INSERT immediate Increment the "immediate constraint counter".
  75301. **
  75302. ** DELETE immediate Decrement the "immediate constraint counter".
  75303. **
  75304. ** INSERT deferred Increment the "deferred constraint counter".
  75305. **
  75306. ** DELETE deferred Decrement the "deferred constraint counter".
  75307. **
  75308. ** These operations are identified in the comment at the top of this file
  75309. ** (fkey.c) as "I.1" and "D.1".
  75310. */
  75311. static void fkLookupParent(
  75312. Parse *pParse, /* Parse context */
  75313. int iDb, /* Index of database housing pTab */
  75314. Table *pTab, /* Parent table of FK pFKey */
  75315. Index *pIdx, /* Unique index on parent key columns in pTab */
  75316. FKey *pFKey, /* Foreign key constraint */
  75317. int *aiCol, /* Map from parent key columns to child table columns */
  75318. int regData, /* Address of array containing child table row */
  75319. int nIncr, /* Increment constraint counter by this */
  75320. int isIgnore /* If true, pretend pTab contains all NULL values */
  75321. ){
  75322. int i; /* Iterator variable */
  75323. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  75324. int iCur = pParse->nTab - 1; /* Cursor number to use */
  75325. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  75326. /* If nIncr is less than zero, then check at runtime if there are any
  75327. ** outstanding constraints to resolve. If there are not, there is no need
  75328. ** to check if deleting this row resolves any outstanding violations.
  75329. **
  75330. ** Check if any of the key columns in the child table row are NULL. If
  75331. ** any are, then the constraint is considered satisfied. No need to
  75332. ** search for a matching row in the parent table. */
  75333. if( nIncr<0 ){
  75334. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  75335. }
  75336. for(i=0; i<pFKey->nCol; i++){
  75337. int iReg = aiCol[i] + regData + 1;
  75338. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  75339. }
  75340. if( isIgnore==0 ){
  75341. if( pIdx==0 ){
  75342. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  75343. ** column of the parent table (table pTab). */
  75344. int iMustBeInt; /* Address of MustBeInt instruction */
  75345. int regTemp = sqlite3GetTempReg(pParse);
  75346. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  75347. ** apply the affinity of the parent key). If this fails, then there
  75348. ** is no matching parent key. Before using MustBeInt, make a copy of
  75349. ** the value. Otherwise, the value inserted into the child key column
  75350. ** will have INTEGER affinity applied to it, which may not be correct. */
  75351. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  75352. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  75353. /* If the parent table is the same as the child table, and we are about
  75354. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  75355. ** then check if the row being inserted matches itself. If so, do not
  75356. ** increment the constraint-counter. */
  75357. if( pTab==pFKey->pFrom && nIncr==1 ){
  75358. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  75359. }
  75360. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  75361. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  75362. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  75363. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  75364. sqlite3VdbeJumpHere(v, iMustBeInt);
  75365. sqlite3ReleaseTempReg(pParse, regTemp);
  75366. }else{
  75367. int nCol = pFKey->nCol;
  75368. int regTemp = sqlite3GetTempRange(pParse, nCol);
  75369. int regRec = sqlite3GetTempReg(pParse);
  75370. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  75371. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  75372. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  75373. for(i=0; i<nCol; i++){
  75374. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  75375. }
  75376. /* If the parent table is the same as the child table, and we are about
  75377. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  75378. ** then check if the row being inserted matches itself. If so, do not
  75379. ** increment the constraint-counter.
  75380. **
  75381. ** If any of the parent-key values are NULL, then the row cannot match
  75382. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  75383. ** of the parent-key values are NULL (at this point it is known that
  75384. ** none of the child key values are).
  75385. */
  75386. if( pTab==pFKey->pFrom && nIncr==1 ){
  75387. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  75388. for(i=0; i<nCol; i++){
  75389. int iChild = aiCol[i]+1+regData;
  75390. int iParent = pIdx->aiColumn[i]+1+regData;
  75391. assert( aiCol[i]!=pTab->iPKey );
  75392. if( pIdx->aiColumn[i]==pTab->iPKey ){
  75393. /* The parent key is a composite key that includes the IPK column */
  75394. iParent = regData;
  75395. }
  75396. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  75397. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  75398. }
  75399. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  75400. }
  75401. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  75402. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  75403. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  75404. sqlite3ReleaseTempReg(pParse, regRec);
  75405. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  75406. }
  75407. }
  75408. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  75409. && !pParse->pToplevel
  75410. && !pParse->isMultiWrite
  75411. ){
  75412. /* Special case: If this is an INSERT statement that will insert exactly
  75413. ** one row into the table, raise a constraint immediately instead of
  75414. ** incrementing a counter. This is necessary as the VM code is being
  75415. ** generated for will not open a statement transaction. */
  75416. assert( nIncr==1 );
  75417. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  75418. OE_Abort, "foreign key constraint failed", P4_STATIC
  75419. );
  75420. }else{
  75421. if( nIncr>0 && pFKey->isDeferred==0 ){
  75422. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  75423. }
  75424. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  75425. }
  75426. sqlite3VdbeResolveLabel(v, iOk);
  75427. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  75428. }
  75429. /*
  75430. ** This function is called to generate code executed when a row is deleted
  75431. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  75432. ** deferred, when a row is inserted into the same table. When generating
  75433. ** code for an SQL UPDATE operation, this function may be called twice -
  75434. ** once to "delete" the old row and once to "insert" the new row.
  75435. **
  75436. ** The code generated by this function scans through the rows in the child
  75437. ** table that correspond to the parent table row being deleted or inserted.
  75438. ** For each child row found, one of the following actions is taken:
  75439. **
  75440. ** Operation | FK type | Action taken
  75441. ** --------------------------------------------------------------------------
  75442. ** DELETE immediate Increment the "immediate constraint counter".
  75443. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  75444. ** throw a "foreign key constraint failed" exception.
  75445. **
  75446. ** INSERT immediate Decrement the "immediate constraint counter".
  75447. **
  75448. ** DELETE deferred Increment the "deferred constraint counter".
  75449. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  75450. ** throw a "foreign key constraint failed" exception.
  75451. **
  75452. ** INSERT deferred Decrement the "deferred constraint counter".
  75453. **
  75454. ** These operations are identified in the comment at the top of this file
  75455. ** (fkey.c) as "I.2" and "D.2".
  75456. */
  75457. static void fkScanChildren(
  75458. Parse *pParse, /* Parse context */
  75459. SrcList *pSrc, /* SrcList containing the table to scan */
  75460. Table *pTab,
  75461. Index *pIdx, /* Foreign key index */
  75462. FKey *pFKey, /* Foreign key relationship */
  75463. int *aiCol, /* Map from pIdx cols to child table cols */
  75464. int regData, /* Referenced table data starts here */
  75465. int nIncr /* Amount to increment deferred counter by */
  75466. ){
  75467. sqlite3 *db = pParse->db; /* Database handle */
  75468. int i; /* Iterator variable */
  75469. Expr *pWhere = 0; /* WHERE clause to scan with */
  75470. NameContext sNameContext; /* Context used to resolve WHERE clause */
  75471. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  75472. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  75473. Vdbe *v = sqlite3GetVdbe(pParse);
  75474. assert( !pIdx || pIdx->pTable==pTab );
  75475. if( nIncr<0 ){
  75476. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  75477. }
  75478. /* Create an Expr object representing an SQL expression like:
  75479. **
  75480. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  75481. **
  75482. ** The collation sequence used for the comparison should be that of
  75483. ** the parent key columns. The affinity of the parent key column should
  75484. ** be applied to each child key value before the comparison takes place.
  75485. */
  75486. for(i=0; i<pFKey->nCol; i++){
  75487. Expr *pLeft; /* Value from parent table row */
  75488. Expr *pRight; /* Column ref to child table */
  75489. Expr *pEq; /* Expression (pLeft = pRight) */
  75490. int iCol; /* Index of column in child table */
  75491. const char *zCol; /* Name of column in child table */
  75492. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  75493. if( pLeft ){
  75494. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  75495. ** expression to the parent key column defaults. */
  75496. if( pIdx ){
  75497. Column *pCol;
  75498. const char *zColl;
  75499. iCol = pIdx->aiColumn[i];
  75500. pCol = &pTab->aCol[iCol];
  75501. if( pTab->iPKey==iCol ) iCol = -1;
  75502. pLeft->iTable = regData+iCol+1;
  75503. pLeft->affinity = pCol->affinity;
  75504. zColl = pCol->zColl;
  75505. if( zColl==0 ) zColl = db->pDfltColl->zName;
  75506. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  75507. }else{
  75508. pLeft->iTable = regData;
  75509. pLeft->affinity = SQLITE_AFF_INTEGER;
  75510. }
  75511. }
  75512. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  75513. assert( iCol>=0 );
  75514. zCol = pFKey->pFrom->aCol[iCol].zName;
  75515. pRight = sqlite3Expr(db, TK_ID, zCol);
  75516. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  75517. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  75518. }
  75519. /* If the child table is the same as the parent table, and this scan
  75520. ** is taking place as part of a DELETE operation (operation D.2), omit the
  75521. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  75522. ** clause, where $rowid is the rowid of the row being deleted. */
  75523. if( pTab==pFKey->pFrom && nIncr>0 ){
  75524. Expr *pEq; /* Expression (pLeft = pRight) */
  75525. Expr *pLeft; /* Value from parent table row */
  75526. Expr *pRight; /* Column ref to child table */
  75527. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  75528. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  75529. if( pLeft && pRight ){
  75530. pLeft->iTable = regData;
  75531. pLeft->affinity = SQLITE_AFF_INTEGER;
  75532. pRight->iTable = pSrc->a[0].iCursor;
  75533. pRight->iColumn = -1;
  75534. }
  75535. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  75536. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  75537. }
  75538. /* Resolve the references in the WHERE clause. */
  75539. memset(&sNameContext, 0, sizeof(NameContext));
  75540. sNameContext.pSrcList = pSrc;
  75541. sNameContext.pParse = pParse;
  75542. sqlite3ResolveExprNames(&sNameContext, pWhere);
  75543. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  75544. ** clause. If the constraint is not deferred, throw an exception for
  75545. ** each row found. Otherwise, for deferred constraints, increment the
  75546. ** deferred constraint counter by nIncr for each row selected. */
  75547. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  75548. if( nIncr>0 && pFKey->isDeferred==0 ){
  75549. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  75550. }
  75551. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  75552. if( pWInfo ){
  75553. sqlite3WhereEnd(pWInfo);
  75554. }
  75555. /* Clean up the WHERE clause constructed above. */
  75556. sqlite3ExprDelete(db, pWhere);
  75557. if( iFkIfZero ){
  75558. sqlite3VdbeJumpHere(v, iFkIfZero);
  75559. }
  75560. }
  75561. /*
  75562. ** This function returns a pointer to the head of a linked list of FK
  75563. ** constraints for which table pTab is the parent table. For example,
  75564. ** given the following schema:
  75565. **
  75566. ** CREATE TABLE t1(a PRIMARY KEY);
  75567. ** CREATE TABLE t2(b REFERENCES t1(a);
  75568. **
  75569. ** Calling this function with table "t1" as an argument returns a pointer
  75570. ** to the FKey structure representing the foreign key constraint on table
  75571. ** "t2". Calling this function with "t2" as the argument would return a
  75572. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  75573. ** table).
  75574. */
  75575. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  75576. int nName = sqlite3Strlen30(pTab->zName);
  75577. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  75578. }
  75579. /*
  75580. ** The second argument is a Trigger structure allocated by the
  75581. ** fkActionTrigger() routine. This function deletes the Trigger structure
  75582. ** and all of its sub-components.
  75583. **
  75584. ** The Trigger structure or any of its sub-components may be allocated from
  75585. ** the lookaside buffer belonging to database handle dbMem.
  75586. */
  75587. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  75588. if( p ){
  75589. TriggerStep *pStep = p->step_list;
  75590. sqlite3ExprDelete(dbMem, pStep->pWhere);
  75591. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  75592. sqlite3SelectDelete(dbMem, pStep->pSelect);
  75593. sqlite3ExprDelete(dbMem, p->pWhen);
  75594. sqlite3DbFree(dbMem, p);
  75595. }
  75596. }
  75597. /*
  75598. ** This function is called to generate code that runs when table pTab is
  75599. ** being dropped from the database. The SrcList passed as the second argument
  75600. ** to this function contains a single entry guaranteed to resolve to
  75601. ** table pTab.
  75602. **
  75603. ** Normally, no code is required. However, if either
  75604. **
  75605. ** (a) The table is the parent table of a FK constraint, or
  75606. ** (b) The table is the child table of a deferred FK constraint and it is
  75607. ** determined at runtime that there are outstanding deferred FK
  75608. ** constraint violations in the database,
  75609. **
  75610. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  75611. ** the table from the database. Triggers are disabled while running this
  75612. ** DELETE, but foreign key actions are not.
  75613. */
  75614. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  75615. sqlite3 *db = pParse->db;
  75616. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  75617. int iSkip = 0;
  75618. Vdbe *v = sqlite3GetVdbe(pParse);
  75619. assert( v ); /* VDBE has already been allocated */
  75620. if( sqlite3FkReferences(pTab)==0 ){
  75621. /* Search for a deferred foreign key constraint for which this table
  75622. ** is the child table. If one cannot be found, return without
  75623. ** generating any VDBE code. If one can be found, then jump over
  75624. ** the entire DELETE if there are no outstanding deferred constraints
  75625. ** when this statement is run. */
  75626. FKey *p;
  75627. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75628. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  75629. }
  75630. if( !p ) return;
  75631. iSkip = sqlite3VdbeMakeLabel(v);
  75632. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  75633. }
  75634. pParse->disableTriggers = 1;
  75635. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  75636. pParse->disableTriggers = 0;
  75637. /* If the DELETE has generated immediate foreign key constraint
  75638. ** violations, halt the VDBE and return an error at this point, before
  75639. ** any modifications to the schema are made. This is because statement
  75640. ** transactions are not able to rollback schema changes.
  75641. **
  75642. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  75643. ** the statement transaction will not be rolled back even if FK
  75644. ** constraints are violated.
  75645. */
  75646. if( (db->flags & SQLITE_DeferFKs)==0 ){
  75647. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  75648. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  75649. OE_Abort, "foreign key constraint failed", P4_STATIC
  75650. );
  75651. }
  75652. if( iSkip ){
  75653. sqlite3VdbeResolveLabel(v, iSkip);
  75654. }
  75655. }
  75656. }
  75657. /*
  75658. ** The second argument points to an FKey object representing a foreign key
  75659. ** for which pTab is the child table. An UPDATE statement against pTab
  75660. ** is currently being processed. For each column of the table that is
  75661. ** actually updated, the corresponding element in the aChange[] array
  75662. ** is zero or greater (if a column is unmodified the corresponding element
  75663. ** is set to -1). If the rowid column is modified by the UPDATE statement
  75664. ** the bChngRowid argument is non-zero.
  75665. **
  75666. ** This function returns true if any of the columns that are part of the
  75667. ** child key for FK constraint *p are modified.
  75668. */
  75669. static int fkChildIsModified(
  75670. Table *pTab, /* Table being updated */
  75671. FKey *p, /* Foreign key for which pTab is the child */
  75672. int *aChange, /* Array indicating modified columns */
  75673. int bChngRowid /* True if rowid is modified by this update */
  75674. ){
  75675. int i;
  75676. for(i=0; i<p->nCol; i++){
  75677. int iChildKey = p->aCol[i].iFrom;
  75678. if( aChange[iChildKey]>=0 ) return 1;
  75679. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  75680. }
  75681. return 0;
  75682. }
  75683. /*
  75684. ** The second argument points to an FKey object representing a foreign key
  75685. ** for which pTab is the parent table. An UPDATE statement against pTab
  75686. ** is currently being processed. For each column of the table that is
  75687. ** actually updated, the corresponding element in the aChange[] array
  75688. ** is zero or greater (if a column is unmodified the corresponding element
  75689. ** is set to -1). If the rowid column is modified by the UPDATE statement
  75690. ** the bChngRowid argument is non-zero.
  75691. **
  75692. ** This function returns true if any of the columns that are part of the
  75693. ** parent key for FK constraint *p are modified.
  75694. */
  75695. static int fkParentIsModified(
  75696. Table *pTab,
  75697. FKey *p,
  75698. int *aChange,
  75699. int bChngRowid
  75700. ){
  75701. int i;
  75702. for(i=0; i<p->nCol; i++){
  75703. char *zKey = p->aCol[i].zCol;
  75704. int iKey;
  75705. for(iKey=0; iKey<pTab->nCol; iKey++){
  75706. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  75707. Column *pCol = &pTab->aCol[iKey];
  75708. if( zKey ){
  75709. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  75710. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  75711. return 1;
  75712. }
  75713. }
  75714. }
  75715. }
  75716. return 0;
  75717. }
  75718. /*
  75719. ** This function is called when inserting, deleting or updating a row of
  75720. ** table pTab to generate VDBE code to perform foreign key constraint
  75721. ** processing for the operation.
  75722. **
  75723. ** For a DELETE operation, parameter regOld is passed the index of the
  75724. ** first register in an array of (pTab->nCol+1) registers containing the
  75725. ** rowid of the row being deleted, followed by each of the column values
  75726. ** of the row being deleted, from left to right. Parameter regNew is passed
  75727. ** zero in this case.
  75728. **
  75729. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  75730. ** first register of an array of (pTab->nCol+1) registers containing the new
  75731. ** row data.
  75732. **
  75733. ** For an UPDATE operation, this function is called twice. Once before
  75734. ** the original record is deleted from the table using the calling convention
  75735. ** described for DELETE. Then again after the original record is deleted
  75736. ** but before the new record is inserted using the INSERT convention.
  75737. */
  75738. SQLITE_PRIVATE void sqlite3FkCheck(
  75739. Parse *pParse, /* Parse context */
  75740. Table *pTab, /* Row is being deleted from this table */
  75741. int regOld, /* Previous row data is stored here */
  75742. int regNew, /* New row data is stored here */
  75743. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  75744. int bChngRowid /* True if rowid is UPDATEd */
  75745. ){
  75746. sqlite3 *db = pParse->db; /* Database handle */
  75747. FKey *pFKey; /* Used to iterate through FKs */
  75748. int iDb; /* Index of database containing pTab */
  75749. const char *zDb; /* Name of database containing pTab */
  75750. int isIgnoreErrors = pParse->disableTriggers;
  75751. /* Exactly one of regOld and regNew should be non-zero. */
  75752. assert( (regOld==0)!=(regNew==0) );
  75753. /* If foreign-keys are disabled, this function is a no-op. */
  75754. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  75755. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75756. zDb = db->aDb[iDb].zName;
  75757. /* Loop through all the foreign key constraints for which pTab is the
  75758. ** child table (the table that the foreign key definition is part of). */
  75759. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  75760. Table *pTo; /* Parent table of foreign key pFKey */
  75761. Index *pIdx = 0; /* Index on key columns in pTo */
  75762. int *aiFree = 0;
  75763. int *aiCol;
  75764. int iCol;
  75765. int i;
  75766. int isIgnore = 0;
  75767. if( aChange
  75768. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  75769. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  75770. ){
  75771. continue;
  75772. }
  75773. /* Find the parent table of this foreign key. Also find a unique index
  75774. ** on the parent key columns in the parent table. If either of these
  75775. ** schema items cannot be located, set an error in pParse and return
  75776. ** early. */
  75777. if( pParse->disableTriggers ){
  75778. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  75779. }else{
  75780. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  75781. }
  75782. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  75783. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  75784. if( !isIgnoreErrors || db->mallocFailed ) return;
  75785. if( pTo==0 ){
  75786. /* If isIgnoreErrors is true, then a table is being dropped. In this
  75787. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  75788. ** before actually dropping it in order to check FK constraints.
  75789. ** If the parent table of an FK constraint on the current table is
  75790. ** missing, behave as if it is empty. i.e. decrement the relevant
  75791. ** FK counter for each row of the current table with non-NULL keys.
  75792. */
  75793. Vdbe *v = sqlite3GetVdbe(pParse);
  75794. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  75795. for(i=0; i<pFKey->nCol; i++){
  75796. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  75797. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  75798. }
  75799. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  75800. }
  75801. continue;
  75802. }
  75803. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  75804. if( aiFree ){
  75805. aiCol = aiFree;
  75806. }else{
  75807. iCol = pFKey->aCol[0].iFrom;
  75808. aiCol = &iCol;
  75809. }
  75810. for(i=0; i<pFKey->nCol; i++){
  75811. if( aiCol[i]==pTab->iPKey ){
  75812. aiCol[i] = -1;
  75813. }
  75814. #ifndef SQLITE_OMIT_AUTHORIZATION
  75815. /* Request permission to read the parent key columns. If the
  75816. ** authorization callback returns SQLITE_IGNORE, behave as if any
  75817. ** values read from the parent table are NULL. */
  75818. if( db->xAuth ){
  75819. int rcauth;
  75820. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  75821. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  75822. isIgnore = (rcauth==SQLITE_IGNORE);
  75823. }
  75824. #endif
  75825. }
  75826. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  75827. ** a cursor to use to search the unique index on the parent key columns
  75828. ** in the parent table. */
  75829. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  75830. pParse->nTab++;
  75831. if( regOld!=0 ){
  75832. /* A row is being removed from the child table. Search for the parent.
  75833. ** If the parent does not exist, removing the child row resolves an
  75834. ** outstanding foreign key constraint violation. */
  75835. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  75836. }
  75837. if( regNew!=0 ){
  75838. /* A row is being added to the child table. If a parent row cannot
  75839. ** be found, adding the child row has violated the FK constraint. */
  75840. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  75841. }
  75842. sqlite3DbFree(db, aiFree);
  75843. }
  75844. /* Loop through all the foreign key constraints that refer to this table */
  75845. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  75846. Index *pIdx = 0; /* Foreign key index for pFKey */
  75847. SrcList *pSrc;
  75848. int *aiCol = 0;
  75849. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  75850. continue;
  75851. }
  75852. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  75853. && !pParse->pToplevel && !pParse->isMultiWrite
  75854. ){
  75855. assert( regOld==0 && regNew!=0 );
  75856. /* Inserting a single row into a parent table cannot cause an immediate
  75857. ** foreign key violation. So do nothing in this case. */
  75858. continue;
  75859. }
  75860. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  75861. if( !isIgnoreErrors || db->mallocFailed ) return;
  75862. continue;
  75863. }
  75864. assert( aiCol || pFKey->nCol==1 );
  75865. /* Create a SrcList structure containing a single table (the table
  75866. ** the foreign key that refers to this table is attached to). This
  75867. ** is required for the sqlite3WhereXXX() interface. */
  75868. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  75869. if( pSrc ){
  75870. struct SrcList_item *pItem = pSrc->a;
  75871. pItem->pTab = pFKey->pFrom;
  75872. pItem->zName = pFKey->pFrom->zName;
  75873. pItem->pTab->nRef++;
  75874. pItem->iCursor = pParse->nTab++;
  75875. if( regNew!=0 ){
  75876. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  75877. }
  75878. if( regOld!=0 ){
  75879. /* If there is a RESTRICT action configured for the current operation
  75880. ** on the parent table of this FK, then throw an exception
  75881. ** immediately if the FK constraint is violated, even if this is a
  75882. ** deferred trigger. That's what RESTRICT means. To defer checking
  75883. ** the constraint, the FK should specify NO ACTION (represented
  75884. ** using OE_None). NO ACTION is the default. */
  75885. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  75886. }
  75887. pItem->zName = 0;
  75888. sqlite3SrcListDelete(db, pSrc);
  75889. }
  75890. sqlite3DbFree(db, aiCol);
  75891. }
  75892. }
  75893. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  75894. /*
  75895. ** This function is called before generating code to update or delete a
  75896. ** row contained in table pTab.
  75897. */
  75898. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  75899. Parse *pParse, /* Parse context */
  75900. Table *pTab /* Table being modified */
  75901. ){
  75902. u32 mask = 0;
  75903. if( pParse->db->flags&SQLITE_ForeignKeys ){
  75904. FKey *p;
  75905. int i;
  75906. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75907. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  75908. }
  75909. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75910. Index *pIdx = 0;
  75911. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  75912. if( pIdx ){
  75913. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  75914. }
  75915. }
  75916. }
  75917. return mask;
  75918. }
  75919. /*
  75920. ** This function is called before generating code to update or delete a
  75921. ** row contained in table pTab. If the operation is a DELETE, then
  75922. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  75923. ** to an array of size N, where N is the number of columns in table pTab.
  75924. ** If the i'th column is not modified by the UPDATE, then the corresponding
  75925. ** entry in the aChange[] array is set to -1. If the column is modified,
  75926. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  75927. ** UPDATE statement modifies the rowid fields of the table.
  75928. **
  75929. ** If any foreign key processing will be required, this function returns
  75930. ** true. If there is no foreign key related processing, this function
  75931. ** returns false.
  75932. */
  75933. SQLITE_PRIVATE int sqlite3FkRequired(
  75934. Parse *pParse, /* Parse context */
  75935. Table *pTab, /* Table being modified */
  75936. int *aChange, /* Non-NULL for UPDATE operations */
  75937. int chngRowid /* True for UPDATE that affects rowid */
  75938. ){
  75939. if( pParse->db->flags&SQLITE_ForeignKeys ){
  75940. if( !aChange ){
  75941. /* A DELETE operation. Foreign key processing is required if the
  75942. ** table in question is either the child or parent table for any
  75943. ** foreign key constraint. */
  75944. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  75945. }else{
  75946. /* This is an UPDATE. Foreign key processing is only required if the
  75947. ** operation modifies one or more child or parent key columns. */
  75948. FKey *p;
  75949. /* Check if any child key columns are being modified. */
  75950. for(p=pTab->pFKey; p; p=p->pNextFrom){
  75951. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  75952. }
  75953. /* Check if any parent key columns are being modified. */
  75954. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  75955. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  75956. }
  75957. }
  75958. }
  75959. return 0;
  75960. }
  75961. /*
  75962. ** This function is called when an UPDATE or DELETE operation is being
  75963. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  75964. ** If the current operation is an UPDATE, then the pChanges parameter is
  75965. ** passed a pointer to the list of columns being modified. If it is a
  75966. ** DELETE, pChanges is passed a NULL pointer.
  75967. **
  75968. ** It returns a pointer to a Trigger structure containing a trigger
  75969. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  75970. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  75971. ** returned (these actions require no special handling by the triggers
  75972. ** sub-system, code for them is created by fkScanChildren()).
  75973. **
  75974. ** For example, if pFKey is the foreign key and pTab is table "p" in
  75975. ** the following schema:
  75976. **
  75977. ** CREATE TABLE p(pk PRIMARY KEY);
  75978. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  75979. **
  75980. ** then the returned trigger structure is equivalent to:
  75981. **
  75982. ** CREATE TRIGGER ... DELETE ON p BEGIN
  75983. ** DELETE FROM c WHERE ck = old.pk;
  75984. ** END;
  75985. **
  75986. ** The returned pointer is cached as part of the foreign key object. It
  75987. ** is eventually freed along with the rest of the foreign key object by
  75988. ** sqlite3FkDelete().
  75989. */
  75990. static Trigger *fkActionTrigger(
  75991. Parse *pParse, /* Parse context */
  75992. Table *pTab, /* Table being updated or deleted from */
  75993. FKey *pFKey, /* Foreign key to get action for */
  75994. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  75995. ){
  75996. sqlite3 *db = pParse->db; /* Database handle */
  75997. int action; /* One of OE_None, OE_Cascade etc. */
  75998. Trigger *pTrigger; /* Trigger definition to return */
  75999. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  76000. action = pFKey->aAction[iAction];
  76001. pTrigger = pFKey->apTrigger[iAction];
  76002. if( action!=OE_None && !pTrigger ){
  76003. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  76004. char const *zFrom; /* Name of child table */
  76005. int nFrom; /* Length in bytes of zFrom */
  76006. Index *pIdx = 0; /* Parent key index for this FK */
  76007. int *aiCol = 0; /* child table cols -> parent key cols */
  76008. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  76009. Expr *pWhere = 0; /* WHERE clause of trigger step */
  76010. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  76011. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  76012. int i; /* Iterator variable */
  76013. Expr *pWhen = 0; /* WHEN clause for the trigger */
  76014. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  76015. assert( aiCol || pFKey->nCol==1 );
  76016. for(i=0; i<pFKey->nCol; i++){
  76017. Token tOld = { "old", 3 }; /* Literal "old" token */
  76018. Token tNew = { "new", 3 }; /* Literal "new" token */
  76019. Token tFromCol; /* Name of column in child table */
  76020. Token tToCol; /* Name of column in parent table */
  76021. int iFromCol; /* Idx of column in child table */
  76022. Expr *pEq; /* tFromCol = OLD.tToCol */
  76023. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  76024. assert( iFromCol>=0 );
  76025. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  76026. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  76027. tToCol.n = sqlite3Strlen30(tToCol.z);
  76028. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  76029. /* Create the expression "OLD.zToCol = zFromCol". It is important
  76030. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  76031. ** that the affinity and collation sequence associated with the
  76032. ** parent table are used for the comparison. */
  76033. pEq = sqlite3PExpr(pParse, TK_EQ,
  76034. sqlite3PExpr(pParse, TK_DOT,
  76035. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  76036. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  76037. , 0),
  76038. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  76039. , 0);
  76040. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  76041. /* For ON UPDATE, construct the next term of the WHEN clause.
  76042. ** The final WHEN clause will be like this:
  76043. **
  76044. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  76045. */
  76046. if( pChanges ){
  76047. pEq = sqlite3PExpr(pParse, TK_IS,
  76048. sqlite3PExpr(pParse, TK_DOT,
  76049. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  76050. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  76051. 0),
  76052. sqlite3PExpr(pParse, TK_DOT,
  76053. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  76054. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  76055. 0),
  76056. 0);
  76057. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  76058. }
  76059. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  76060. Expr *pNew;
  76061. if( action==OE_Cascade ){
  76062. pNew = sqlite3PExpr(pParse, TK_DOT,
  76063. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  76064. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  76065. , 0);
  76066. }else if( action==OE_SetDflt ){
  76067. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  76068. if( pDflt ){
  76069. pNew = sqlite3ExprDup(db, pDflt, 0);
  76070. }else{
  76071. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  76072. }
  76073. }else{
  76074. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  76075. }
  76076. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  76077. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  76078. }
  76079. }
  76080. sqlite3DbFree(db, aiCol);
  76081. zFrom = pFKey->pFrom->zName;
  76082. nFrom = sqlite3Strlen30(zFrom);
  76083. if( action==OE_Restrict ){
  76084. Token tFrom;
  76085. Expr *pRaise;
  76086. tFrom.z = zFrom;
  76087. tFrom.n = nFrom;
  76088. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  76089. if( pRaise ){
  76090. pRaise->affinity = OE_Abort;
  76091. }
  76092. pSelect = sqlite3SelectNew(pParse,
  76093. sqlite3ExprListAppend(pParse, 0, pRaise),
  76094. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  76095. pWhere,
  76096. 0, 0, 0, 0, 0, 0
  76097. );
  76098. pWhere = 0;
  76099. }
  76100. /* Disable lookaside memory allocation */
  76101. enableLookaside = db->lookaside.bEnabled;
  76102. db->lookaside.bEnabled = 0;
  76103. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  76104. sizeof(Trigger) + /* struct Trigger */
  76105. sizeof(TriggerStep) + /* Single step in trigger program */
  76106. nFrom + 1 /* Space for pStep->target.z */
  76107. );
  76108. if( pTrigger ){
  76109. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  76110. pStep->target.z = (char *)&pStep[1];
  76111. pStep->target.n = nFrom;
  76112. memcpy((char *)pStep->target.z, zFrom, nFrom);
  76113. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  76114. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  76115. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  76116. if( pWhen ){
  76117. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  76118. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  76119. }
  76120. }
  76121. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  76122. db->lookaside.bEnabled = enableLookaside;
  76123. sqlite3ExprDelete(db, pWhere);
  76124. sqlite3ExprDelete(db, pWhen);
  76125. sqlite3ExprListDelete(db, pList);
  76126. sqlite3SelectDelete(db, pSelect);
  76127. if( db->mallocFailed==1 ){
  76128. fkTriggerDelete(db, pTrigger);
  76129. return 0;
  76130. }
  76131. assert( pStep!=0 );
  76132. switch( action ){
  76133. case OE_Restrict:
  76134. pStep->op = TK_SELECT;
  76135. break;
  76136. case OE_Cascade:
  76137. if( !pChanges ){
  76138. pStep->op = TK_DELETE;
  76139. break;
  76140. }
  76141. default:
  76142. pStep->op = TK_UPDATE;
  76143. }
  76144. pStep->pTrig = pTrigger;
  76145. pTrigger->pSchema = pTab->pSchema;
  76146. pTrigger->pTabSchema = pTab->pSchema;
  76147. pFKey->apTrigger[iAction] = pTrigger;
  76148. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  76149. }
  76150. return pTrigger;
  76151. }
  76152. /*
  76153. ** This function is called when deleting or updating a row to implement
  76154. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  76155. */
  76156. SQLITE_PRIVATE void sqlite3FkActions(
  76157. Parse *pParse, /* Parse context */
  76158. Table *pTab, /* Table being updated or deleted from */
  76159. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  76160. int regOld, /* Address of array containing old row */
  76161. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  76162. int bChngRowid /* True if rowid is UPDATEd */
  76163. ){
  76164. /* If foreign-key support is enabled, iterate through all FKs that
  76165. ** refer to table pTab. If there is an action associated with the FK
  76166. ** for this operation (either update or delete), invoke the associated
  76167. ** trigger sub-program. */
  76168. if( pParse->db->flags&SQLITE_ForeignKeys ){
  76169. FKey *pFKey; /* Iterator variable */
  76170. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  76171. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  76172. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  76173. if( pAct ){
  76174. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  76175. }
  76176. }
  76177. }
  76178. }
  76179. }
  76180. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  76181. /*
  76182. ** Free all memory associated with foreign key definitions attached to
  76183. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  76184. ** hash table.
  76185. */
  76186. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  76187. FKey *pFKey; /* Iterator variable */
  76188. FKey *pNext; /* Copy of pFKey->pNextFrom */
  76189. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  76190. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  76191. /* Remove the FK from the fkeyHash hash table. */
  76192. if( !db || db->pnBytesFreed==0 ){
  76193. if( pFKey->pPrevTo ){
  76194. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  76195. }else{
  76196. void *p = (void *)pFKey->pNextTo;
  76197. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  76198. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  76199. }
  76200. if( pFKey->pNextTo ){
  76201. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  76202. }
  76203. }
  76204. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  76205. ** classified as either immediate or deferred.
  76206. */
  76207. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  76208. /* Delete any triggers created to implement actions for this FK. */
  76209. #ifndef SQLITE_OMIT_TRIGGER
  76210. fkTriggerDelete(db, pFKey->apTrigger[0]);
  76211. fkTriggerDelete(db, pFKey->apTrigger[1]);
  76212. #endif
  76213. pNext = pFKey->pNextFrom;
  76214. sqlite3DbFree(db, pFKey);
  76215. }
  76216. }
  76217. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  76218. /************** End of fkey.c ************************************************/
  76219. /************** Begin file insert.c ******************************************/
  76220. /*
  76221. ** 2001 September 15
  76222. **
  76223. ** The author disclaims copyright to this source code. In place of
  76224. ** a legal notice, here is a blessing:
  76225. **
  76226. ** May you do good and not evil.
  76227. ** May you find forgiveness for yourself and forgive others.
  76228. ** May you share freely, never taking more than you give.
  76229. **
  76230. *************************************************************************
  76231. ** This file contains C code routines that are called by the parser
  76232. ** to handle INSERT statements in SQLite.
  76233. */
  76234. /*
  76235. ** Generate code that will open a table for reading.
  76236. */
  76237. SQLITE_PRIVATE void sqlite3OpenTable(
  76238. Parse *p, /* Generate code into this VDBE */
  76239. int iCur, /* The cursor number of the table */
  76240. int iDb, /* The database index in sqlite3.aDb[] */
  76241. Table *pTab, /* The table to be opened */
  76242. int opcode /* OP_OpenRead or OP_OpenWrite */
  76243. ){
  76244. Vdbe *v;
  76245. assert( !IsVirtual(pTab) );
  76246. v = sqlite3GetVdbe(p);
  76247. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  76248. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  76249. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  76250. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  76251. VdbeComment((v, "%s", pTab->zName));
  76252. }
  76253. /*
  76254. ** Return a pointer to the column affinity string associated with index
  76255. ** pIdx. A column affinity string has one character for each column in
  76256. ** the table, according to the affinity of the column:
  76257. **
  76258. ** Character Column affinity
  76259. ** ------------------------------
  76260. ** 'a' TEXT
  76261. ** 'b' NONE
  76262. ** 'c' NUMERIC
  76263. ** 'd' INTEGER
  76264. ** 'e' REAL
  76265. **
  76266. ** An extra 'd' is appended to the end of the string to cover the
  76267. ** rowid that appears as the last column in every index.
  76268. **
  76269. ** Memory for the buffer containing the column index affinity string
  76270. ** is managed along with the rest of the Index structure. It will be
  76271. ** released when sqlite3DeleteIndex() is called.
  76272. */
  76273. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  76274. if( !pIdx->zColAff ){
  76275. /* The first time a column affinity string for a particular index is
  76276. ** required, it is allocated and populated here. It is then stored as
  76277. ** a member of the Index structure for subsequent use.
  76278. **
  76279. ** The column affinity string will eventually be deleted by
  76280. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  76281. ** up.
  76282. */
  76283. int n;
  76284. Table *pTab = pIdx->pTable;
  76285. sqlite3 *db = sqlite3VdbeDb(v);
  76286. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  76287. if( !pIdx->zColAff ){
  76288. db->mallocFailed = 1;
  76289. return 0;
  76290. }
  76291. for(n=0; n<pIdx->nColumn; n++){
  76292. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  76293. }
  76294. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  76295. pIdx->zColAff[n] = 0;
  76296. }
  76297. return pIdx->zColAff;
  76298. }
  76299. /*
  76300. ** Set P4 of the most recently inserted opcode to a column affinity
  76301. ** string for table pTab. A column affinity string has one character
  76302. ** for each column indexed by the index, according to the affinity of the
  76303. ** column:
  76304. **
  76305. ** Character Column affinity
  76306. ** ------------------------------
  76307. ** 'a' TEXT
  76308. ** 'b' NONE
  76309. ** 'c' NUMERIC
  76310. ** 'd' INTEGER
  76311. ** 'e' REAL
  76312. */
  76313. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  76314. /* The first time a column affinity string for a particular table
  76315. ** is required, it is allocated and populated here. It is then
  76316. ** stored as a member of the Table structure for subsequent use.
  76317. **
  76318. ** The column affinity string will eventually be deleted by
  76319. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  76320. */
  76321. if( !pTab->zColAff ){
  76322. char *zColAff;
  76323. int i;
  76324. sqlite3 *db = sqlite3VdbeDb(v);
  76325. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  76326. if( !zColAff ){
  76327. db->mallocFailed = 1;
  76328. return;
  76329. }
  76330. for(i=0; i<pTab->nCol; i++){
  76331. zColAff[i] = pTab->aCol[i].affinity;
  76332. }
  76333. zColAff[pTab->nCol] = '\0';
  76334. pTab->zColAff = zColAff;
  76335. }
  76336. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  76337. }
  76338. /*
  76339. ** Return non-zero if the table pTab in database iDb or any of its indices
  76340. ** have been opened at any point in the VDBE program beginning at location
  76341. ** iStartAddr throught the end of the program. This is used to see if
  76342. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  76343. ** run without using temporary table for the results of the SELECT.
  76344. */
  76345. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  76346. Vdbe *v = sqlite3GetVdbe(p);
  76347. int i;
  76348. int iEnd = sqlite3VdbeCurrentAddr(v);
  76349. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76350. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  76351. #endif
  76352. for(i=iStartAddr; i<iEnd; i++){
  76353. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  76354. assert( pOp!=0 );
  76355. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  76356. Index *pIndex;
  76357. int tnum = pOp->p2;
  76358. if( tnum==pTab->tnum ){
  76359. return 1;
  76360. }
  76361. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  76362. if( tnum==pIndex->tnum ){
  76363. return 1;
  76364. }
  76365. }
  76366. }
  76367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76368. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  76369. assert( pOp->p4.pVtab!=0 );
  76370. assert( pOp->p4type==P4_VTAB );
  76371. return 1;
  76372. }
  76373. #endif
  76374. }
  76375. return 0;
  76376. }
  76377. #ifndef SQLITE_OMIT_AUTOINCREMENT
  76378. /*
  76379. ** Locate or create an AutoincInfo structure associated with table pTab
  76380. ** which is in database iDb. Return the register number for the register
  76381. ** that holds the maximum rowid.
  76382. **
  76383. ** There is at most one AutoincInfo structure per table even if the
  76384. ** same table is autoincremented multiple times due to inserts within
  76385. ** triggers. A new AutoincInfo structure is created if this is the
  76386. ** first use of table pTab. On 2nd and subsequent uses, the original
  76387. ** AutoincInfo structure is used.
  76388. **
  76389. ** Three memory locations are allocated:
  76390. **
  76391. ** (1) Register to hold the name of the pTab table.
  76392. ** (2) Register to hold the maximum ROWID of pTab.
  76393. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  76394. **
  76395. ** The 2nd register is the one that is returned. That is all the
  76396. ** insert routine needs to know about.
  76397. */
  76398. static int autoIncBegin(
  76399. Parse *pParse, /* Parsing context */
  76400. int iDb, /* Index of the database holding pTab */
  76401. Table *pTab /* The table we are writing to */
  76402. ){
  76403. int memId = 0; /* Register holding maximum rowid */
  76404. if( pTab->tabFlags & TF_Autoincrement ){
  76405. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  76406. AutoincInfo *pInfo;
  76407. pInfo = pToplevel->pAinc;
  76408. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  76409. if( pInfo==0 ){
  76410. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  76411. if( pInfo==0 ) return 0;
  76412. pInfo->pNext = pToplevel->pAinc;
  76413. pToplevel->pAinc = pInfo;
  76414. pInfo->pTab = pTab;
  76415. pInfo->iDb = iDb;
  76416. pToplevel->nMem++; /* Register to hold name of table */
  76417. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  76418. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  76419. }
  76420. memId = pInfo->regCtr;
  76421. }
  76422. return memId;
  76423. }
  76424. /*
  76425. ** This routine generates code that will initialize all of the
  76426. ** register used by the autoincrement tracker.
  76427. */
  76428. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  76429. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  76430. sqlite3 *db = pParse->db; /* The database connection */
  76431. Db *pDb; /* Database only autoinc table */
  76432. int memId; /* Register holding max rowid */
  76433. int addr; /* A VDBE address */
  76434. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  76435. /* This routine is never called during trigger-generation. It is
  76436. ** only called from the top-level */
  76437. assert( pParse->pTriggerTab==0 );
  76438. assert( pParse==sqlite3ParseToplevel(pParse) );
  76439. assert( v ); /* We failed long ago if this is not so */
  76440. for(p = pParse->pAinc; p; p = p->pNext){
  76441. pDb = &db->aDb[p->iDb];
  76442. memId = p->regCtr;
  76443. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  76444. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  76445. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  76446. addr = sqlite3VdbeCurrentAddr(v);
  76447. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  76448. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  76449. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  76450. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  76451. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  76452. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  76453. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  76454. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  76455. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  76456. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  76457. sqlite3VdbeAddOp0(v, OP_Close);
  76458. }
  76459. }
  76460. /*
  76461. ** Update the maximum rowid for an autoincrement calculation.
  76462. **
  76463. ** This routine should be called when the top of the stack holds a
  76464. ** new rowid that is about to be inserted. If that new rowid is
  76465. ** larger than the maximum rowid in the memId memory cell, then the
  76466. ** memory cell is updated. The stack is unchanged.
  76467. */
  76468. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  76469. if( memId>0 ){
  76470. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  76471. }
  76472. }
  76473. /*
  76474. ** This routine generates the code needed to write autoincrement
  76475. ** maximum rowid values back into the sqlite_sequence register.
  76476. ** Every statement that might do an INSERT into an autoincrement
  76477. ** table (either directly or through triggers) needs to call this
  76478. ** routine just before the "exit" code.
  76479. */
  76480. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  76481. AutoincInfo *p;
  76482. Vdbe *v = pParse->pVdbe;
  76483. sqlite3 *db = pParse->db;
  76484. assert( v );
  76485. for(p = pParse->pAinc; p; p = p->pNext){
  76486. Db *pDb = &db->aDb[p->iDb];
  76487. int j1, j2, j3, j4, j5;
  76488. int iRec;
  76489. int memId = p->regCtr;
  76490. iRec = sqlite3GetTempReg(pParse);
  76491. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  76492. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  76493. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  76494. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  76495. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  76496. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  76497. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  76498. sqlite3VdbeJumpHere(v, j2);
  76499. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  76500. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  76501. sqlite3VdbeJumpHere(v, j4);
  76502. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  76503. sqlite3VdbeJumpHere(v, j1);
  76504. sqlite3VdbeJumpHere(v, j5);
  76505. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  76506. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  76507. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  76508. sqlite3VdbeAddOp0(v, OP_Close);
  76509. sqlite3ReleaseTempReg(pParse, iRec);
  76510. }
  76511. }
  76512. #else
  76513. /*
  76514. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  76515. ** above are all no-ops
  76516. */
  76517. # define autoIncBegin(A,B,C) (0)
  76518. # define autoIncStep(A,B,C)
  76519. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  76520. /*
  76521. ** Generate code for a co-routine that will evaluate a subquery one
  76522. ** row at a time.
  76523. **
  76524. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  76525. ** Information about the location of co-routine and the registers it will use
  76526. ** is returned by filling in the pDest object.
  76527. **
  76528. ** Registers are allocated as follows:
  76529. **
  76530. ** pDest->iSDParm The register holding the next entry-point of the
  76531. ** co-routine. Run the co-routine to its next breakpoint
  76532. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  76533. **
  76534. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  76535. ** co-routine. This register is 0 if the previous Yield
  76536. ** generated a new result row, or 1 if the subquery
  76537. ** has completed. If the Yield is called again
  76538. ** after this register becomes 1, then the VDBE will
  76539. ** halt with an SQLITE_INTERNAL error.
  76540. **
  76541. ** pDest->iSdst First result register.
  76542. **
  76543. ** pDest->nSdst Number of result registers.
  76544. **
  76545. ** This routine handles all of the register allocation and fills in the
  76546. ** pDest structure appropriately.
  76547. **
  76548. ** Here is a schematic of the generated code assuming that X is the
  76549. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  76550. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  76551. ** registers that hold the result set, reg[pDest->iSdst] through
  76552. ** reg[pDest->iSdst+pDest->nSdst-1]:
  76553. **
  76554. ** X <- A
  76555. ** EOF <- 0
  76556. ** goto B
  76557. ** A: setup for the SELECT
  76558. ** loop rows in the SELECT
  76559. ** load results into registers R..S
  76560. ** yield X
  76561. ** end loop
  76562. ** cleanup after the SELECT
  76563. ** EOF <- 1
  76564. ** yield X
  76565. ** halt-error
  76566. ** B:
  76567. **
  76568. ** To use this subroutine, the caller generates code as follows:
  76569. **
  76570. ** [ Co-routine generated by this subroutine, shown above ]
  76571. ** S: yield X
  76572. ** if EOF goto E
  76573. ** if skip this row, goto C
  76574. ** if terminate loop, goto E
  76575. ** deal with this row
  76576. ** C: goto S
  76577. ** E:
  76578. */
  76579. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  76580. int regYield; /* Register holding co-routine entry-point */
  76581. int regEof; /* Register holding co-routine completion flag */
  76582. int addrTop; /* Top of the co-routine */
  76583. int j1; /* Jump instruction */
  76584. int rc; /* Result code */
  76585. Vdbe *v; /* VDBE under construction */
  76586. regYield = ++pParse->nMem;
  76587. regEof = ++pParse->nMem;
  76588. v = sqlite3GetVdbe(pParse);
  76589. addrTop = sqlite3VdbeCurrentAddr(v);
  76590. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  76591. VdbeComment((v, "Co-routine entry point"));
  76592. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  76593. VdbeComment((v, "Co-routine completion flag"));
  76594. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  76595. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  76596. rc = sqlite3Select(pParse, pSelect, pDest);
  76597. assert( pParse->nErr==0 || rc );
  76598. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  76599. if( rc ) return rc;
  76600. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  76601. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  76602. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  76603. VdbeComment((v, "End of coroutine"));
  76604. sqlite3VdbeJumpHere(v, j1); /* label B: */
  76605. return rc;
  76606. }
  76607. /* Forward declaration */
  76608. static int xferOptimization(
  76609. Parse *pParse, /* Parser context */
  76610. Table *pDest, /* The table we are inserting into */
  76611. Select *pSelect, /* A SELECT statement to use as the data source */
  76612. int onError, /* How to handle constraint errors */
  76613. int iDbDest /* The database of pDest */
  76614. );
  76615. /*
  76616. ** This routine is call to handle SQL of the following forms:
  76617. **
  76618. ** insert into TABLE (IDLIST) values(EXPRLIST)
  76619. ** insert into TABLE (IDLIST) select
  76620. **
  76621. ** The IDLIST following the table name is always optional. If omitted,
  76622. ** then a list of all columns for the table is substituted. The IDLIST
  76623. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  76624. **
  76625. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  76626. ** statement above, and pSelect is NULL. For the second form, pList is
  76627. ** NULL and pSelect is a pointer to the select statement used to generate
  76628. ** data for the insert.
  76629. **
  76630. ** The code generated follows one of four templates. For a simple
  76631. ** select with data coming from a VALUES clause, the code executes
  76632. ** once straight down through. Pseudo-code follows (we call this
  76633. ** the "1st template"):
  76634. **
  76635. ** open write cursor to <table> and its indices
  76636. ** puts VALUES clause expressions onto the stack
  76637. ** write the resulting record into <table>
  76638. ** cleanup
  76639. **
  76640. ** The three remaining templates assume the statement is of the form
  76641. **
  76642. ** INSERT INTO <table> SELECT ...
  76643. **
  76644. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  76645. ** in other words if the SELECT pulls all columns from a single table
  76646. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  76647. ** if <table2> and <table1> are distinct tables but have identical
  76648. ** schemas, including all the same indices, then a special optimization
  76649. ** is invoked that copies raw records from <table2> over to <table1>.
  76650. ** See the xferOptimization() function for the implementation of this
  76651. ** template. This is the 2nd template.
  76652. **
  76653. ** open a write cursor to <table>
  76654. ** open read cursor on <table2>
  76655. ** transfer all records in <table2> over to <table>
  76656. ** close cursors
  76657. ** foreach index on <table>
  76658. ** open a write cursor on the <table> index
  76659. ** open a read cursor on the corresponding <table2> index
  76660. ** transfer all records from the read to the write cursors
  76661. ** close cursors
  76662. ** end foreach
  76663. **
  76664. ** The 3rd template is for when the second template does not apply
  76665. ** and the SELECT clause does not read from <table> at any time.
  76666. ** The generated code follows this template:
  76667. **
  76668. ** EOF <- 0
  76669. ** X <- A
  76670. ** goto B
  76671. ** A: setup for the SELECT
  76672. ** loop over the rows in the SELECT
  76673. ** load values into registers R..R+n
  76674. ** yield X
  76675. ** end loop
  76676. ** cleanup after the SELECT
  76677. ** EOF <- 1
  76678. ** yield X
  76679. ** goto A
  76680. ** B: open write cursor to <table> and its indices
  76681. ** C: yield X
  76682. ** if EOF goto D
  76683. ** insert the select result into <table> from R..R+n
  76684. ** goto C
  76685. ** D: cleanup
  76686. **
  76687. ** The 4th template is used if the insert statement takes its
  76688. ** values from a SELECT but the data is being inserted into a table
  76689. ** that is also read as part of the SELECT. In the third form,
  76690. ** we have to use a intermediate table to store the results of
  76691. ** the select. The template is like this:
  76692. **
  76693. ** EOF <- 0
  76694. ** X <- A
  76695. ** goto B
  76696. ** A: setup for the SELECT
  76697. ** loop over the tables in the SELECT
  76698. ** load value into register R..R+n
  76699. ** yield X
  76700. ** end loop
  76701. ** cleanup after the SELECT
  76702. ** EOF <- 1
  76703. ** yield X
  76704. ** halt-error
  76705. ** B: open temp table
  76706. ** L: yield X
  76707. ** if EOF goto M
  76708. ** insert row from R..R+n into temp table
  76709. ** goto L
  76710. ** M: open write cursor to <table> and its indices
  76711. ** rewind temp table
  76712. ** C: loop over rows of intermediate table
  76713. ** transfer values form intermediate table into <table>
  76714. ** end loop
  76715. ** D: cleanup
  76716. */
  76717. SQLITE_PRIVATE void sqlite3Insert(
  76718. Parse *pParse, /* Parser context */
  76719. SrcList *pTabList, /* Name of table into which we are inserting */
  76720. ExprList *pList, /* List of values to be inserted */
  76721. Select *pSelect, /* A SELECT statement to use as the data source */
  76722. IdList *pColumn, /* Column names corresponding to IDLIST. */
  76723. int onError /* How to handle constraint errors */
  76724. ){
  76725. sqlite3 *db; /* The main database structure */
  76726. Table *pTab; /* The table to insert into. aka TABLE */
  76727. char *zTab; /* Name of the table into which we are inserting */
  76728. const char *zDb; /* Name of the database holding this table */
  76729. int i, j, idx; /* Loop counters */
  76730. Vdbe *v; /* Generate code into this virtual machine */
  76731. Index *pIdx; /* For looping over indices of the table */
  76732. int nColumn; /* Number of columns in the data */
  76733. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  76734. int baseCur = 0; /* VDBE Cursor number for pTab */
  76735. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  76736. int endOfLoop; /* Label for the end of the insertion loop */
  76737. int useTempTable = 0; /* Store SELECT results in intermediate table */
  76738. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  76739. int addrInsTop = 0; /* Jump to label "D" */
  76740. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  76741. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  76742. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  76743. int iDb; /* Index of database holding TABLE */
  76744. Db *pDb; /* The database containing table being inserted into */
  76745. int appendFlag = 0; /* True if the insert is likely to be an append */
  76746. /* Register allocations */
  76747. int regFromSelect = 0;/* Base register for data coming from SELECT */
  76748. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  76749. int regRowCount = 0; /* Memory cell used for the row counter */
  76750. int regIns; /* Block of regs holding rowid+data being inserted */
  76751. int regRowid; /* registers holding insert rowid */
  76752. int regData; /* register holding first column to insert */
  76753. int regEof = 0; /* Register recording end of SELECT data */
  76754. int *aRegIdx = 0; /* One register allocated to each index */
  76755. #ifndef SQLITE_OMIT_TRIGGER
  76756. int isView; /* True if attempting to insert into a view */
  76757. Trigger *pTrigger; /* List of triggers on pTab, if required */
  76758. int tmask; /* Mask of trigger times */
  76759. #endif
  76760. db = pParse->db;
  76761. memset(&dest, 0, sizeof(dest));
  76762. if( pParse->nErr || db->mallocFailed ){
  76763. goto insert_cleanup;
  76764. }
  76765. /* Locate the table into which we will be inserting new information.
  76766. */
  76767. assert( pTabList->nSrc==1 );
  76768. zTab = pTabList->a[0].zName;
  76769. if( NEVER(zTab==0) ) goto insert_cleanup;
  76770. pTab = sqlite3SrcListLookup(pParse, pTabList);
  76771. if( pTab==0 ){
  76772. goto insert_cleanup;
  76773. }
  76774. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  76775. assert( iDb<db->nDb );
  76776. pDb = &db->aDb[iDb];
  76777. zDb = pDb->zName;
  76778. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  76779. goto insert_cleanup;
  76780. }
  76781. /* Figure out if we have any triggers and if the table being
  76782. ** inserted into is a view
  76783. */
  76784. #ifndef SQLITE_OMIT_TRIGGER
  76785. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  76786. isView = pTab->pSelect!=0;
  76787. #else
  76788. # define pTrigger 0
  76789. # define tmask 0
  76790. # define isView 0
  76791. #endif
  76792. #ifdef SQLITE_OMIT_VIEW
  76793. # undef isView
  76794. # define isView 0
  76795. #endif
  76796. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  76797. /* If pTab is really a view, make sure it has been initialized.
  76798. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  76799. ** module table).
  76800. */
  76801. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  76802. goto insert_cleanup;
  76803. }
  76804. /* Ensure that:
  76805. * (a) the table is not read-only,
  76806. * (b) that if it is a view then ON INSERT triggers exist
  76807. */
  76808. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  76809. goto insert_cleanup;
  76810. }
  76811. /* Allocate a VDBE
  76812. */
  76813. v = sqlite3GetVdbe(pParse);
  76814. if( v==0 ) goto insert_cleanup;
  76815. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  76816. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  76817. #ifndef SQLITE_OMIT_XFER_OPT
  76818. /* If the statement is of the form
  76819. **
  76820. ** INSERT INTO <table1> SELECT * FROM <table2>;
  76821. **
  76822. ** Then special optimizations can be applied that make the transfer
  76823. ** very fast and which reduce fragmentation of indices.
  76824. **
  76825. ** This is the 2nd template.
  76826. */
  76827. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  76828. assert( !pTrigger );
  76829. assert( pList==0 );
  76830. goto insert_end;
  76831. }
  76832. #endif /* SQLITE_OMIT_XFER_OPT */
  76833. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  76834. ** sqlite_sequence table and store it in memory cell regAutoinc.
  76835. */
  76836. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  76837. /* Figure out how many columns of data are supplied. If the data
  76838. ** is coming from a SELECT statement, then generate a co-routine that
  76839. ** produces a single row of the SELECT on each invocation. The
  76840. ** co-routine is the common header to the 3rd and 4th templates.
  76841. */
  76842. if( pSelect ){
  76843. /* Data is coming from a SELECT. Generate a co-routine to run that
  76844. ** SELECT. */
  76845. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  76846. if( rc ) goto insert_cleanup;
  76847. regEof = dest.iSDParm + 1;
  76848. regFromSelect = dest.iSdst;
  76849. assert( pSelect->pEList );
  76850. nColumn = pSelect->pEList->nExpr;
  76851. assert( dest.nSdst==nColumn );
  76852. /* Set useTempTable to TRUE if the result of the SELECT statement
  76853. ** should be written into a temporary table (template 4). Set to
  76854. ** FALSE if each* row of the SELECT can be written directly into
  76855. ** the destination table (template 3).
  76856. **
  76857. ** A temp table must be used if the table being updated is also one
  76858. ** of the tables being read by the SELECT statement. Also use a
  76859. ** temp table in the case of row triggers.
  76860. */
  76861. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  76862. useTempTable = 1;
  76863. }
  76864. if( useTempTable ){
  76865. /* Invoke the coroutine to extract information from the SELECT
  76866. ** and add it to a transient table srcTab. The code generated
  76867. ** here is from the 4th template:
  76868. **
  76869. ** B: open temp table
  76870. ** L: yield X
  76871. ** if EOF goto M
  76872. ** insert row from R..R+n into temp table
  76873. ** goto L
  76874. ** M: ...
  76875. */
  76876. int regRec; /* Register to hold packed record */
  76877. int regTempRowid; /* Register to hold temp table ROWID */
  76878. int addrTop; /* Label "L" */
  76879. int addrIf; /* Address of jump to M */
  76880. srcTab = pParse->nTab++;
  76881. regRec = sqlite3GetTempReg(pParse);
  76882. regTempRowid = sqlite3GetTempReg(pParse);
  76883. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  76884. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  76885. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  76886. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  76887. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  76888. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  76889. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  76890. sqlite3VdbeJumpHere(v, addrIf);
  76891. sqlite3ReleaseTempReg(pParse, regRec);
  76892. sqlite3ReleaseTempReg(pParse, regTempRowid);
  76893. }
  76894. }else{
  76895. /* This is the case if the data for the INSERT is coming from a VALUES
  76896. ** clause
  76897. */
  76898. NameContext sNC;
  76899. memset(&sNC, 0, sizeof(sNC));
  76900. sNC.pParse = pParse;
  76901. srcTab = -1;
  76902. assert( useTempTable==0 );
  76903. nColumn = pList ? pList->nExpr : 0;
  76904. for(i=0; i<nColumn; i++){
  76905. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  76906. goto insert_cleanup;
  76907. }
  76908. }
  76909. }
  76910. /* Make sure the number of columns in the source data matches the number
  76911. ** of columns to be inserted into the table.
  76912. */
  76913. if( IsVirtual(pTab) ){
  76914. for(i=0; i<pTab->nCol; i++){
  76915. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  76916. }
  76917. }
  76918. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  76919. sqlite3ErrorMsg(pParse,
  76920. "table %S has %d columns but %d values were supplied",
  76921. pTabList, 0, pTab->nCol-nHidden, nColumn);
  76922. goto insert_cleanup;
  76923. }
  76924. if( pColumn!=0 && nColumn!=pColumn->nId ){
  76925. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  76926. goto insert_cleanup;
  76927. }
  76928. /* If the INSERT statement included an IDLIST term, then make sure
  76929. ** all elements of the IDLIST really are columns of the table and
  76930. ** remember the column indices.
  76931. **
  76932. ** If the table has an INTEGER PRIMARY KEY column and that column
  76933. ** is named in the IDLIST, then record in the keyColumn variable
  76934. ** the index into IDLIST of the primary key column. keyColumn is
  76935. ** the index of the primary key as it appears in IDLIST, not as
  76936. ** is appears in the original table. (The index of the primary
  76937. ** key in the original table is pTab->iPKey.)
  76938. */
  76939. if( pColumn ){
  76940. for(i=0; i<pColumn->nId; i++){
  76941. pColumn->a[i].idx = -1;
  76942. }
  76943. for(i=0; i<pColumn->nId; i++){
  76944. for(j=0; j<pTab->nCol; j++){
  76945. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  76946. pColumn->a[i].idx = j;
  76947. if( j==pTab->iPKey ){
  76948. keyColumn = i;
  76949. }
  76950. break;
  76951. }
  76952. }
  76953. if( j>=pTab->nCol ){
  76954. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  76955. keyColumn = i;
  76956. }else{
  76957. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  76958. pTabList, 0, pColumn->a[i].zName);
  76959. pParse->checkSchema = 1;
  76960. goto insert_cleanup;
  76961. }
  76962. }
  76963. }
  76964. }
  76965. /* If there is no IDLIST term but the table has an integer primary
  76966. ** key, the set the keyColumn variable to the primary key column index
  76967. ** in the original table definition.
  76968. */
  76969. if( pColumn==0 && nColumn>0 ){
  76970. keyColumn = pTab->iPKey;
  76971. }
  76972. /* Initialize the count of rows to be inserted
  76973. */
  76974. if( db->flags & SQLITE_CountRows ){
  76975. regRowCount = ++pParse->nMem;
  76976. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  76977. }
  76978. /* If this is not a view, open the table and and all indices */
  76979. if( !isView ){
  76980. int nIdx;
  76981. baseCur = pParse->nTab;
  76982. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  76983. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  76984. if( aRegIdx==0 ){
  76985. goto insert_cleanup;
  76986. }
  76987. for(i=0; i<nIdx; i++){
  76988. aRegIdx[i] = ++pParse->nMem;
  76989. }
  76990. }
  76991. /* This is the top of the main insertion loop */
  76992. if( useTempTable ){
  76993. /* This block codes the top of loop only. The complete loop is the
  76994. ** following pseudocode (template 4):
  76995. **
  76996. ** rewind temp table
  76997. ** C: loop over rows of intermediate table
  76998. ** transfer values form intermediate table into <table>
  76999. ** end loop
  77000. ** D: ...
  77001. */
  77002. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  77003. addrCont = sqlite3VdbeCurrentAddr(v);
  77004. }else if( pSelect ){
  77005. /* This block codes the top of loop only. The complete loop is the
  77006. ** following pseudocode (template 3):
  77007. **
  77008. ** C: yield X
  77009. ** if EOF goto D
  77010. ** insert the select result into <table> from R..R+n
  77011. ** goto C
  77012. ** D: ...
  77013. */
  77014. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  77015. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  77016. }
  77017. /* Allocate registers for holding the rowid of the new row,
  77018. ** the content of the new row, and the assemblied row record.
  77019. */
  77020. regRowid = regIns = pParse->nMem+1;
  77021. pParse->nMem += pTab->nCol + 1;
  77022. if( IsVirtual(pTab) ){
  77023. regRowid++;
  77024. pParse->nMem++;
  77025. }
  77026. regData = regRowid+1;
  77027. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  77028. */
  77029. endOfLoop = sqlite3VdbeMakeLabel(v);
  77030. if( tmask & TRIGGER_BEFORE ){
  77031. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  77032. /* build the NEW.* reference row. Note that if there is an INTEGER
  77033. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  77034. ** translated into a unique ID for the row. But on a BEFORE trigger,
  77035. ** we do not know what the unique ID will be (because the insert has
  77036. ** not happened yet) so we substitute a rowid of -1
  77037. */
  77038. if( keyColumn<0 ){
  77039. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  77040. }else{
  77041. int j1;
  77042. if( useTempTable ){
  77043. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  77044. }else{
  77045. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  77046. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  77047. }
  77048. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  77049. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  77050. sqlite3VdbeJumpHere(v, j1);
  77051. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  77052. }
  77053. /* Cannot have triggers on a virtual table. If it were possible,
  77054. ** this block would have to account for hidden column.
  77055. */
  77056. assert( !IsVirtual(pTab) );
  77057. /* Create the new column data
  77058. */
  77059. for(i=0; i<pTab->nCol; i++){
  77060. if( pColumn==0 ){
  77061. j = i;
  77062. }else{
  77063. for(j=0; j<pColumn->nId; j++){
  77064. if( pColumn->a[j].idx==i ) break;
  77065. }
  77066. }
  77067. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  77068. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  77069. }else if( useTempTable ){
  77070. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  77071. }else{
  77072. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  77073. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  77074. }
  77075. }
  77076. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  77077. ** do not attempt any conversions before assembling the record.
  77078. ** If this is a real table, attempt conversions as required by the
  77079. ** table column affinities.
  77080. */
  77081. if( !isView ){
  77082. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  77083. sqlite3TableAffinityStr(v, pTab);
  77084. }
  77085. /* Fire BEFORE or INSTEAD OF triggers */
  77086. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  77087. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  77088. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  77089. }
  77090. /* Push the record number for the new entry onto the stack. The
  77091. ** record number is a randomly generate integer created by NewRowid
  77092. ** except when the table has an INTEGER PRIMARY KEY column, in which
  77093. ** case the record number is the same as that column.
  77094. */
  77095. if( !isView ){
  77096. if( IsVirtual(pTab) ){
  77097. /* The row that the VUpdate opcode will delete: none */
  77098. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  77099. }
  77100. if( keyColumn>=0 ){
  77101. if( useTempTable ){
  77102. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  77103. }else if( pSelect ){
  77104. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  77105. }else{
  77106. VdbeOp *pOp;
  77107. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  77108. pOp = sqlite3VdbeGetOp(v, -1);
  77109. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  77110. appendFlag = 1;
  77111. pOp->opcode = OP_NewRowid;
  77112. pOp->p1 = baseCur;
  77113. pOp->p2 = regRowid;
  77114. pOp->p3 = regAutoinc;
  77115. }
  77116. }
  77117. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  77118. ** to generate a unique primary key value.
  77119. */
  77120. if( !appendFlag ){
  77121. int j1;
  77122. if( !IsVirtual(pTab) ){
  77123. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  77124. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  77125. sqlite3VdbeJumpHere(v, j1);
  77126. }else{
  77127. j1 = sqlite3VdbeCurrentAddr(v);
  77128. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  77129. }
  77130. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  77131. }
  77132. }else if( IsVirtual(pTab) ){
  77133. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  77134. }else{
  77135. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  77136. appendFlag = 1;
  77137. }
  77138. autoIncStep(pParse, regAutoinc, regRowid);
  77139. /* Push onto the stack, data for all columns of the new entry, beginning
  77140. ** with the first column.
  77141. */
  77142. nHidden = 0;
  77143. for(i=0; i<pTab->nCol; i++){
  77144. int iRegStore = regRowid+1+i;
  77145. if( i==pTab->iPKey ){
  77146. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  77147. ** Whenever this column is read, the record number will be substituted
  77148. ** in its place. So will fill this column with a NULL to avoid
  77149. ** taking up data space with information that will never be used. */
  77150. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  77151. continue;
  77152. }
  77153. if( pColumn==0 ){
  77154. if( IsHiddenColumn(&pTab->aCol[i]) ){
  77155. assert( IsVirtual(pTab) );
  77156. j = -1;
  77157. nHidden++;
  77158. }else{
  77159. j = i - nHidden;
  77160. }
  77161. }else{
  77162. for(j=0; j<pColumn->nId; j++){
  77163. if( pColumn->a[j].idx==i ) break;
  77164. }
  77165. }
  77166. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  77167. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  77168. }else if( useTempTable ){
  77169. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  77170. }else if( pSelect ){
  77171. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  77172. }else{
  77173. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  77174. }
  77175. }
  77176. /* Generate code to check constraints and generate index keys and
  77177. ** do the insertion.
  77178. */
  77179. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77180. if( IsVirtual(pTab) ){
  77181. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  77182. sqlite3VtabMakeWritable(pParse, pTab);
  77183. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  77184. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  77185. sqlite3MayAbort(pParse);
  77186. }else
  77187. #endif
  77188. {
  77189. int isReplace; /* Set to true if constraints may cause a replace */
  77190. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  77191. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  77192. );
  77193. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  77194. sqlite3CompleteInsertion(
  77195. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  77196. );
  77197. }
  77198. }
  77199. /* Update the count of rows that are inserted
  77200. */
  77201. if( (db->flags & SQLITE_CountRows)!=0 ){
  77202. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  77203. }
  77204. if( pTrigger ){
  77205. /* Code AFTER triggers */
  77206. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  77207. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  77208. }
  77209. /* The bottom of the main insertion loop, if the data source
  77210. ** is a SELECT statement.
  77211. */
  77212. sqlite3VdbeResolveLabel(v, endOfLoop);
  77213. if( useTempTable ){
  77214. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  77215. sqlite3VdbeJumpHere(v, addrInsTop);
  77216. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  77217. }else if( pSelect ){
  77218. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  77219. sqlite3VdbeJumpHere(v, addrInsTop);
  77220. }
  77221. if( !IsVirtual(pTab) && !isView ){
  77222. /* Close all tables opened */
  77223. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  77224. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  77225. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  77226. }
  77227. }
  77228. insert_end:
  77229. /* Update the sqlite_sequence table by storing the content of the
  77230. ** maximum rowid counter values recorded while inserting into
  77231. ** autoincrement tables.
  77232. */
  77233. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  77234. sqlite3AutoincrementEnd(pParse);
  77235. }
  77236. /*
  77237. ** Return the number of rows inserted. If this routine is
  77238. ** generating code because of a call to sqlite3NestedParse(), do not
  77239. ** invoke the callback function.
  77240. */
  77241. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  77242. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  77243. sqlite3VdbeSetNumCols(v, 1);
  77244. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  77245. }
  77246. insert_cleanup:
  77247. sqlite3SrcListDelete(db, pTabList);
  77248. sqlite3ExprListDelete(db, pList);
  77249. sqlite3SelectDelete(db, pSelect);
  77250. sqlite3IdListDelete(db, pColumn);
  77251. sqlite3DbFree(db, aRegIdx);
  77252. }
  77253. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  77254. ** thely may interfere with compilation of other functions in this file
  77255. ** (or in another file, if this file becomes part of the amalgamation). */
  77256. #ifdef isView
  77257. #undef isView
  77258. #endif
  77259. #ifdef pTrigger
  77260. #undef pTrigger
  77261. #endif
  77262. #ifdef tmask
  77263. #undef tmask
  77264. #endif
  77265. /*
  77266. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  77267. **
  77268. ** The input is a range of consecutive registers as follows:
  77269. **
  77270. ** 1. The rowid of the row after the update.
  77271. **
  77272. ** 2. The data in the first column of the entry after the update.
  77273. **
  77274. ** i. Data from middle columns...
  77275. **
  77276. ** N. The data in the last column of the entry after the update.
  77277. **
  77278. ** The regRowid parameter is the index of the register containing (1).
  77279. **
  77280. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  77281. ** the address of a register containing the rowid before the update takes
  77282. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  77283. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  77284. ** indicates that the rowid was explicitly specified as part of the
  77285. ** INSERT statement. If rowidChng is false, it means that the rowid is
  77286. ** computed automatically in an insert or that the rowid value is not
  77287. ** modified by an update.
  77288. **
  77289. ** The code generated by this routine store new index entries into
  77290. ** registers identified by aRegIdx[]. No index entry is created for
  77291. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  77292. ** the same as the order of indices on the linked list of indices
  77293. ** attached to the table.
  77294. **
  77295. ** This routine also generates code to check constraints. NOT NULL,
  77296. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  77297. ** then the appropriate action is performed. There are five possible
  77298. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  77299. **
  77300. ** Constraint type Action What Happens
  77301. ** --------------- ---------- ----------------------------------------
  77302. ** any ROLLBACK The current transaction is rolled back and
  77303. ** sqlite3_exec() returns immediately with a
  77304. ** return code of SQLITE_CONSTRAINT.
  77305. **
  77306. ** any ABORT Back out changes from the current command
  77307. ** only (do not do a complete rollback) then
  77308. ** cause sqlite3_exec() to return immediately
  77309. ** with SQLITE_CONSTRAINT.
  77310. **
  77311. ** any FAIL Sqlite3_exec() returns immediately with a
  77312. ** return code of SQLITE_CONSTRAINT. The
  77313. ** transaction is not rolled back and any
  77314. ** prior changes are retained.
  77315. **
  77316. ** any IGNORE The record number and data is popped from
  77317. ** the stack and there is an immediate jump
  77318. ** to label ignoreDest.
  77319. **
  77320. ** NOT NULL REPLACE The NULL value is replace by the default
  77321. ** value for that column. If the default value
  77322. ** is NULL, the action is the same as ABORT.
  77323. **
  77324. ** UNIQUE REPLACE The other row that conflicts with the row
  77325. ** being inserted is removed.
  77326. **
  77327. ** CHECK REPLACE Illegal. The results in an exception.
  77328. **
  77329. ** Which action to take is determined by the overrideError parameter.
  77330. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  77331. ** is used. Or if pParse->onError==OE_Default then the onError value
  77332. ** for the constraint is used.
  77333. **
  77334. ** The calling routine must open a read/write cursor for pTab with
  77335. ** cursor number "baseCur". All indices of pTab must also have open
  77336. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  77337. ** Except, if there is no possibility of a REPLACE action then
  77338. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  77339. */
  77340. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  77341. Parse *pParse, /* The parser context */
  77342. Table *pTab, /* the table into which we are inserting */
  77343. int baseCur, /* Index of a read/write cursor pointing at pTab */
  77344. int regRowid, /* Index of the range of input registers */
  77345. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  77346. int rowidChng, /* True if the rowid might collide with existing entry */
  77347. int isUpdate, /* True for UPDATE, False for INSERT */
  77348. int overrideError, /* Override onError to this if not OE_Default */
  77349. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  77350. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  77351. ){
  77352. int i; /* loop counter */
  77353. Vdbe *v; /* VDBE under constrution */
  77354. int nCol; /* Number of columns */
  77355. int onError; /* Conflict resolution strategy */
  77356. int j1; /* Addresss of jump instruction */
  77357. int j2 = 0, j3; /* Addresses of jump instructions */
  77358. int regData; /* Register containing first data column */
  77359. int iCur; /* Table cursor number */
  77360. Index *pIdx; /* Pointer to one of the indices */
  77361. sqlite3 *db; /* Database connection */
  77362. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  77363. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  77364. db = pParse->db;
  77365. v = sqlite3GetVdbe(pParse);
  77366. assert( v!=0 );
  77367. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  77368. nCol = pTab->nCol;
  77369. regData = regRowid + 1;
  77370. /* Test all NOT NULL constraints.
  77371. */
  77372. for(i=0; i<nCol; i++){
  77373. if( i==pTab->iPKey ){
  77374. continue;
  77375. }
  77376. onError = pTab->aCol[i].notNull;
  77377. if( onError==OE_None ) continue;
  77378. if( overrideError!=OE_Default ){
  77379. onError = overrideError;
  77380. }else if( onError==OE_Default ){
  77381. onError = OE_Abort;
  77382. }
  77383. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  77384. onError = OE_Abort;
  77385. }
  77386. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  77387. || onError==OE_Ignore || onError==OE_Replace );
  77388. switch( onError ){
  77389. case OE_Abort:
  77390. sqlite3MayAbort(pParse);
  77391. case OE_Rollback:
  77392. case OE_Fail: {
  77393. char *zMsg;
  77394. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  77395. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  77396. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  77397. pTab->zName, pTab->aCol[i].zName);
  77398. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  77399. break;
  77400. }
  77401. case OE_Ignore: {
  77402. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  77403. break;
  77404. }
  77405. default: {
  77406. assert( onError==OE_Replace );
  77407. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  77408. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  77409. sqlite3VdbeJumpHere(v, j1);
  77410. break;
  77411. }
  77412. }
  77413. }
  77414. /* Test all CHECK constraints
  77415. */
  77416. #ifndef SQLITE_OMIT_CHECK
  77417. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  77418. ExprList *pCheck = pTab->pCheck;
  77419. pParse->ckBase = regData;
  77420. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  77421. for(i=0; i<pCheck->nExpr; i++){
  77422. int allOk = sqlite3VdbeMakeLabel(v);
  77423. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  77424. if( onError==OE_Ignore ){
  77425. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77426. }else{
  77427. char *zConsName = pCheck->a[i].zName;
  77428. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  77429. if( zConsName ){
  77430. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  77431. }else{
  77432. zConsName = 0;
  77433. }
  77434. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  77435. onError, zConsName, P4_DYNAMIC);
  77436. }
  77437. sqlite3VdbeResolveLabel(v, allOk);
  77438. }
  77439. }
  77440. #endif /* !defined(SQLITE_OMIT_CHECK) */
  77441. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  77442. ** of the new record does not previously exist. Except, if this
  77443. ** is an UPDATE and the primary key is not changing, that is OK.
  77444. */
  77445. if( rowidChng ){
  77446. onError = pTab->keyConf;
  77447. if( overrideError!=OE_Default ){
  77448. onError = overrideError;
  77449. }else if( onError==OE_Default ){
  77450. onError = OE_Abort;
  77451. }
  77452. if( isUpdate ){
  77453. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  77454. }
  77455. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  77456. switch( onError ){
  77457. default: {
  77458. onError = OE_Abort;
  77459. /* Fall thru into the next case */
  77460. }
  77461. case OE_Rollback:
  77462. case OE_Abort:
  77463. case OE_Fail: {
  77464. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  77465. onError, "PRIMARY KEY must be unique", P4_STATIC);
  77466. break;
  77467. }
  77468. case OE_Replace: {
  77469. /* If there are DELETE triggers on this table and the
  77470. ** recursive-triggers flag is set, call GenerateRowDelete() to
  77471. ** remove the conflicting row from the table. This will fire
  77472. ** the triggers and remove both the table and index b-tree entries.
  77473. **
  77474. ** Otherwise, if there are no triggers or the recursive-triggers
  77475. ** flag is not set, but the table has one or more indexes, call
  77476. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  77477. ** only. The table b-tree entry will be replaced by the new entry
  77478. ** when it is inserted.
  77479. **
  77480. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  77481. ** also invoke MultiWrite() to indicate that this VDBE may require
  77482. ** statement rollback (if the statement is aborted after the delete
  77483. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  77484. ** but being more selective here allows statements like:
  77485. **
  77486. ** REPLACE INTO t(rowid) VALUES($newrowid)
  77487. **
  77488. ** to run without a statement journal if there are no indexes on the
  77489. ** table.
  77490. */
  77491. Trigger *pTrigger = 0;
  77492. if( db->flags&SQLITE_RecTriggers ){
  77493. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  77494. }
  77495. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  77496. sqlite3MultiWrite(pParse);
  77497. sqlite3GenerateRowDelete(
  77498. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  77499. );
  77500. }else if( pTab->pIndex ){
  77501. sqlite3MultiWrite(pParse);
  77502. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  77503. }
  77504. seenReplace = 1;
  77505. break;
  77506. }
  77507. case OE_Ignore: {
  77508. assert( seenReplace==0 );
  77509. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77510. break;
  77511. }
  77512. }
  77513. sqlite3VdbeJumpHere(v, j3);
  77514. if( isUpdate ){
  77515. sqlite3VdbeJumpHere(v, j2);
  77516. }
  77517. }
  77518. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  77519. ** index and making sure that duplicate entries do not already exist.
  77520. ** Add the new records to the indices as we go.
  77521. */
  77522. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  77523. int regIdx;
  77524. int regR;
  77525. int addrSkipRow = 0;
  77526. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  77527. if( pIdx->pPartIdxWhere ){
  77528. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
  77529. addrSkipRow = sqlite3VdbeMakeLabel(v);
  77530. pParse->ckBase = regData;
  77531. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
  77532. SQLITE_JUMPIFNULL);
  77533. pParse->ckBase = 0;
  77534. }
  77535. /* Create a key for accessing the index entry */
  77536. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  77537. for(i=0; i<pIdx->nColumn; i++){
  77538. int idx = pIdx->aiColumn[i];
  77539. if( idx==pTab->iPKey ){
  77540. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  77541. }else{
  77542. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  77543. }
  77544. }
  77545. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  77546. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  77547. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  77548. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  77549. /* Find out what action to take in case there is an indexing conflict */
  77550. onError = pIdx->onError;
  77551. if( onError==OE_None ){
  77552. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  77553. sqlite3VdbeResolveLabel(v, addrSkipRow);
  77554. continue; /* pIdx is not a UNIQUE index */
  77555. }
  77556. if( overrideError!=OE_Default ){
  77557. onError = overrideError;
  77558. }else if( onError==OE_Default ){
  77559. onError = OE_Abort;
  77560. }
  77561. if( seenReplace ){
  77562. if( onError==OE_Ignore ) onError = OE_Replace;
  77563. else if( onError==OE_Fail ) onError = OE_Abort;
  77564. }
  77565. /* Check to see if the new index entry will be unique */
  77566. regR = sqlite3GetTempReg(pParse);
  77567. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  77568. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  77569. regR, SQLITE_INT_TO_PTR(regIdx),
  77570. P4_INT32);
  77571. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  77572. /* Generate code that executes if the new index entry is not unique */
  77573. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  77574. || onError==OE_Ignore || onError==OE_Replace );
  77575. switch( onError ){
  77576. case OE_Rollback:
  77577. case OE_Abort:
  77578. case OE_Fail: {
  77579. int j;
  77580. StrAccum errMsg;
  77581. const char *zSep;
  77582. char *zErr;
  77583. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  77584. errMsg.db = db;
  77585. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  77586. for(j=0; j<pIdx->nColumn; j++){
  77587. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  77588. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  77589. zSep = ", ";
  77590. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  77591. }
  77592. sqlite3StrAccumAppend(&errMsg,
  77593. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  77594. zErr = sqlite3StrAccumFinish(&errMsg);
  77595. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  77596. onError, zErr, 0);
  77597. sqlite3DbFree(errMsg.db, zErr);
  77598. break;
  77599. }
  77600. case OE_Ignore: {
  77601. assert( seenReplace==0 );
  77602. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  77603. break;
  77604. }
  77605. default: {
  77606. Trigger *pTrigger = 0;
  77607. assert( onError==OE_Replace );
  77608. sqlite3MultiWrite(pParse);
  77609. if( db->flags&SQLITE_RecTriggers ){
  77610. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  77611. }
  77612. sqlite3GenerateRowDelete(
  77613. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  77614. );
  77615. seenReplace = 1;
  77616. break;
  77617. }
  77618. }
  77619. sqlite3VdbeJumpHere(v, j3);
  77620. sqlite3VdbeResolveLabel(v, addrSkipRow);
  77621. sqlite3ReleaseTempReg(pParse, regR);
  77622. }
  77623. if( pbMayReplace ){
  77624. *pbMayReplace = seenReplace;
  77625. }
  77626. }
  77627. /*
  77628. ** This routine generates code to finish the INSERT or UPDATE operation
  77629. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  77630. ** A consecutive range of registers starting at regRowid contains the
  77631. ** rowid and the content to be inserted.
  77632. **
  77633. ** The arguments to this routine should be the same as the first six
  77634. ** arguments to sqlite3GenerateConstraintChecks.
  77635. */
  77636. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  77637. Parse *pParse, /* The parser context */
  77638. Table *pTab, /* the table into which we are inserting */
  77639. int baseCur, /* Index of a read/write cursor pointing at pTab */
  77640. int regRowid, /* Range of content */
  77641. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  77642. int isUpdate, /* True for UPDATE, False for INSERT */
  77643. int appendBias, /* True if this is likely to be an append */
  77644. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  77645. ){
  77646. int i;
  77647. Vdbe *v;
  77648. Index *pIdx;
  77649. u8 pik_flags;
  77650. int regData;
  77651. int regRec;
  77652. v = sqlite3GetVdbe(pParse);
  77653. assert( v!=0 );
  77654. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  77655. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  77656. if( aRegIdx[i]==0 ) continue;
  77657. if( pIdx->pPartIdxWhere ){
  77658. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  77659. }
  77660. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  77661. if( useSeekResult ){
  77662. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  77663. }
  77664. }
  77665. regData = regRowid + 1;
  77666. regRec = sqlite3GetTempReg(pParse);
  77667. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  77668. sqlite3TableAffinityStr(v, pTab);
  77669. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  77670. if( pParse->nested ){
  77671. pik_flags = 0;
  77672. }else{
  77673. pik_flags = OPFLAG_NCHANGE;
  77674. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  77675. }
  77676. if( appendBias ){
  77677. pik_flags |= OPFLAG_APPEND;
  77678. }
  77679. if( useSeekResult ){
  77680. pik_flags |= OPFLAG_USESEEKRESULT;
  77681. }
  77682. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  77683. if( !pParse->nested ){
  77684. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  77685. }
  77686. sqlite3VdbeChangeP5(v, pik_flags);
  77687. }
  77688. /*
  77689. ** Generate code that will open cursors for a table and for all
  77690. ** indices of that table. The "baseCur" parameter is the cursor number used
  77691. ** for the table. Indices are opened on subsequent cursors.
  77692. **
  77693. ** Return the number of indices on the table.
  77694. */
  77695. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  77696. Parse *pParse, /* Parsing context */
  77697. Table *pTab, /* Table to be opened */
  77698. int baseCur, /* Cursor number assigned to the table */
  77699. int op /* OP_OpenRead or OP_OpenWrite */
  77700. ){
  77701. int i;
  77702. int iDb;
  77703. Index *pIdx;
  77704. Vdbe *v;
  77705. if( IsVirtual(pTab) ) return 0;
  77706. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  77707. v = sqlite3GetVdbe(pParse);
  77708. assert( v!=0 );
  77709. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  77710. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  77711. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  77712. assert( pIdx->pSchema==pTab->pSchema );
  77713. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  77714. (char*)pKey, P4_KEYINFO_HANDOFF);
  77715. VdbeComment((v, "%s", pIdx->zName));
  77716. }
  77717. if( pParse->nTab<baseCur+i ){
  77718. pParse->nTab = baseCur+i;
  77719. }
  77720. return i-1;
  77721. }
  77722. #ifdef SQLITE_TEST
  77723. /*
  77724. ** The following global variable is incremented whenever the
  77725. ** transfer optimization is used. This is used for testing
  77726. ** purposes only - to make sure the transfer optimization really
  77727. ** is happening when it is suppose to.
  77728. */
  77729. SQLITE_API int sqlite3_xferopt_count;
  77730. #endif /* SQLITE_TEST */
  77731. #ifndef SQLITE_OMIT_XFER_OPT
  77732. /*
  77733. ** Check to collation names to see if they are compatible.
  77734. */
  77735. static int xferCompatibleCollation(const char *z1, const char *z2){
  77736. if( z1==0 ){
  77737. return z2==0;
  77738. }
  77739. if( z2==0 ){
  77740. return 0;
  77741. }
  77742. return sqlite3StrICmp(z1, z2)==0;
  77743. }
  77744. /*
  77745. ** Check to see if index pSrc is compatible as a source of data
  77746. ** for index pDest in an insert transfer optimization. The rules
  77747. ** for a compatible index:
  77748. **
  77749. ** * The index is over the same set of columns
  77750. ** * The same DESC and ASC markings occurs on all columns
  77751. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  77752. ** * The same collating sequence on each column
  77753. ** * The index has the exact same WHERE clause
  77754. */
  77755. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  77756. int i;
  77757. assert( pDest && pSrc );
  77758. assert( pDest->pTable!=pSrc->pTable );
  77759. if( pDest->nColumn!=pSrc->nColumn ){
  77760. return 0; /* Different number of columns */
  77761. }
  77762. if( pDest->onError!=pSrc->onError ){
  77763. return 0; /* Different conflict resolution strategies */
  77764. }
  77765. for(i=0; i<pSrc->nColumn; i++){
  77766. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  77767. return 0; /* Different columns indexed */
  77768. }
  77769. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  77770. return 0; /* Different sort orders */
  77771. }
  77772. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  77773. return 0; /* Different collating sequences */
  77774. }
  77775. }
  77776. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  77777. return 0; /* Different WHERE clauses */
  77778. }
  77779. /* If no test above fails then the indices must be compatible */
  77780. return 1;
  77781. }
  77782. /*
  77783. ** Attempt the transfer optimization on INSERTs of the form
  77784. **
  77785. ** INSERT INTO tab1 SELECT * FROM tab2;
  77786. **
  77787. ** The xfer optimization transfers raw records from tab2 over to tab1.
  77788. ** Columns are not decoded and reassemblied, which greatly improves
  77789. ** performance. Raw index records are transferred in the same way.
  77790. **
  77791. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  77792. ** There are lots of rules for determining compatibility - see comments
  77793. ** embedded in the code for details.
  77794. **
  77795. ** This routine returns TRUE if the optimization is guaranteed to be used.
  77796. ** Sometimes the xfer optimization will only work if the destination table
  77797. ** is empty - a factor that can only be determined at run-time. In that
  77798. ** case, this routine generates code for the xfer optimization but also
  77799. ** does a test to see if the destination table is empty and jumps over the
  77800. ** xfer optimization code if the test fails. In that case, this routine
  77801. ** returns FALSE so that the caller will know to go ahead and generate
  77802. ** an unoptimized transfer. This routine also returns FALSE if there
  77803. ** is no chance that the xfer optimization can be applied.
  77804. **
  77805. ** This optimization is particularly useful at making VACUUM run faster.
  77806. */
  77807. static int xferOptimization(
  77808. Parse *pParse, /* Parser context */
  77809. Table *pDest, /* The table we are inserting into */
  77810. Select *pSelect, /* A SELECT statement to use as the data source */
  77811. int onError, /* How to handle constraint errors */
  77812. int iDbDest /* The database of pDest */
  77813. ){
  77814. ExprList *pEList; /* The result set of the SELECT */
  77815. Table *pSrc; /* The table in the FROM clause of SELECT */
  77816. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  77817. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  77818. int i; /* Loop counter */
  77819. int iDbSrc; /* The database of pSrc */
  77820. int iSrc, iDest; /* Cursors from source and destination */
  77821. int addr1, addr2; /* Loop addresses */
  77822. int emptyDestTest; /* Address of test for empty pDest */
  77823. int emptySrcTest; /* Address of test for empty pSrc */
  77824. Vdbe *v; /* The VDBE we are building */
  77825. KeyInfo *pKey; /* Key information for an index */
  77826. int regAutoinc; /* Memory register used by AUTOINC */
  77827. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  77828. int regData, regRowid; /* Registers holding data and rowid */
  77829. if( pSelect==0 ){
  77830. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  77831. }
  77832. if( sqlite3TriggerList(pParse, pDest) ){
  77833. return 0; /* tab1 must not have triggers */
  77834. }
  77835. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77836. if( pDest->tabFlags & TF_Virtual ){
  77837. return 0; /* tab1 must not be a virtual table */
  77838. }
  77839. #endif
  77840. if( onError==OE_Default ){
  77841. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  77842. if( onError==OE_Default ) onError = OE_Abort;
  77843. }
  77844. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  77845. if( pSelect->pSrc->nSrc!=1 ){
  77846. return 0; /* FROM clause must have exactly one term */
  77847. }
  77848. if( pSelect->pSrc->a[0].pSelect ){
  77849. return 0; /* FROM clause cannot contain a subquery */
  77850. }
  77851. if( pSelect->pWhere ){
  77852. return 0; /* SELECT may not have a WHERE clause */
  77853. }
  77854. if( pSelect->pOrderBy ){
  77855. return 0; /* SELECT may not have an ORDER BY clause */
  77856. }
  77857. /* Do not need to test for a HAVING clause. If HAVING is present but
  77858. ** there is no ORDER BY, we will get an error. */
  77859. if( pSelect->pGroupBy ){
  77860. return 0; /* SELECT may not have a GROUP BY clause */
  77861. }
  77862. if( pSelect->pLimit ){
  77863. return 0; /* SELECT may not have a LIMIT clause */
  77864. }
  77865. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  77866. if( pSelect->pPrior ){
  77867. return 0; /* SELECT may not be a compound query */
  77868. }
  77869. if( pSelect->selFlags & SF_Distinct ){
  77870. return 0; /* SELECT may not be DISTINCT */
  77871. }
  77872. pEList = pSelect->pEList;
  77873. assert( pEList!=0 );
  77874. if( pEList->nExpr!=1 ){
  77875. return 0; /* The result set must have exactly one column */
  77876. }
  77877. assert( pEList->a[0].pExpr );
  77878. if( pEList->a[0].pExpr->op!=TK_ALL ){
  77879. return 0; /* The result set must be the special operator "*" */
  77880. }
  77881. /* At this point we have established that the statement is of the
  77882. ** correct syntactic form to participate in this optimization. Now
  77883. ** we have to check the semantics.
  77884. */
  77885. pItem = pSelect->pSrc->a;
  77886. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  77887. if( pSrc==0 ){
  77888. return 0; /* FROM clause does not contain a real table */
  77889. }
  77890. if( pSrc==pDest ){
  77891. return 0; /* tab1 and tab2 may not be the same table */
  77892. }
  77893. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77894. if( pSrc->tabFlags & TF_Virtual ){
  77895. return 0; /* tab2 must not be a virtual table */
  77896. }
  77897. #endif
  77898. if( pSrc->pSelect ){
  77899. return 0; /* tab2 may not be a view */
  77900. }
  77901. if( pDest->nCol!=pSrc->nCol ){
  77902. return 0; /* Number of columns must be the same in tab1 and tab2 */
  77903. }
  77904. if( pDest->iPKey!=pSrc->iPKey ){
  77905. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  77906. }
  77907. for(i=0; i<pDest->nCol; i++){
  77908. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  77909. return 0; /* Affinity must be the same on all columns */
  77910. }
  77911. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  77912. return 0; /* Collating sequence must be the same on all columns */
  77913. }
  77914. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  77915. return 0; /* tab2 must be NOT NULL if tab1 is */
  77916. }
  77917. }
  77918. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  77919. if( pDestIdx->onError!=OE_None ){
  77920. destHasUniqueIdx = 1;
  77921. }
  77922. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  77923. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  77924. }
  77925. if( pSrcIdx==0 ){
  77926. return 0; /* pDestIdx has no corresponding index in pSrc */
  77927. }
  77928. }
  77929. #ifndef SQLITE_OMIT_CHECK
  77930. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  77931. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  77932. }
  77933. #endif
  77934. #ifndef SQLITE_OMIT_FOREIGN_KEY
  77935. /* Disallow the transfer optimization if the destination table constains
  77936. ** any foreign key constraints. This is more restrictive than necessary.
  77937. ** But the main beneficiary of the transfer optimization is the VACUUM
  77938. ** command, and the VACUUM command disables foreign key constraints. So
  77939. ** the extra complication to make this rule less restrictive is probably
  77940. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  77941. */
  77942. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  77943. return 0;
  77944. }
  77945. #endif
  77946. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  77947. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  77948. }
  77949. /* If we get this far, it means that the xfer optimization is at
  77950. ** least a possibility, though it might only work if the destination
  77951. ** table (tab1) is initially empty.
  77952. */
  77953. #ifdef SQLITE_TEST
  77954. sqlite3_xferopt_count++;
  77955. #endif
  77956. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  77957. v = sqlite3GetVdbe(pParse);
  77958. sqlite3CodeVerifySchema(pParse, iDbSrc);
  77959. iSrc = pParse->nTab++;
  77960. iDest = pParse->nTab++;
  77961. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  77962. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  77963. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  77964. || destHasUniqueIdx /* (2) */
  77965. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  77966. ){
  77967. /* In some circumstances, we are able to run the xfer optimization
  77968. ** only if the destination table is initially empty. This code makes
  77969. ** that determination. Conditions under which the destination must
  77970. ** be empty:
  77971. **
  77972. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  77973. ** (If the destination is not initially empty, the rowid fields
  77974. ** of index entries might need to change.)
  77975. **
  77976. ** (2) The destination has a unique index. (The xfer optimization
  77977. ** is unable to test uniqueness.)
  77978. **
  77979. ** (3) onError is something other than OE_Abort and OE_Rollback.
  77980. */
  77981. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  77982. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  77983. sqlite3VdbeJumpHere(v, addr1);
  77984. }else{
  77985. emptyDestTest = 0;
  77986. }
  77987. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  77988. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  77989. regData = sqlite3GetTempReg(pParse);
  77990. regRowid = sqlite3GetTempReg(pParse);
  77991. if( pDest->iPKey>=0 ){
  77992. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  77993. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  77994. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  77995. onError, "PRIMARY KEY must be unique", P4_STATIC);
  77996. sqlite3VdbeJumpHere(v, addr2);
  77997. autoIncStep(pParse, regAutoinc, regRowid);
  77998. }else if( pDest->pIndex==0 ){
  77999. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  78000. }else{
  78001. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  78002. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  78003. }
  78004. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  78005. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  78006. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  78007. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  78008. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  78009. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  78010. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  78011. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  78012. }
  78013. assert( pSrcIdx );
  78014. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  78015. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78016. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  78017. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  78018. (char*)pKey, P4_KEYINFO_HANDOFF);
  78019. VdbeComment((v, "%s", pSrcIdx->zName));
  78020. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  78021. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  78022. (char*)pKey, P4_KEYINFO_HANDOFF);
  78023. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  78024. VdbeComment((v, "%s", pDestIdx->zName));
  78025. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  78026. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  78027. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  78028. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  78029. sqlite3VdbeJumpHere(v, addr1);
  78030. }
  78031. sqlite3VdbeJumpHere(v, emptySrcTest);
  78032. sqlite3ReleaseTempReg(pParse, regRowid);
  78033. sqlite3ReleaseTempReg(pParse, regData);
  78034. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  78035. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78036. if( emptyDestTest ){
  78037. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  78038. sqlite3VdbeJumpHere(v, emptyDestTest);
  78039. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  78040. return 0;
  78041. }else{
  78042. return 1;
  78043. }
  78044. }
  78045. #endif /* SQLITE_OMIT_XFER_OPT */
  78046. /************** End of insert.c **********************************************/
  78047. /************** Begin file legacy.c ******************************************/
  78048. /*
  78049. ** 2001 September 15
  78050. **
  78051. ** The author disclaims copyright to this source code. In place of
  78052. ** a legal notice, here is a blessing:
  78053. **
  78054. ** May you do good and not evil.
  78055. ** May you find forgiveness for yourself and forgive others.
  78056. ** May you share freely, never taking more than you give.
  78057. **
  78058. *************************************************************************
  78059. ** Main file for the SQLite library. The routines in this file
  78060. ** implement the programmer interface to the library. Routines in
  78061. ** other files are for internal use by SQLite and should not be
  78062. ** accessed by users of the library.
  78063. */
  78064. /*
  78065. ** Execute SQL code. Return one of the SQLITE_ success/failure
  78066. ** codes. Also write an error message into memory obtained from
  78067. ** malloc() and make *pzErrMsg point to that message.
  78068. **
  78069. ** If the SQL is a query, then for each row in the query result
  78070. ** the xCallback() function is called. pArg becomes the first
  78071. ** argument to xCallback(). If xCallback=NULL then no callback
  78072. ** is invoked, even for queries.
  78073. */
  78074. SQLITE_API int sqlite3_exec(
  78075. sqlite3 *db, /* The database on which the SQL executes */
  78076. const char *zSql, /* The SQL to be executed */
  78077. sqlite3_callback xCallback, /* Invoke this callback routine */
  78078. void *pArg, /* First argument to xCallback() */
  78079. char **pzErrMsg /* Write error messages here */
  78080. ){
  78081. int rc = SQLITE_OK; /* Return code */
  78082. const char *zLeftover; /* Tail of unprocessed SQL */
  78083. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  78084. char **azCols = 0; /* Names of result columns */
  78085. int callbackIsInit; /* True if callback data is initialized */
  78086. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  78087. if( zSql==0 ) zSql = "";
  78088. sqlite3_mutex_enter(db->mutex);
  78089. sqlite3Error(db, SQLITE_OK, 0);
  78090. while( rc==SQLITE_OK && zSql[0] ){
  78091. int nCol;
  78092. char **azVals = 0;
  78093. pStmt = 0;
  78094. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  78095. assert( rc==SQLITE_OK || pStmt==0 );
  78096. if( rc!=SQLITE_OK ){
  78097. continue;
  78098. }
  78099. if( !pStmt ){
  78100. /* this happens for a comment or white-space */
  78101. zSql = zLeftover;
  78102. continue;
  78103. }
  78104. callbackIsInit = 0;
  78105. nCol = sqlite3_column_count(pStmt);
  78106. while( 1 ){
  78107. int i;
  78108. rc = sqlite3_step(pStmt);
  78109. /* Invoke the callback function if required */
  78110. if( xCallback && (SQLITE_ROW==rc ||
  78111. (SQLITE_DONE==rc && !callbackIsInit
  78112. && db->flags&SQLITE_NullCallback)) ){
  78113. if( !callbackIsInit ){
  78114. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  78115. if( azCols==0 ){
  78116. goto exec_out;
  78117. }
  78118. for(i=0; i<nCol; i++){
  78119. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  78120. /* sqlite3VdbeSetColName() installs column names as UTF8
  78121. ** strings so there is no way for sqlite3_column_name() to fail. */
  78122. assert( azCols[i]!=0 );
  78123. }
  78124. callbackIsInit = 1;
  78125. }
  78126. if( rc==SQLITE_ROW ){
  78127. azVals = &azCols[nCol];
  78128. for(i=0; i<nCol; i++){
  78129. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  78130. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  78131. db->mallocFailed = 1;
  78132. goto exec_out;
  78133. }
  78134. }
  78135. }
  78136. if( xCallback(pArg, nCol, azVals, azCols) ){
  78137. rc = SQLITE_ABORT;
  78138. sqlite3VdbeFinalize((Vdbe *)pStmt);
  78139. pStmt = 0;
  78140. sqlite3Error(db, SQLITE_ABORT, 0);
  78141. goto exec_out;
  78142. }
  78143. }
  78144. if( rc!=SQLITE_ROW ){
  78145. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  78146. pStmt = 0;
  78147. zSql = zLeftover;
  78148. while( sqlite3Isspace(zSql[0]) ) zSql++;
  78149. break;
  78150. }
  78151. }
  78152. sqlite3DbFree(db, azCols);
  78153. azCols = 0;
  78154. }
  78155. exec_out:
  78156. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  78157. sqlite3DbFree(db, azCols);
  78158. rc = sqlite3ApiExit(db, rc);
  78159. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  78160. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  78161. *pzErrMsg = sqlite3Malloc(nErrMsg);
  78162. if( *pzErrMsg ){
  78163. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  78164. }else{
  78165. rc = SQLITE_NOMEM;
  78166. sqlite3Error(db, SQLITE_NOMEM, 0);
  78167. }
  78168. }else if( pzErrMsg ){
  78169. *pzErrMsg = 0;
  78170. }
  78171. assert( (rc&db->errMask)==rc );
  78172. sqlite3_mutex_leave(db->mutex);
  78173. return rc;
  78174. }
  78175. /************** End of legacy.c **********************************************/
  78176. /************** Begin file loadext.c *****************************************/
  78177. /*
  78178. ** 2006 June 7
  78179. **
  78180. ** The author disclaims copyright to this source code. In place of
  78181. ** a legal notice, here is a blessing:
  78182. **
  78183. ** May you do good and not evil.
  78184. ** May you find forgiveness for yourself and forgive others.
  78185. ** May you share freely, never taking more than you give.
  78186. **
  78187. *************************************************************************
  78188. ** This file contains code used to dynamically load extensions into
  78189. ** the SQLite library.
  78190. */
  78191. #ifndef SQLITE_CORE
  78192. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  78193. #endif
  78194. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  78195. /************** Begin file sqlite3ext.h **************************************/
  78196. /*
  78197. ** 2006 June 7
  78198. **
  78199. ** The author disclaims copyright to this source code. In place of
  78200. ** a legal notice, here is a blessing:
  78201. **
  78202. ** May you do good and not evil.
  78203. ** May you find forgiveness for yourself and forgive others.
  78204. ** May you share freely, never taking more than you give.
  78205. **
  78206. *************************************************************************
  78207. ** This header file defines the SQLite interface for use by
  78208. ** shared libraries that want to be imported as extensions into
  78209. ** an SQLite instance. Shared libraries that intend to be loaded
  78210. ** as extensions by SQLite should #include this file instead of
  78211. ** sqlite3.h.
  78212. */
  78213. #ifndef _SQLITE3EXT_H_
  78214. #define _SQLITE3EXT_H_
  78215. typedef struct sqlite3_api_routines sqlite3_api_routines;
  78216. /*
  78217. ** The following structure holds pointers to all of the SQLite API
  78218. ** routines.
  78219. **
  78220. ** WARNING: In order to maintain backwards compatibility, add new
  78221. ** interfaces to the end of this structure only. If you insert new
  78222. ** interfaces in the middle of this structure, then older different
  78223. ** versions of SQLite will not be able to load each others' shared
  78224. ** libraries!
  78225. */
  78226. struct sqlite3_api_routines {
  78227. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  78228. int (*aggregate_count)(sqlite3_context*);
  78229. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  78230. int (*bind_double)(sqlite3_stmt*,int,double);
  78231. int (*bind_int)(sqlite3_stmt*,int,int);
  78232. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  78233. int (*bind_null)(sqlite3_stmt*,int);
  78234. int (*bind_parameter_count)(sqlite3_stmt*);
  78235. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  78236. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  78237. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  78238. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  78239. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  78240. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  78241. int (*busy_timeout)(sqlite3*,int ms);
  78242. int (*changes)(sqlite3*);
  78243. int (*close)(sqlite3*);
  78244. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  78245. int eTextRep,const char*));
  78246. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  78247. int eTextRep,const void*));
  78248. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  78249. int (*column_bytes)(sqlite3_stmt*,int iCol);
  78250. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  78251. int (*column_count)(sqlite3_stmt*pStmt);
  78252. const char * (*column_database_name)(sqlite3_stmt*,int);
  78253. const void * (*column_database_name16)(sqlite3_stmt*,int);
  78254. const char * (*column_decltype)(sqlite3_stmt*,int i);
  78255. const void * (*column_decltype16)(sqlite3_stmt*,int);
  78256. double (*column_double)(sqlite3_stmt*,int iCol);
  78257. int (*column_int)(sqlite3_stmt*,int iCol);
  78258. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  78259. const char * (*column_name)(sqlite3_stmt*,int);
  78260. const void * (*column_name16)(sqlite3_stmt*,int);
  78261. const char * (*column_origin_name)(sqlite3_stmt*,int);
  78262. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  78263. const char * (*column_table_name)(sqlite3_stmt*,int);
  78264. const void * (*column_table_name16)(sqlite3_stmt*,int);
  78265. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  78266. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  78267. int (*column_type)(sqlite3_stmt*,int iCol);
  78268. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  78269. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  78270. int (*complete)(const char*sql);
  78271. int (*complete16)(const void*sql);
  78272. int (*create_collation)(sqlite3*,const char*,int,void*,
  78273. int(*)(void*,int,const void*,int,const void*));
  78274. int (*create_collation16)(sqlite3*,const void*,int,void*,
  78275. int(*)(void*,int,const void*,int,const void*));
  78276. int (*create_function)(sqlite3*,const char*,int,int,void*,
  78277. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  78278. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  78279. void (*xFinal)(sqlite3_context*));
  78280. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  78281. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  78282. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  78283. void (*xFinal)(sqlite3_context*));
  78284. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  78285. int (*data_count)(sqlite3_stmt*pStmt);
  78286. sqlite3 * (*db_handle)(sqlite3_stmt*);
  78287. int (*declare_vtab)(sqlite3*,const char*);
  78288. int (*enable_shared_cache)(int);
  78289. int (*errcode)(sqlite3*db);
  78290. const char * (*errmsg)(sqlite3*);
  78291. const void * (*errmsg16)(sqlite3*);
  78292. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  78293. int (*expired)(sqlite3_stmt*);
  78294. int (*finalize)(sqlite3_stmt*pStmt);
  78295. void (*free)(void*);
  78296. void (*free_table)(char**result);
  78297. int (*get_autocommit)(sqlite3*);
  78298. void * (*get_auxdata)(sqlite3_context*,int);
  78299. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  78300. int (*global_recover)(void);
  78301. void (*interruptx)(sqlite3*);
  78302. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  78303. const char * (*libversion)(void);
  78304. int (*libversion_number)(void);
  78305. void *(*malloc)(int);
  78306. char * (*mprintf)(const char*,...);
  78307. int (*open)(const char*,sqlite3**);
  78308. int (*open16)(const void*,sqlite3**);
  78309. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  78310. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  78311. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  78312. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  78313. void *(*realloc)(void*,int);
  78314. int (*reset)(sqlite3_stmt*pStmt);
  78315. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  78316. void (*result_double)(sqlite3_context*,double);
  78317. void (*result_error)(sqlite3_context*,const char*,int);
  78318. void (*result_error16)(sqlite3_context*,const void*,int);
  78319. void (*result_int)(sqlite3_context*,int);
  78320. void (*result_int64)(sqlite3_context*,sqlite_int64);
  78321. void (*result_null)(sqlite3_context*);
  78322. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  78323. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  78324. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  78325. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  78326. void (*result_value)(sqlite3_context*,sqlite3_value*);
  78327. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  78328. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  78329. const char*,const char*),void*);
  78330. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  78331. char * (*snprintf)(int,char*,const char*,...);
  78332. int (*step)(sqlite3_stmt*);
  78333. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  78334. char const**,char const**,int*,int*,int*);
  78335. void (*thread_cleanup)(void);
  78336. int (*total_changes)(sqlite3*);
  78337. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  78338. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  78339. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  78340. sqlite_int64),void*);
  78341. void * (*user_data)(sqlite3_context*);
  78342. const void * (*value_blob)(sqlite3_value*);
  78343. int (*value_bytes)(sqlite3_value*);
  78344. int (*value_bytes16)(sqlite3_value*);
  78345. double (*value_double)(sqlite3_value*);
  78346. int (*value_int)(sqlite3_value*);
  78347. sqlite_int64 (*value_int64)(sqlite3_value*);
  78348. int (*value_numeric_type)(sqlite3_value*);
  78349. const unsigned char * (*value_text)(sqlite3_value*);
  78350. const void * (*value_text16)(sqlite3_value*);
  78351. const void * (*value_text16be)(sqlite3_value*);
  78352. const void * (*value_text16le)(sqlite3_value*);
  78353. int (*value_type)(sqlite3_value*);
  78354. char *(*vmprintf)(const char*,va_list);
  78355. /* Added ??? */
  78356. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  78357. /* Added by 3.3.13 */
  78358. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  78359. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  78360. int (*clear_bindings)(sqlite3_stmt*);
  78361. /* Added by 3.4.1 */
  78362. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  78363. void (*xDestroy)(void *));
  78364. /* Added by 3.5.0 */
  78365. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  78366. int (*blob_bytes)(sqlite3_blob*);
  78367. int (*blob_close)(sqlite3_blob*);
  78368. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  78369. int,sqlite3_blob**);
  78370. int (*blob_read)(sqlite3_blob*,void*,int,int);
  78371. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  78372. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  78373. int(*)(void*,int,const void*,int,const void*),
  78374. void(*)(void*));
  78375. int (*file_control)(sqlite3*,const char*,int,void*);
  78376. sqlite3_int64 (*memory_highwater)(int);
  78377. sqlite3_int64 (*memory_used)(void);
  78378. sqlite3_mutex *(*mutex_alloc)(int);
  78379. void (*mutex_enter)(sqlite3_mutex*);
  78380. void (*mutex_free)(sqlite3_mutex*);
  78381. void (*mutex_leave)(sqlite3_mutex*);
  78382. int (*mutex_try)(sqlite3_mutex*);
  78383. int (*open_v2)(const char*,sqlite3**,int,const char*);
  78384. int (*release_memory)(int);
  78385. void (*result_error_nomem)(sqlite3_context*);
  78386. void (*result_error_toobig)(sqlite3_context*);
  78387. int (*sleep)(int);
  78388. void (*soft_heap_limit)(int);
  78389. sqlite3_vfs *(*vfs_find)(const char*);
  78390. int (*vfs_register)(sqlite3_vfs*,int);
  78391. int (*vfs_unregister)(sqlite3_vfs*);
  78392. int (*xthreadsafe)(void);
  78393. void (*result_zeroblob)(sqlite3_context*,int);
  78394. void (*result_error_code)(sqlite3_context*,int);
  78395. int (*test_control)(int, ...);
  78396. void (*randomness)(int,void*);
  78397. sqlite3 *(*context_db_handle)(sqlite3_context*);
  78398. int (*extended_result_codes)(sqlite3*,int);
  78399. int (*limit)(sqlite3*,int,int);
  78400. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  78401. const char *(*sql)(sqlite3_stmt*);
  78402. int (*status)(int,int*,int*,int);
  78403. int (*backup_finish)(sqlite3_backup*);
  78404. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  78405. int (*backup_pagecount)(sqlite3_backup*);
  78406. int (*backup_remaining)(sqlite3_backup*);
  78407. int (*backup_step)(sqlite3_backup*,int);
  78408. const char *(*compileoption_get)(int);
  78409. int (*compileoption_used)(const char*);
  78410. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  78411. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  78412. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  78413. void (*xFinal)(sqlite3_context*),
  78414. void(*xDestroy)(void*));
  78415. int (*db_config)(sqlite3*,int,...);
  78416. sqlite3_mutex *(*db_mutex)(sqlite3*);
  78417. int (*db_status)(sqlite3*,int,int*,int*,int);
  78418. int (*extended_errcode)(sqlite3*);
  78419. void (*log)(int,const char*,...);
  78420. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  78421. const char *(*sourceid)(void);
  78422. int (*stmt_status)(sqlite3_stmt*,int,int);
  78423. int (*strnicmp)(const char*,const char*,int);
  78424. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  78425. int (*wal_autocheckpoint)(sqlite3*,int);
  78426. int (*wal_checkpoint)(sqlite3*,const char*);
  78427. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  78428. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  78429. int (*vtab_config)(sqlite3*,int op,...);
  78430. int (*vtab_on_conflict)(sqlite3*);
  78431. /* Version 3.7.16 and later */
  78432. int (*close_v2)(sqlite3*);
  78433. const char *(*db_filename)(sqlite3*,const char*);
  78434. int (*db_readonly)(sqlite3*,const char*);
  78435. int (*db_release_memory)(sqlite3*);
  78436. const char *(*errstr)(int);
  78437. int (*stmt_busy)(sqlite3_stmt*);
  78438. int (*stmt_readonly)(sqlite3_stmt*);
  78439. int (*stricmp)(const char*,const char*);
  78440. int (*uri_boolean)(const char*,const char*,int);
  78441. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  78442. const char *(*uri_parameter)(const char*,const char*);
  78443. char *(*vsnprintf)(int,char*,const char*,va_list);
  78444. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  78445. };
  78446. /*
  78447. ** The following macros redefine the API routines so that they are
  78448. ** redirected throught the global sqlite3_api structure.
  78449. **
  78450. ** This header file is also used by the loadext.c source file
  78451. ** (part of the main SQLite library - not an extension) so that
  78452. ** it can get access to the sqlite3_api_routines structure
  78453. ** definition. But the main library does not want to redefine
  78454. ** the API. So the redefinition macros are only valid if the
  78455. ** SQLITE_CORE macros is undefined.
  78456. */
  78457. #ifndef SQLITE_CORE
  78458. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  78459. #ifndef SQLITE_OMIT_DEPRECATED
  78460. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  78461. #endif
  78462. #define sqlite3_bind_blob sqlite3_api->bind_blob
  78463. #define sqlite3_bind_double sqlite3_api->bind_double
  78464. #define sqlite3_bind_int sqlite3_api->bind_int
  78465. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  78466. #define sqlite3_bind_null sqlite3_api->bind_null
  78467. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  78468. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  78469. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  78470. #define sqlite3_bind_text sqlite3_api->bind_text
  78471. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  78472. #define sqlite3_bind_value sqlite3_api->bind_value
  78473. #define sqlite3_busy_handler sqlite3_api->busy_handler
  78474. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  78475. #define sqlite3_changes sqlite3_api->changes
  78476. #define sqlite3_close sqlite3_api->close
  78477. #define sqlite3_collation_needed sqlite3_api->collation_needed
  78478. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  78479. #define sqlite3_column_blob sqlite3_api->column_blob
  78480. #define sqlite3_column_bytes sqlite3_api->column_bytes
  78481. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  78482. #define sqlite3_column_count sqlite3_api->column_count
  78483. #define sqlite3_column_database_name sqlite3_api->column_database_name
  78484. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  78485. #define sqlite3_column_decltype sqlite3_api->column_decltype
  78486. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  78487. #define sqlite3_column_double sqlite3_api->column_double
  78488. #define sqlite3_column_int sqlite3_api->column_int
  78489. #define sqlite3_column_int64 sqlite3_api->column_int64
  78490. #define sqlite3_column_name sqlite3_api->column_name
  78491. #define sqlite3_column_name16 sqlite3_api->column_name16
  78492. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  78493. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  78494. #define sqlite3_column_table_name sqlite3_api->column_table_name
  78495. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  78496. #define sqlite3_column_text sqlite3_api->column_text
  78497. #define sqlite3_column_text16 sqlite3_api->column_text16
  78498. #define sqlite3_column_type sqlite3_api->column_type
  78499. #define sqlite3_column_value sqlite3_api->column_value
  78500. #define sqlite3_commit_hook sqlite3_api->commit_hook
  78501. #define sqlite3_complete sqlite3_api->complete
  78502. #define sqlite3_complete16 sqlite3_api->complete16
  78503. #define sqlite3_create_collation sqlite3_api->create_collation
  78504. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  78505. #define sqlite3_create_function sqlite3_api->create_function
  78506. #define sqlite3_create_function16 sqlite3_api->create_function16
  78507. #define sqlite3_create_module sqlite3_api->create_module
  78508. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  78509. #define sqlite3_data_count sqlite3_api->data_count
  78510. #define sqlite3_db_handle sqlite3_api->db_handle
  78511. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  78512. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  78513. #define sqlite3_errcode sqlite3_api->errcode
  78514. #define sqlite3_errmsg sqlite3_api->errmsg
  78515. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  78516. #define sqlite3_exec sqlite3_api->exec
  78517. #ifndef SQLITE_OMIT_DEPRECATED
  78518. #define sqlite3_expired sqlite3_api->expired
  78519. #endif
  78520. #define sqlite3_finalize sqlite3_api->finalize
  78521. #define sqlite3_free sqlite3_api->free
  78522. #define sqlite3_free_table sqlite3_api->free_table
  78523. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  78524. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  78525. #define sqlite3_get_table sqlite3_api->get_table
  78526. #ifndef SQLITE_OMIT_DEPRECATED
  78527. #define sqlite3_global_recover sqlite3_api->global_recover
  78528. #endif
  78529. #define sqlite3_interrupt sqlite3_api->interruptx
  78530. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  78531. #define sqlite3_libversion sqlite3_api->libversion
  78532. #define sqlite3_libversion_number sqlite3_api->libversion_number
  78533. #define sqlite3_malloc sqlite3_api->malloc
  78534. #define sqlite3_mprintf sqlite3_api->mprintf
  78535. #define sqlite3_open sqlite3_api->open
  78536. #define sqlite3_open16 sqlite3_api->open16
  78537. #define sqlite3_prepare sqlite3_api->prepare
  78538. #define sqlite3_prepare16 sqlite3_api->prepare16
  78539. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  78540. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  78541. #define sqlite3_profile sqlite3_api->profile
  78542. #define sqlite3_progress_handler sqlite3_api->progress_handler
  78543. #define sqlite3_realloc sqlite3_api->realloc
  78544. #define sqlite3_reset sqlite3_api->reset
  78545. #define sqlite3_result_blob sqlite3_api->result_blob
  78546. #define sqlite3_result_double sqlite3_api->result_double
  78547. #define sqlite3_result_error sqlite3_api->result_error
  78548. #define sqlite3_result_error16 sqlite3_api->result_error16
  78549. #define sqlite3_result_int sqlite3_api->result_int
  78550. #define sqlite3_result_int64 sqlite3_api->result_int64
  78551. #define sqlite3_result_null sqlite3_api->result_null
  78552. #define sqlite3_result_text sqlite3_api->result_text
  78553. #define sqlite3_result_text16 sqlite3_api->result_text16
  78554. #define sqlite3_result_text16be sqlite3_api->result_text16be
  78555. #define sqlite3_result_text16le sqlite3_api->result_text16le
  78556. #define sqlite3_result_value sqlite3_api->result_value
  78557. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  78558. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  78559. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  78560. #define sqlite3_snprintf sqlite3_api->snprintf
  78561. #define sqlite3_step sqlite3_api->step
  78562. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  78563. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  78564. #define sqlite3_total_changes sqlite3_api->total_changes
  78565. #define sqlite3_trace sqlite3_api->trace
  78566. #ifndef SQLITE_OMIT_DEPRECATED
  78567. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  78568. #endif
  78569. #define sqlite3_update_hook sqlite3_api->update_hook
  78570. #define sqlite3_user_data sqlite3_api->user_data
  78571. #define sqlite3_value_blob sqlite3_api->value_blob
  78572. #define sqlite3_value_bytes sqlite3_api->value_bytes
  78573. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  78574. #define sqlite3_value_double sqlite3_api->value_double
  78575. #define sqlite3_value_int sqlite3_api->value_int
  78576. #define sqlite3_value_int64 sqlite3_api->value_int64
  78577. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  78578. #define sqlite3_value_text sqlite3_api->value_text
  78579. #define sqlite3_value_text16 sqlite3_api->value_text16
  78580. #define sqlite3_value_text16be sqlite3_api->value_text16be
  78581. #define sqlite3_value_text16le sqlite3_api->value_text16le
  78582. #define sqlite3_value_type sqlite3_api->value_type
  78583. #define sqlite3_vmprintf sqlite3_api->vmprintf
  78584. #define sqlite3_overload_function sqlite3_api->overload_function
  78585. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  78586. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  78587. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  78588. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  78589. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  78590. #define sqlite3_blob_close sqlite3_api->blob_close
  78591. #define sqlite3_blob_open sqlite3_api->blob_open
  78592. #define sqlite3_blob_read sqlite3_api->blob_read
  78593. #define sqlite3_blob_write sqlite3_api->blob_write
  78594. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  78595. #define sqlite3_file_control sqlite3_api->file_control
  78596. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  78597. #define sqlite3_memory_used sqlite3_api->memory_used
  78598. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  78599. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  78600. #define sqlite3_mutex_free sqlite3_api->mutex_free
  78601. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  78602. #define sqlite3_mutex_try sqlite3_api->mutex_try
  78603. #define sqlite3_open_v2 sqlite3_api->open_v2
  78604. #define sqlite3_release_memory sqlite3_api->release_memory
  78605. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  78606. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  78607. #define sqlite3_sleep sqlite3_api->sleep
  78608. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  78609. #define sqlite3_vfs_find sqlite3_api->vfs_find
  78610. #define sqlite3_vfs_register sqlite3_api->vfs_register
  78611. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  78612. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  78613. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  78614. #define sqlite3_result_error_code sqlite3_api->result_error_code
  78615. #define sqlite3_test_control sqlite3_api->test_control
  78616. #define sqlite3_randomness sqlite3_api->randomness
  78617. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  78618. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  78619. #define sqlite3_limit sqlite3_api->limit
  78620. #define sqlite3_next_stmt sqlite3_api->next_stmt
  78621. #define sqlite3_sql sqlite3_api->sql
  78622. #define sqlite3_status sqlite3_api->status
  78623. #define sqlite3_backup_finish sqlite3_api->backup_finish
  78624. #define sqlite3_backup_init sqlite3_api->backup_init
  78625. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  78626. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  78627. #define sqlite3_backup_step sqlite3_api->backup_step
  78628. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  78629. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  78630. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  78631. #define sqlite3_db_config sqlite3_api->db_config
  78632. #define sqlite3_db_mutex sqlite3_api->db_mutex
  78633. #define sqlite3_db_status sqlite3_api->db_status
  78634. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  78635. #define sqlite3_log sqlite3_api->log
  78636. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  78637. #define sqlite3_sourceid sqlite3_api->sourceid
  78638. #define sqlite3_stmt_status sqlite3_api->stmt_status
  78639. #define sqlite3_strnicmp sqlite3_api->strnicmp
  78640. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  78641. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  78642. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  78643. #define sqlite3_wal_hook sqlite3_api->wal_hook
  78644. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  78645. #define sqlite3_vtab_config sqlite3_api->vtab_config
  78646. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  78647. /* Version 3.7.16 and later */
  78648. #define sqlite3_close_v2 sqlite3_api->close_v2
  78649. #define sqlite3_db_filename sqlite3_api->db_filename
  78650. #define sqlite3_db_readonly sqlite3_api->db_readonly
  78651. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  78652. #define sqlite3_errstr sqlite3_api->errstr
  78653. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  78654. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  78655. #define sqlite3_stricmp sqlite3_api->stricmp
  78656. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  78657. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  78658. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  78659. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  78660. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  78661. #endif /* SQLITE_CORE */
  78662. #ifndef SQLITE_CORE
  78663. /* This case when the file really is being compiled as a loadable
  78664. ** extension */
  78665. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  78666. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  78667. # define SQLITE_EXTENSION_INIT3 \
  78668. extern const sqlite3_api_routines *sqlite3_api;
  78669. #else
  78670. /* This case when the file is being statically linked into the
  78671. ** application */
  78672. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  78673. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  78674. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  78675. #endif
  78676. #endif /* _SQLITE3EXT_H_ */
  78677. /************** End of sqlite3ext.h ******************************************/
  78678. /************** Continuing where we left off in loadext.c ********************/
  78679. /* #include <string.h> */
  78680. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  78681. /*
  78682. ** Some API routines are omitted when various features are
  78683. ** excluded from a build of SQLite. Substitute a NULL pointer
  78684. ** for any missing APIs.
  78685. */
  78686. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  78687. # define sqlite3_column_database_name 0
  78688. # define sqlite3_column_database_name16 0
  78689. # define sqlite3_column_table_name 0
  78690. # define sqlite3_column_table_name16 0
  78691. # define sqlite3_column_origin_name 0
  78692. # define sqlite3_column_origin_name16 0
  78693. # define sqlite3_table_column_metadata 0
  78694. #endif
  78695. #ifdef SQLITE_OMIT_AUTHORIZATION
  78696. # define sqlite3_set_authorizer 0
  78697. #endif
  78698. #ifdef SQLITE_OMIT_UTF16
  78699. # define sqlite3_bind_text16 0
  78700. # define sqlite3_collation_needed16 0
  78701. # define sqlite3_column_decltype16 0
  78702. # define sqlite3_column_name16 0
  78703. # define sqlite3_column_text16 0
  78704. # define sqlite3_complete16 0
  78705. # define sqlite3_create_collation16 0
  78706. # define sqlite3_create_function16 0
  78707. # define sqlite3_errmsg16 0
  78708. # define sqlite3_open16 0
  78709. # define sqlite3_prepare16 0
  78710. # define sqlite3_prepare16_v2 0
  78711. # define sqlite3_result_error16 0
  78712. # define sqlite3_result_text16 0
  78713. # define sqlite3_result_text16be 0
  78714. # define sqlite3_result_text16le 0
  78715. # define sqlite3_value_text16 0
  78716. # define sqlite3_value_text16be 0
  78717. # define sqlite3_value_text16le 0
  78718. # define sqlite3_column_database_name16 0
  78719. # define sqlite3_column_table_name16 0
  78720. # define sqlite3_column_origin_name16 0
  78721. #endif
  78722. #ifdef SQLITE_OMIT_COMPLETE
  78723. # define sqlite3_complete 0
  78724. # define sqlite3_complete16 0
  78725. #endif
  78726. #ifdef SQLITE_OMIT_DECLTYPE
  78727. # define sqlite3_column_decltype16 0
  78728. # define sqlite3_column_decltype 0
  78729. #endif
  78730. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  78731. # define sqlite3_progress_handler 0
  78732. #endif
  78733. #ifdef SQLITE_OMIT_VIRTUALTABLE
  78734. # define sqlite3_create_module 0
  78735. # define sqlite3_create_module_v2 0
  78736. # define sqlite3_declare_vtab 0
  78737. # define sqlite3_vtab_config 0
  78738. # define sqlite3_vtab_on_conflict 0
  78739. #endif
  78740. #ifdef SQLITE_OMIT_SHARED_CACHE
  78741. # define sqlite3_enable_shared_cache 0
  78742. #endif
  78743. #ifdef SQLITE_OMIT_TRACE
  78744. # define sqlite3_profile 0
  78745. # define sqlite3_trace 0
  78746. #endif
  78747. #ifdef SQLITE_OMIT_GET_TABLE
  78748. # define sqlite3_free_table 0
  78749. # define sqlite3_get_table 0
  78750. #endif
  78751. #ifdef SQLITE_OMIT_INCRBLOB
  78752. #define sqlite3_bind_zeroblob 0
  78753. #define sqlite3_blob_bytes 0
  78754. #define sqlite3_blob_close 0
  78755. #define sqlite3_blob_open 0
  78756. #define sqlite3_blob_read 0
  78757. #define sqlite3_blob_write 0
  78758. #define sqlite3_blob_reopen 0
  78759. #endif
  78760. /*
  78761. ** The following structure contains pointers to all SQLite API routines.
  78762. ** A pointer to this structure is passed into extensions when they are
  78763. ** loaded so that the extension can make calls back into the SQLite
  78764. ** library.
  78765. **
  78766. ** When adding new APIs, add them to the bottom of this structure
  78767. ** in order to preserve backwards compatibility.
  78768. **
  78769. ** Extensions that use newer APIs should first call the
  78770. ** sqlite3_libversion_number() to make sure that the API they
  78771. ** intend to use is supported by the library. Extensions should
  78772. ** also check to make sure that the pointer to the function is
  78773. ** not NULL before calling it.
  78774. */
  78775. static const sqlite3_api_routines sqlite3Apis = {
  78776. sqlite3_aggregate_context,
  78777. #ifndef SQLITE_OMIT_DEPRECATED
  78778. sqlite3_aggregate_count,
  78779. #else
  78780. 0,
  78781. #endif
  78782. sqlite3_bind_blob,
  78783. sqlite3_bind_double,
  78784. sqlite3_bind_int,
  78785. sqlite3_bind_int64,
  78786. sqlite3_bind_null,
  78787. sqlite3_bind_parameter_count,
  78788. sqlite3_bind_parameter_index,
  78789. sqlite3_bind_parameter_name,
  78790. sqlite3_bind_text,
  78791. sqlite3_bind_text16,
  78792. sqlite3_bind_value,
  78793. sqlite3_busy_handler,
  78794. sqlite3_busy_timeout,
  78795. sqlite3_changes,
  78796. sqlite3_close,
  78797. sqlite3_collation_needed,
  78798. sqlite3_collation_needed16,
  78799. sqlite3_column_blob,
  78800. sqlite3_column_bytes,
  78801. sqlite3_column_bytes16,
  78802. sqlite3_column_count,
  78803. sqlite3_column_database_name,
  78804. sqlite3_column_database_name16,
  78805. sqlite3_column_decltype,
  78806. sqlite3_column_decltype16,
  78807. sqlite3_column_double,
  78808. sqlite3_column_int,
  78809. sqlite3_column_int64,
  78810. sqlite3_column_name,
  78811. sqlite3_column_name16,
  78812. sqlite3_column_origin_name,
  78813. sqlite3_column_origin_name16,
  78814. sqlite3_column_table_name,
  78815. sqlite3_column_table_name16,
  78816. sqlite3_column_text,
  78817. sqlite3_column_text16,
  78818. sqlite3_column_type,
  78819. sqlite3_column_value,
  78820. sqlite3_commit_hook,
  78821. sqlite3_complete,
  78822. sqlite3_complete16,
  78823. sqlite3_create_collation,
  78824. sqlite3_create_collation16,
  78825. sqlite3_create_function,
  78826. sqlite3_create_function16,
  78827. sqlite3_create_module,
  78828. sqlite3_data_count,
  78829. sqlite3_db_handle,
  78830. sqlite3_declare_vtab,
  78831. sqlite3_enable_shared_cache,
  78832. sqlite3_errcode,
  78833. sqlite3_errmsg,
  78834. sqlite3_errmsg16,
  78835. sqlite3_exec,
  78836. #ifndef SQLITE_OMIT_DEPRECATED
  78837. sqlite3_expired,
  78838. #else
  78839. 0,
  78840. #endif
  78841. sqlite3_finalize,
  78842. sqlite3_free,
  78843. sqlite3_free_table,
  78844. sqlite3_get_autocommit,
  78845. sqlite3_get_auxdata,
  78846. sqlite3_get_table,
  78847. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  78848. sqlite3_interrupt,
  78849. sqlite3_last_insert_rowid,
  78850. sqlite3_libversion,
  78851. sqlite3_libversion_number,
  78852. sqlite3_malloc,
  78853. sqlite3_mprintf,
  78854. sqlite3_open,
  78855. sqlite3_open16,
  78856. sqlite3_prepare,
  78857. sqlite3_prepare16,
  78858. sqlite3_profile,
  78859. sqlite3_progress_handler,
  78860. sqlite3_realloc,
  78861. sqlite3_reset,
  78862. sqlite3_result_blob,
  78863. sqlite3_result_double,
  78864. sqlite3_result_error,
  78865. sqlite3_result_error16,
  78866. sqlite3_result_int,
  78867. sqlite3_result_int64,
  78868. sqlite3_result_null,
  78869. sqlite3_result_text,
  78870. sqlite3_result_text16,
  78871. sqlite3_result_text16be,
  78872. sqlite3_result_text16le,
  78873. sqlite3_result_value,
  78874. sqlite3_rollback_hook,
  78875. sqlite3_set_authorizer,
  78876. sqlite3_set_auxdata,
  78877. sqlite3_snprintf,
  78878. sqlite3_step,
  78879. sqlite3_table_column_metadata,
  78880. #ifndef SQLITE_OMIT_DEPRECATED
  78881. sqlite3_thread_cleanup,
  78882. #else
  78883. 0,
  78884. #endif
  78885. sqlite3_total_changes,
  78886. sqlite3_trace,
  78887. #ifndef SQLITE_OMIT_DEPRECATED
  78888. sqlite3_transfer_bindings,
  78889. #else
  78890. 0,
  78891. #endif
  78892. sqlite3_update_hook,
  78893. sqlite3_user_data,
  78894. sqlite3_value_blob,
  78895. sqlite3_value_bytes,
  78896. sqlite3_value_bytes16,
  78897. sqlite3_value_double,
  78898. sqlite3_value_int,
  78899. sqlite3_value_int64,
  78900. sqlite3_value_numeric_type,
  78901. sqlite3_value_text,
  78902. sqlite3_value_text16,
  78903. sqlite3_value_text16be,
  78904. sqlite3_value_text16le,
  78905. sqlite3_value_type,
  78906. sqlite3_vmprintf,
  78907. /*
  78908. ** The original API set ends here. All extensions can call any
  78909. ** of the APIs above provided that the pointer is not NULL. But
  78910. ** before calling APIs that follow, extension should check the
  78911. ** sqlite3_libversion_number() to make sure they are dealing with
  78912. ** a library that is new enough to support that API.
  78913. *************************************************************************
  78914. */
  78915. sqlite3_overload_function,
  78916. /*
  78917. ** Added after 3.3.13
  78918. */
  78919. sqlite3_prepare_v2,
  78920. sqlite3_prepare16_v2,
  78921. sqlite3_clear_bindings,
  78922. /*
  78923. ** Added for 3.4.1
  78924. */
  78925. sqlite3_create_module_v2,
  78926. /*
  78927. ** Added for 3.5.0
  78928. */
  78929. sqlite3_bind_zeroblob,
  78930. sqlite3_blob_bytes,
  78931. sqlite3_blob_close,
  78932. sqlite3_blob_open,
  78933. sqlite3_blob_read,
  78934. sqlite3_blob_write,
  78935. sqlite3_create_collation_v2,
  78936. sqlite3_file_control,
  78937. sqlite3_memory_highwater,
  78938. sqlite3_memory_used,
  78939. #ifdef SQLITE_MUTEX_OMIT
  78940. 0,
  78941. 0,
  78942. 0,
  78943. 0,
  78944. 0,
  78945. #else
  78946. sqlite3_mutex_alloc,
  78947. sqlite3_mutex_enter,
  78948. sqlite3_mutex_free,
  78949. sqlite3_mutex_leave,
  78950. sqlite3_mutex_try,
  78951. #endif
  78952. sqlite3_open_v2,
  78953. sqlite3_release_memory,
  78954. sqlite3_result_error_nomem,
  78955. sqlite3_result_error_toobig,
  78956. sqlite3_sleep,
  78957. sqlite3_soft_heap_limit,
  78958. sqlite3_vfs_find,
  78959. sqlite3_vfs_register,
  78960. sqlite3_vfs_unregister,
  78961. /*
  78962. ** Added for 3.5.8
  78963. */
  78964. sqlite3_threadsafe,
  78965. sqlite3_result_zeroblob,
  78966. sqlite3_result_error_code,
  78967. sqlite3_test_control,
  78968. sqlite3_randomness,
  78969. sqlite3_context_db_handle,
  78970. /*
  78971. ** Added for 3.6.0
  78972. */
  78973. sqlite3_extended_result_codes,
  78974. sqlite3_limit,
  78975. sqlite3_next_stmt,
  78976. sqlite3_sql,
  78977. sqlite3_status,
  78978. /*
  78979. ** Added for 3.7.4
  78980. */
  78981. sqlite3_backup_finish,
  78982. sqlite3_backup_init,
  78983. sqlite3_backup_pagecount,
  78984. sqlite3_backup_remaining,
  78985. sqlite3_backup_step,
  78986. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  78987. sqlite3_compileoption_get,
  78988. sqlite3_compileoption_used,
  78989. #else
  78990. 0,
  78991. 0,
  78992. #endif
  78993. sqlite3_create_function_v2,
  78994. sqlite3_db_config,
  78995. sqlite3_db_mutex,
  78996. sqlite3_db_status,
  78997. sqlite3_extended_errcode,
  78998. sqlite3_log,
  78999. sqlite3_soft_heap_limit64,
  79000. sqlite3_sourceid,
  79001. sqlite3_stmt_status,
  79002. sqlite3_strnicmp,
  79003. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  79004. sqlite3_unlock_notify,
  79005. #else
  79006. 0,
  79007. #endif
  79008. #ifndef SQLITE_OMIT_WAL
  79009. sqlite3_wal_autocheckpoint,
  79010. sqlite3_wal_checkpoint,
  79011. sqlite3_wal_hook,
  79012. #else
  79013. 0,
  79014. 0,
  79015. 0,
  79016. #endif
  79017. sqlite3_blob_reopen,
  79018. sqlite3_vtab_config,
  79019. sqlite3_vtab_on_conflict,
  79020. sqlite3_close_v2,
  79021. sqlite3_db_filename,
  79022. sqlite3_db_readonly,
  79023. sqlite3_db_release_memory,
  79024. sqlite3_errstr,
  79025. sqlite3_stmt_busy,
  79026. sqlite3_stmt_readonly,
  79027. sqlite3_stricmp,
  79028. sqlite3_uri_boolean,
  79029. sqlite3_uri_int64,
  79030. sqlite3_uri_parameter,
  79031. sqlite3_vsnprintf,
  79032. sqlite3_wal_checkpoint_v2
  79033. };
  79034. /*
  79035. ** Attempt to load an SQLite extension library contained in the file
  79036. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  79037. ** default entry point name (sqlite3_extension_init) is used. Use
  79038. ** of the default name is recommended.
  79039. **
  79040. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  79041. **
  79042. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  79043. ** error message text. The calling function should free this memory
  79044. ** by calling sqlite3DbFree(db, ).
  79045. */
  79046. static int sqlite3LoadExtension(
  79047. sqlite3 *db, /* Load the extension into this database connection */
  79048. const char *zFile, /* Name of the shared library containing extension */
  79049. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  79050. char **pzErrMsg /* Put error message here if not 0 */
  79051. ){
  79052. sqlite3_vfs *pVfs = db->pVfs;
  79053. void *handle;
  79054. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  79055. char *zErrmsg = 0;
  79056. const char *zEntry;
  79057. char *zAltEntry = 0;
  79058. void **aHandle;
  79059. int nMsg = 300 + sqlite3Strlen30(zFile);
  79060. int ii;
  79061. /* Shared library endings to try if zFile cannot be loaded as written */
  79062. static const char *azEndings[] = {
  79063. #if SQLITE_OS_WIN
  79064. "dll"
  79065. #elif defined(__APPLE__)
  79066. "dylib"
  79067. #else
  79068. "so"
  79069. #endif
  79070. };
  79071. if( pzErrMsg ) *pzErrMsg = 0;
  79072. /* Ticket #1863. To avoid a creating security problems for older
  79073. ** applications that relink against newer versions of SQLite, the
  79074. ** ability to run load_extension is turned off by default. One
  79075. ** must call sqlite3_enable_load_extension() to turn on extension
  79076. ** loading. Otherwise you get the following error.
  79077. */
  79078. if( (db->flags & SQLITE_LoadExtension)==0 ){
  79079. if( pzErrMsg ){
  79080. *pzErrMsg = sqlite3_mprintf("not authorized");
  79081. }
  79082. return SQLITE_ERROR;
  79083. }
  79084. zEntry = zProc ? zProc : "sqlite3_extension_init";
  79085. handle = sqlite3OsDlOpen(pVfs, zFile);
  79086. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  79087. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  79088. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  79089. if( zAltFile==0 ) return SQLITE_NOMEM;
  79090. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  79091. sqlite3_free(zAltFile);
  79092. }
  79093. #endif
  79094. if( handle==0 ){
  79095. if( pzErrMsg ){
  79096. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  79097. if( zErrmsg ){
  79098. sqlite3_snprintf(nMsg, zErrmsg,
  79099. "unable to open shared library [%s]", zFile);
  79100. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  79101. }
  79102. }
  79103. return SQLITE_ERROR;
  79104. }
  79105. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79106. sqlite3OsDlSym(pVfs, handle, zEntry);
  79107. /* If no entry point was specified and the default legacy
  79108. ** entry point name "sqlite3_extension_init" was not found, then
  79109. ** construct an entry point name "sqlite3_X_init" where the X is
  79110. ** replaced by the lowercase value of every ASCII alphabetic
  79111. ** character in the filename after the last "/" upto the first ".",
  79112. ** and eliding the first three characters if they are "lib".
  79113. ** Examples:
  79114. **
  79115. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  79116. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  79117. */
  79118. if( xInit==0 && zProc==0 ){
  79119. int iFile, iEntry, c;
  79120. int ncFile = sqlite3Strlen30(zFile);
  79121. zAltEntry = sqlite3_malloc(ncFile+30);
  79122. if( zAltEntry==0 ){
  79123. sqlite3OsDlClose(pVfs, handle);
  79124. return SQLITE_NOMEM;
  79125. }
  79126. memcpy(zAltEntry, "sqlite3_", 8);
  79127. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  79128. iFile++;
  79129. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  79130. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  79131. if( sqlite3Isalpha(c) ){
  79132. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  79133. }
  79134. }
  79135. memcpy(zAltEntry+iEntry, "_init", 6);
  79136. zEntry = zAltEntry;
  79137. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79138. sqlite3OsDlSym(pVfs, handle, zEntry);
  79139. }
  79140. if( xInit==0 ){
  79141. if( pzErrMsg ){
  79142. nMsg += sqlite3Strlen30(zEntry);
  79143. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  79144. if( zErrmsg ){
  79145. sqlite3_snprintf(nMsg, zErrmsg,
  79146. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  79147. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  79148. }
  79149. }
  79150. sqlite3OsDlClose(pVfs, handle);
  79151. sqlite3_free(zAltEntry);
  79152. return SQLITE_ERROR;
  79153. }
  79154. sqlite3_free(zAltEntry);
  79155. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  79156. if( pzErrMsg ){
  79157. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  79158. }
  79159. sqlite3_free(zErrmsg);
  79160. sqlite3OsDlClose(pVfs, handle);
  79161. return SQLITE_ERROR;
  79162. }
  79163. /* Append the new shared library handle to the db->aExtension array. */
  79164. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  79165. if( aHandle==0 ){
  79166. return SQLITE_NOMEM;
  79167. }
  79168. if( db->nExtension>0 ){
  79169. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  79170. }
  79171. sqlite3DbFree(db, db->aExtension);
  79172. db->aExtension = aHandle;
  79173. db->aExtension[db->nExtension++] = handle;
  79174. return SQLITE_OK;
  79175. }
  79176. SQLITE_API int sqlite3_load_extension(
  79177. sqlite3 *db, /* Load the extension into this database connection */
  79178. const char *zFile, /* Name of the shared library containing extension */
  79179. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  79180. char **pzErrMsg /* Put error message here if not 0 */
  79181. ){
  79182. int rc;
  79183. sqlite3_mutex_enter(db->mutex);
  79184. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  79185. rc = sqlite3ApiExit(db, rc);
  79186. sqlite3_mutex_leave(db->mutex);
  79187. return rc;
  79188. }
  79189. /*
  79190. ** Call this routine when the database connection is closing in order
  79191. ** to clean up loaded extensions
  79192. */
  79193. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  79194. int i;
  79195. assert( sqlite3_mutex_held(db->mutex) );
  79196. for(i=0; i<db->nExtension; i++){
  79197. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  79198. }
  79199. sqlite3DbFree(db, db->aExtension);
  79200. }
  79201. /*
  79202. ** Enable or disable extension loading. Extension loading is disabled by
  79203. ** default so as not to open security holes in older applications.
  79204. */
  79205. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  79206. sqlite3_mutex_enter(db->mutex);
  79207. if( onoff ){
  79208. db->flags |= SQLITE_LoadExtension;
  79209. }else{
  79210. db->flags &= ~SQLITE_LoadExtension;
  79211. }
  79212. sqlite3_mutex_leave(db->mutex);
  79213. return SQLITE_OK;
  79214. }
  79215. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  79216. /*
  79217. ** The auto-extension code added regardless of whether or not extension
  79218. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  79219. ** code if regular extension loading is not available. This is that
  79220. ** dummy pointer.
  79221. */
  79222. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  79223. static const sqlite3_api_routines sqlite3Apis = { 0 };
  79224. #endif
  79225. /*
  79226. ** The following object holds the list of automatically loaded
  79227. ** extensions.
  79228. **
  79229. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  79230. ** mutex must be held while accessing this list.
  79231. */
  79232. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  79233. static SQLITE_WSD struct sqlite3AutoExtList {
  79234. int nExt; /* Number of entries in aExt[] */
  79235. void (**aExt)(void); /* Pointers to the extension init functions */
  79236. } sqlite3Autoext = { 0, 0 };
  79237. /* The "wsdAutoext" macro will resolve to the autoextension
  79238. ** state vector. If writable static data is unsupported on the target,
  79239. ** we have to locate the state vector at run-time. In the more common
  79240. ** case where writable static data is supported, wsdStat can refer directly
  79241. ** to the "sqlite3Autoext" state vector declared above.
  79242. */
  79243. #ifdef SQLITE_OMIT_WSD
  79244. # define wsdAutoextInit \
  79245. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  79246. # define wsdAutoext x[0]
  79247. #else
  79248. # define wsdAutoextInit
  79249. # define wsdAutoext sqlite3Autoext
  79250. #endif
  79251. /*
  79252. ** Register a statically linked extension that is automatically
  79253. ** loaded by every new database connection.
  79254. */
  79255. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  79256. int rc = SQLITE_OK;
  79257. #ifndef SQLITE_OMIT_AUTOINIT
  79258. rc = sqlite3_initialize();
  79259. if( rc ){
  79260. return rc;
  79261. }else
  79262. #endif
  79263. {
  79264. int i;
  79265. #if SQLITE_THREADSAFE
  79266. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79267. #endif
  79268. wsdAutoextInit;
  79269. sqlite3_mutex_enter(mutex);
  79270. for(i=0; i<wsdAutoext.nExt; i++){
  79271. if( wsdAutoext.aExt[i]==xInit ) break;
  79272. }
  79273. if( i==wsdAutoext.nExt ){
  79274. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  79275. void (**aNew)(void);
  79276. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  79277. if( aNew==0 ){
  79278. rc = SQLITE_NOMEM;
  79279. }else{
  79280. wsdAutoext.aExt = aNew;
  79281. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  79282. wsdAutoext.nExt++;
  79283. }
  79284. }
  79285. sqlite3_mutex_leave(mutex);
  79286. assert( (rc&0xff)==rc );
  79287. return rc;
  79288. }
  79289. }
  79290. /*
  79291. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  79292. ** set of routines that is invoked for each new database connection, if it
  79293. ** is currently on the list. If xInit is not on the list, then this
  79294. ** routine is a no-op.
  79295. **
  79296. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  79297. ** was not on the list.
  79298. */
  79299. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  79300. #if SQLITE_THREADSAFE
  79301. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79302. #endif
  79303. int i;
  79304. int n = 0;
  79305. wsdAutoextInit;
  79306. sqlite3_mutex_enter(mutex);
  79307. for(i=wsdAutoext.nExt-1; i>=0; i--){
  79308. if( wsdAutoext.aExt[i]==xInit ){
  79309. wsdAutoext.nExt--;
  79310. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  79311. n++;
  79312. break;
  79313. }
  79314. }
  79315. sqlite3_mutex_leave(mutex);
  79316. return n;
  79317. }
  79318. /*
  79319. ** Reset the automatic extension loading mechanism.
  79320. */
  79321. SQLITE_API void sqlite3_reset_auto_extension(void){
  79322. #ifndef SQLITE_OMIT_AUTOINIT
  79323. if( sqlite3_initialize()==SQLITE_OK )
  79324. #endif
  79325. {
  79326. #if SQLITE_THREADSAFE
  79327. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79328. #endif
  79329. wsdAutoextInit;
  79330. sqlite3_mutex_enter(mutex);
  79331. sqlite3_free(wsdAutoext.aExt);
  79332. wsdAutoext.aExt = 0;
  79333. wsdAutoext.nExt = 0;
  79334. sqlite3_mutex_leave(mutex);
  79335. }
  79336. }
  79337. /*
  79338. ** Load all automatic extensions.
  79339. **
  79340. ** If anything goes wrong, set an error in the database connection.
  79341. */
  79342. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  79343. int i;
  79344. int go = 1;
  79345. int rc;
  79346. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  79347. wsdAutoextInit;
  79348. if( wsdAutoext.nExt==0 ){
  79349. /* Common case: early out without every having to acquire a mutex */
  79350. return;
  79351. }
  79352. for(i=0; go; i++){
  79353. char *zErrmsg;
  79354. #if SQLITE_THREADSAFE
  79355. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  79356. #endif
  79357. sqlite3_mutex_enter(mutex);
  79358. if( i>=wsdAutoext.nExt ){
  79359. xInit = 0;
  79360. go = 0;
  79361. }else{
  79362. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  79363. wsdAutoext.aExt[i];
  79364. }
  79365. sqlite3_mutex_leave(mutex);
  79366. zErrmsg = 0;
  79367. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  79368. sqlite3Error(db, rc,
  79369. "automatic extension loading failed: %s", zErrmsg);
  79370. go = 0;
  79371. }
  79372. sqlite3_free(zErrmsg);
  79373. }
  79374. }
  79375. /************** End of loadext.c *********************************************/
  79376. /************** Begin file pragma.c ******************************************/
  79377. /*
  79378. ** 2003 April 6
  79379. **
  79380. ** The author disclaims copyright to this source code. In place of
  79381. ** a legal notice, here is a blessing:
  79382. **
  79383. ** May you do good and not evil.
  79384. ** May you find forgiveness for yourself and forgive others.
  79385. ** May you share freely, never taking more than you give.
  79386. **
  79387. *************************************************************************
  79388. ** This file contains code used to implement the PRAGMA command.
  79389. */
  79390. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  79391. # if defined(__APPLE__)
  79392. # define SQLITE_ENABLE_LOCKING_STYLE 1
  79393. # else
  79394. # define SQLITE_ENABLE_LOCKING_STYLE 0
  79395. # endif
  79396. #endif
  79397. /***************************************************************************
  79398. ** The next block of code, including the PragTyp_XXXX macro definitions and
  79399. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  79400. **
  79401. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  79402. ** that script. Then copy/paste the output in place of the following:
  79403. */
  79404. #define PragTyp_HEADER_VALUE 0
  79405. #define PragTyp_AUTO_VACUUM 1
  79406. #define PragTyp_FLAG 2
  79407. #define PragTyp_BUSY_TIMEOUT 3
  79408. #define PragTyp_CACHE_SIZE 4
  79409. #define PragTyp_CASE_SENSITIVE_LIKE 5
  79410. #define PragTyp_COLLATION_LIST 6
  79411. #define PragTyp_COMPILE_OPTIONS 7
  79412. #define PragTyp_DATA_STORE_DIRECTORY 8
  79413. #define PragTyp_DATABASE_LIST 9
  79414. #define PragTyp_DEFAULT_CACHE_SIZE 10
  79415. #define PragTyp_ENCODING 11
  79416. #define PragTyp_FOREIGN_KEY_CHECK 12
  79417. #define PragTyp_FOREIGN_KEY_LIST 13
  79418. #define PragTyp_INCREMENTAL_VACUUM 14
  79419. #define PragTyp_INDEX_INFO 15
  79420. #define PragTyp_INDEX_LIST 16
  79421. #define PragTyp_INTEGRITY_CHECK 17
  79422. #define PragTyp_JOURNAL_MODE 18
  79423. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  79424. #define PragTyp_LOCK_PROXY_FILE 20
  79425. #define PragTyp_LOCKING_MODE 21
  79426. #define PragTyp_PAGE_COUNT 22
  79427. #define PragTyp_MMAP_SIZE 23
  79428. #define PragTyp_PAGE_SIZE 24
  79429. #define PragTyp_SECURE_DELETE 25
  79430. #define PragTyp_SHRINK_MEMORY 26
  79431. #define PragTyp_SOFT_HEAP_LIMIT 27
  79432. #define PragTyp_STATS 28
  79433. #define PragTyp_SYNCHRONOUS 29
  79434. #define PragTyp_TABLE_INFO 30
  79435. #define PragTyp_TEMP_STORE 31
  79436. #define PragTyp_TEMP_STORE_DIRECTORY 32
  79437. #define PragTyp_WAL_AUTOCHECKPOINT 33
  79438. #define PragTyp_WAL_CHECKPOINT 34
  79439. #define PragTyp_ACTIVATE_EXTENSIONS 35
  79440. #define PragTyp_HEXKEY 36
  79441. #define PragTyp_KEY 37
  79442. #define PragTyp_REKEY 38
  79443. #define PragTyp_LOCK_STATUS 39
  79444. #define PragTyp_PARSER_TRACE 40
  79445. #define PragFlag_NeedSchema 0x01
  79446. static const struct sPragmaNames {
  79447. const char *const zName; /* Name of pragma */
  79448. u8 ePragTyp; /* PragTyp_XXX value */
  79449. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  79450. u32 iArg; /* Extra argument */
  79451. } aPragmaNames[] = {
  79452. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  79453. { /* zName: */ "activate_extensions",
  79454. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  79455. /* ePragFlag: */ 0,
  79456. /* iArg: */ 0 },
  79457. #endif
  79458. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79459. { /* zName: */ "application_id",
  79460. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79461. /* ePragFlag: */ 0,
  79462. /* iArg: */ 0 },
  79463. #endif
  79464. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79465. { /* zName: */ "auto_vacuum",
  79466. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  79467. /* ePragFlag: */ PragFlag_NeedSchema,
  79468. /* iArg: */ 0 },
  79469. #endif
  79470. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  79471. { /* zName: */ "automatic_index",
  79472. /* ePragTyp: */ PragTyp_FLAG,
  79473. /* ePragFlag: */ 0,
  79474. /* iArg: */ SQLITE_AutoIndex },
  79475. #endif
  79476. { /* zName: */ "busy_timeout",
  79477. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  79478. /* ePragFlag: */ 0,
  79479. /* iArg: */ 0 },
  79480. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79481. { /* zName: */ "cache_size",
  79482. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  79483. /* ePragFlag: */ PragFlag_NeedSchema,
  79484. /* iArg: */ 0 },
  79485. #endif
  79486. { /* zName: */ "cache_spill",
  79487. /* ePragTyp: */ PragTyp_FLAG,
  79488. /* ePragFlag: */ 0,
  79489. /* iArg: */ SQLITE_CacheSpill },
  79490. { /* zName: */ "case_sensitive_like",
  79491. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  79492. /* ePragFlag: */ 0,
  79493. /* iArg: */ 0 },
  79494. { /* zName: */ "checkpoint_fullfsync",
  79495. /* ePragTyp: */ PragTyp_FLAG,
  79496. /* ePragFlag: */ 0,
  79497. /* iArg: */ SQLITE_CkptFullFSync },
  79498. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79499. { /* zName: */ "collation_list",
  79500. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  79501. /* ePragFlag: */ 0,
  79502. /* iArg: */ 0 },
  79503. #endif
  79504. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  79505. { /* zName: */ "compile_options",
  79506. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  79507. /* ePragFlag: */ 0,
  79508. /* iArg: */ 0 },
  79509. #endif
  79510. { /* zName: */ "count_changes",
  79511. /* ePragTyp: */ PragTyp_FLAG,
  79512. /* ePragFlag: */ 0,
  79513. /* iArg: */ SQLITE_CountRows },
  79514. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  79515. { /* zName: */ "data_store_directory",
  79516. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  79517. /* ePragFlag: */ 0,
  79518. /* iArg: */ 0 },
  79519. #endif
  79520. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79521. { /* zName: */ "database_list",
  79522. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  79523. /* ePragFlag: */ PragFlag_NeedSchema,
  79524. /* iArg: */ 0 },
  79525. #endif
  79526. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  79527. { /* zName: */ "default_cache_size",
  79528. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  79529. /* ePragFlag: */ PragFlag_NeedSchema,
  79530. /* iArg: */ 0 },
  79531. #endif
  79532. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79533. { /* zName: */ "defer_foreign_keys",
  79534. /* ePragTyp: */ PragTyp_FLAG,
  79535. /* ePragFlag: */ 0,
  79536. /* iArg: */ SQLITE_DeferFKs },
  79537. #endif
  79538. { /* zName: */ "empty_result_callbacks",
  79539. /* ePragTyp: */ PragTyp_FLAG,
  79540. /* ePragFlag: */ 0,
  79541. /* iArg: */ SQLITE_NullCallback },
  79542. #if !defined(SQLITE_OMIT_UTF16)
  79543. { /* zName: */ "encoding",
  79544. /* ePragTyp: */ PragTyp_ENCODING,
  79545. /* ePragFlag: */ 0,
  79546. /* iArg: */ 0 },
  79547. #endif
  79548. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79549. { /* zName: */ "foreign_key_check",
  79550. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  79551. /* ePragFlag: */ PragFlag_NeedSchema,
  79552. /* iArg: */ 0 },
  79553. #endif
  79554. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  79555. { /* zName: */ "foreign_key_list",
  79556. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  79557. /* ePragFlag: */ PragFlag_NeedSchema,
  79558. /* iArg: */ 0 },
  79559. #endif
  79560. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79561. { /* zName: */ "foreign_keys",
  79562. /* ePragTyp: */ PragTyp_FLAG,
  79563. /* ePragFlag: */ 0,
  79564. /* iArg: */ SQLITE_ForeignKeys },
  79565. #endif
  79566. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79567. { /* zName: */ "freelist_count",
  79568. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79569. /* ePragFlag: */ 0,
  79570. /* iArg: */ 0 },
  79571. #endif
  79572. { /* zName: */ "full_column_names",
  79573. /* ePragTyp: */ PragTyp_FLAG,
  79574. /* ePragFlag: */ 0,
  79575. /* iArg: */ SQLITE_FullColNames },
  79576. { /* zName: */ "fullfsync",
  79577. /* ePragTyp: */ PragTyp_FLAG,
  79578. /* ePragFlag: */ 0,
  79579. /* iArg: */ SQLITE_FullFSync },
  79580. #if defined(SQLITE_HAS_CODEC)
  79581. { /* zName: */ "hexkey",
  79582. /* ePragTyp: */ PragTyp_HEXKEY,
  79583. /* ePragFlag: */ 0,
  79584. /* iArg: */ 0 },
  79585. { /* zName: */ "hexrekey",
  79586. /* ePragTyp: */ PragTyp_HEXKEY,
  79587. /* ePragFlag: */ 0,
  79588. /* iArg: */ 0 },
  79589. #endif
  79590. #if !defined(SQLITE_OMIT_CHECK)
  79591. { /* zName: */ "ignore_check_constraints",
  79592. /* ePragTyp: */ PragTyp_FLAG,
  79593. /* ePragFlag: */ 0,
  79594. /* iArg: */ SQLITE_IgnoreChecks },
  79595. #endif
  79596. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79597. { /* zName: */ "incremental_vacuum",
  79598. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  79599. /* ePragFlag: */ PragFlag_NeedSchema,
  79600. /* iArg: */ 0 },
  79601. #endif
  79602. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79603. { /* zName: */ "index_info",
  79604. /* ePragTyp: */ PragTyp_INDEX_INFO,
  79605. /* ePragFlag: */ PragFlag_NeedSchema,
  79606. /* iArg: */ 0 },
  79607. { /* zName: */ "index_list",
  79608. /* ePragTyp: */ PragTyp_INDEX_LIST,
  79609. /* ePragFlag: */ PragFlag_NeedSchema,
  79610. /* iArg: */ 0 },
  79611. #endif
  79612. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  79613. { /* zName: */ "integrity_check",
  79614. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  79615. /* ePragFlag: */ PragFlag_NeedSchema,
  79616. /* iArg: */ 0 },
  79617. #endif
  79618. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79619. { /* zName: */ "journal_mode",
  79620. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  79621. /* ePragFlag: */ PragFlag_NeedSchema,
  79622. /* iArg: */ 0 },
  79623. { /* zName: */ "journal_size_limit",
  79624. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  79625. /* ePragFlag: */ 0,
  79626. /* iArg: */ 0 },
  79627. #endif
  79628. #if defined(SQLITE_HAS_CODEC)
  79629. { /* zName: */ "key",
  79630. /* ePragTyp: */ PragTyp_KEY,
  79631. /* ePragFlag: */ 0,
  79632. /* iArg: */ 0 },
  79633. #endif
  79634. { /* zName: */ "legacy_file_format",
  79635. /* ePragTyp: */ PragTyp_FLAG,
  79636. /* ePragFlag: */ 0,
  79637. /* iArg: */ SQLITE_LegacyFileFmt },
  79638. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  79639. { /* zName: */ "lock_proxy_file",
  79640. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  79641. /* ePragFlag: */ 0,
  79642. /* iArg: */ 0 },
  79643. #endif
  79644. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  79645. { /* zName: */ "lock_status",
  79646. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  79647. /* ePragFlag: */ 0,
  79648. /* iArg: */ 0 },
  79649. #endif
  79650. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79651. { /* zName: */ "locking_mode",
  79652. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  79653. /* ePragFlag: */ 0,
  79654. /* iArg: */ 0 },
  79655. { /* zName: */ "max_page_count",
  79656. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  79657. /* ePragFlag: */ PragFlag_NeedSchema,
  79658. /* iArg: */ 0 },
  79659. { /* zName: */ "mmap_size",
  79660. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  79661. /* ePragFlag: */ 0,
  79662. /* iArg: */ 0 },
  79663. { /* zName: */ "page_count",
  79664. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  79665. /* ePragFlag: */ PragFlag_NeedSchema,
  79666. /* iArg: */ 0 },
  79667. { /* zName: */ "page_size",
  79668. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  79669. /* ePragFlag: */ 0,
  79670. /* iArg: */ 0 },
  79671. #endif
  79672. #if defined(SQLITE_DEBUG)
  79673. { /* zName: */ "parser_trace",
  79674. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  79675. /* ePragFlag: */ 0,
  79676. /* iArg: */ 0 },
  79677. #endif
  79678. { /* zName: */ "query_only",
  79679. /* ePragTyp: */ PragTyp_FLAG,
  79680. /* ePragFlag: */ 0,
  79681. /* iArg: */ SQLITE_QueryOnly },
  79682. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  79683. { /* zName: */ "quick_check",
  79684. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  79685. /* ePragFlag: */ PragFlag_NeedSchema,
  79686. /* iArg: */ 0 },
  79687. #endif
  79688. { /* zName: */ "read_uncommitted",
  79689. /* ePragTyp: */ PragTyp_FLAG,
  79690. /* ePragFlag: */ 0,
  79691. /* iArg: */ SQLITE_ReadUncommitted },
  79692. { /* zName: */ "recursive_triggers",
  79693. /* ePragTyp: */ PragTyp_FLAG,
  79694. /* ePragFlag: */ 0,
  79695. /* iArg: */ SQLITE_RecTriggers },
  79696. #if defined(SQLITE_HAS_CODEC)
  79697. { /* zName: */ "rekey",
  79698. /* ePragTyp: */ PragTyp_REKEY,
  79699. /* ePragFlag: */ 0,
  79700. /* iArg: */ 0 },
  79701. #endif
  79702. { /* zName: */ "reverse_unordered_selects",
  79703. /* ePragTyp: */ PragTyp_FLAG,
  79704. /* ePragFlag: */ 0,
  79705. /* iArg: */ SQLITE_ReverseOrder },
  79706. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79707. { /* zName: */ "schema_version",
  79708. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79709. /* ePragFlag: */ 0,
  79710. /* iArg: */ 0 },
  79711. #endif
  79712. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79713. { /* zName: */ "secure_delete",
  79714. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  79715. /* ePragFlag: */ 0,
  79716. /* iArg: */ 0 },
  79717. #endif
  79718. { /* zName: */ "short_column_names",
  79719. /* ePragTyp: */ PragTyp_FLAG,
  79720. /* ePragFlag: */ 0,
  79721. /* iArg: */ SQLITE_ShortColNames },
  79722. { /* zName: */ "shrink_memory",
  79723. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  79724. /* ePragFlag: */ 0,
  79725. /* iArg: */ 0 },
  79726. { /* zName: */ "soft_heap_limit",
  79727. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  79728. /* ePragFlag: */ 0,
  79729. /* iArg: */ 0 },
  79730. #if defined(SQLITE_DEBUG)
  79731. { /* zName: */ "sql_trace",
  79732. /* ePragTyp: */ PragTyp_FLAG,
  79733. /* ePragFlag: */ 0,
  79734. /* iArg: */ SQLITE_SqlTrace },
  79735. #endif
  79736. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79737. { /* zName: */ "stats",
  79738. /* ePragTyp: */ PragTyp_STATS,
  79739. /* ePragFlag: */ PragFlag_NeedSchema,
  79740. /* iArg: */ 0 },
  79741. #endif
  79742. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79743. { /* zName: */ "synchronous",
  79744. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  79745. /* ePragFlag: */ PragFlag_NeedSchema,
  79746. /* iArg: */ 0 },
  79747. #endif
  79748. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  79749. { /* zName: */ "table_info",
  79750. /* ePragTyp: */ PragTyp_TABLE_INFO,
  79751. /* ePragFlag: */ PragFlag_NeedSchema,
  79752. /* iArg: */ 0 },
  79753. #endif
  79754. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  79755. { /* zName: */ "temp_store",
  79756. /* ePragTyp: */ PragTyp_TEMP_STORE,
  79757. /* ePragFlag: */ 0,
  79758. /* iArg: */ 0 },
  79759. { /* zName: */ "temp_store_directory",
  79760. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  79761. /* ePragFlag: */ 0,
  79762. /* iArg: */ 0 },
  79763. #endif
  79764. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  79765. { /* zName: */ "user_version",
  79766. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  79767. /* ePragFlag: */ 0,
  79768. /* iArg: */ 0 },
  79769. #endif
  79770. #if defined(SQLITE_DEBUG)
  79771. { /* zName: */ "vdbe_addoptrace",
  79772. /* ePragTyp: */ PragTyp_FLAG,
  79773. /* ePragFlag: */ 0,
  79774. /* iArg: */ SQLITE_VdbeAddopTrace },
  79775. { /* zName: */ "vdbe_debug",
  79776. /* ePragTyp: */ PragTyp_FLAG,
  79777. /* ePragFlag: */ 0,
  79778. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  79779. { /* zName: */ "vdbe_listing",
  79780. /* ePragTyp: */ PragTyp_FLAG,
  79781. /* ePragFlag: */ 0,
  79782. /* iArg: */ SQLITE_VdbeListing },
  79783. { /* zName: */ "vdbe_trace",
  79784. /* ePragTyp: */ PragTyp_FLAG,
  79785. /* ePragFlag: */ 0,
  79786. /* iArg: */ SQLITE_VdbeTrace },
  79787. #endif
  79788. #if !defined(SQLITE_OMIT_WAL)
  79789. { /* zName: */ "wal_autocheckpoint",
  79790. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  79791. /* ePragFlag: */ 0,
  79792. /* iArg: */ 0 },
  79793. { /* zName: */ "wal_checkpoint",
  79794. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  79795. /* ePragFlag: */ PragFlag_NeedSchema,
  79796. /* iArg: */ 0 },
  79797. #endif
  79798. { /* zName: */ "writable_schema",
  79799. /* ePragTyp: */ PragTyp_FLAG,
  79800. /* ePragFlag: */ 0,
  79801. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  79802. };
  79803. /* Number of pragmas: 56 on by default, 68 total. */
  79804. /* End of the automatically generated pragma table.
  79805. ***************************************************************************/
  79806. /*
  79807. ** Interpret the given string as a safety level. Return 0 for OFF,
  79808. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  79809. ** unrecognized string argument. The FULL option is disallowed
  79810. ** if the omitFull parameter it 1.
  79811. **
  79812. ** Note that the values returned are one less that the values that
  79813. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  79814. ** to support legacy SQL code. The safety level used to be boolean
  79815. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  79816. */
  79817. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  79818. /* 123456789 123456789 */
  79819. static const char zText[] = "onoffalseyestruefull";
  79820. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  79821. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  79822. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  79823. int i, n;
  79824. if( sqlite3Isdigit(*z) ){
  79825. return (u8)sqlite3Atoi(z);
  79826. }
  79827. n = sqlite3Strlen30(z);
  79828. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  79829. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  79830. return iValue[i];
  79831. }
  79832. }
  79833. return dflt;
  79834. }
  79835. /*
  79836. ** Interpret the given string as a boolean value.
  79837. */
  79838. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  79839. return getSafetyLevel(z,1,dflt)!=0;
  79840. }
  79841. /* The sqlite3GetBoolean() function is used by other modules but the
  79842. ** remainder of this file is specific to PRAGMA processing. So omit
  79843. ** the rest of the file if PRAGMAs are omitted from the build.
  79844. */
  79845. #if !defined(SQLITE_OMIT_PRAGMA)
  79846. /*
  79847. ** Interpret the given string as a locking mode value.
  79848. */
  79849. static int getLockingMode(const char *z){
  79850. if( z ){
  79851. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  79852. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  79853. }
  79854. return PAGER_LOCKINGMODE_QUERY;
  79855. }
  79856. #ifndef SQLITE_OMIT_AUTOVACUUM
  79857. /*
  79858. ** Interpret the given string as an auto-vacuum mode value.
  79859. **
  79860. ** The following strings, "none", "full" and "incremental" are
  79861. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  79862. */
  79863. static int getAutoVacuum(const char *z){
  79864. int i;
  79865. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  79866. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  79867. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  79868. i = sqlite3Atoi(z);
  79869. return (u8)((i>=0&&i<=2)?i:0);
  79870. }
  79871. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  79872. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79873. /*
  79874. ** Interpret the given string as a temp db location. Return 1 for file
  79875. ** backed temporary databases, 2 for the Red-Black tree in memory database
  79876. ** and 0 to use the compile-time default.
  79877. */
  79878. static int getTempStore(const char *z){
  79879. if( z[0]>='0' && z[0]<='2' ){
  79880. return z[0] - '0';
  79881. }else if( sqlite3StrICmp(z, "file")==0 ){
  79882. return 1;
  79883. }else if( sqlite3StrICmp(z, "memory")==0 ){
  79884. return 2;
  79885. }else{
  79886. return 0;
  79887. }
  79888. }
  79889. #endif /* SQLITE_PAGER_PRAGMAS */
  79890. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79891. /*
  79892. ** Invalidate temp storage, either when the temp storage is changed
  79893. ** from default, or when 'file' and the temp_store_directory has changed
  79894. */
  79895. static int invalidateTempStorage(Parse *pParse){
  79896. sqlite3 *db = pParse->db;
  79897. if( db->aDb[1].pBt!=0 ){
  79898. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  79899. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  79900. "from within a transaction");
  79901. return SQLITE_ERROR;
  79902. }
  79903. sqlite3BtreeClose(db->aDb[1].pBt);
  79904. db->aDb[1].pBt = 0;
  79905. sqlite3ResetAllSchemasOfConnection(db);
  79906. }
  79907. return SQLITE_OK;
  79908. }
  79909. #endif /* SQLITE_PAGER_PRAGMAS */
  79910. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79911. /*
  79912. ** If the TEMP database is open, close it and mark the database schema
  79913. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  79914. ** or DEFAULT_TEMP_STORE pragmas.
  79915. */
  79916. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  79917. int ts = getTempStore(zStorageType);
  79918. sqlite3 *db = pParse->db;
  79919. if( db->temp_store==ts ) return SQLITE_OK;
  79920. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  79921. return SQLITE_ERROR;
  79922. }
  79923. db->temp_store = (u8)ts;
  79924. return SQLITE_OK;
  79925. }
  79926. #endif /* SQLITE_PAGER_PRAGMAS */
  79927. /*
  79928. ** Generate code to return a single integer value.
  79929. */
  79930. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  79931. Vdbe *v = sqlite3GetVdbe(pParse);
  79932. int mem = ++pParse->nMem;
  79933. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  79934. if( pI64 ){
  79935. memcpy(pI64, &value, sizeof(value));
  79936. }
  79937. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  79938. sqlite3VdbeSetNumCols(v, 1);
  79939. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  79940. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  79941. }
  79942. /*
  79943. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  79944. ** set these values for all pagers.
  79945. */
  79946. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79947. static void setAllPagerFlags(sqlite3 *db){
  79948. if( db->autoCommit ){
  79949. Db *pDb = db->aDb;
  79950. int n = db->nDb;
  79951. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  79952. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  79953. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  79954. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  79955. == PAGER_FLAGS_MASK );
  79956. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  79957. while( (n--) > 0 ){
  79958. if( pDb->pBt ){
  79959. sqlite3BtreeSetPagerFlags(pDb->pBt,
  79960. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  79961. }
  79962. pDb++;
  79963. }
  79964. }
  79965. }
  79966. #else
  79967. # define setAllPagerFlags(X) /* no-op */
  79968. #endif
  79969. /*
  79970. ** Return a human-readable name for a constraint resolution action.
  79971. */
  79972. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79973. static const char *actionName(u8 action){
  79974. const char *zName;
  79975. switch( action ){
  79976. case OE_SetNull: zName = "SET NULL"; break;
  79977. case OE_SetDflt: zName = "SET DEFAULT"; break;
  79978. case OE_Cascade: zName = "CASCADE"; break;
  79979. case OE_Restrict: zName = "RESTRICT"; break;
  79980. default: zName = "NO ACTION";
  79981. assert( action==OE_None ); break;
  79982. }
  79983. return zName;
  79984. }
  79985. #endif
  79986. /*
  79987. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  79988. ** defined in pager.h. This function returns the associated lowercase
  79989. ** journal-mode name.
  79990. */
  79991. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  79992. static char * const azModeName[] = {
  79993. "delete", "persist", "off", "truncate", "memory"
  79994. #ifndef SQLITE_OMIT_WAL
  79995. , "wal"
  79996. #endif
  79997. };
  79998. assert( PAGER_JOURNALMODE_DELETE==0 );
  79999. assert( PAGER_JOURNALMODE_PERSIST==1 );
  80000. assert( PAGER_JOURNALMODE_OFF==2 );
  80001. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  80002. assert( PAGER_JOURNALMODE_MEMORY==4 );
  80003. assert( PAGER_JOURNALMODE_WAL==5 );
  80004. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  80005. if( eMode==ArraySize(azModeName) ) return 0;
  80006. return azModeName[eMode];
  80007. }
  80008. /*
  80009. ** Process a pragma statement.
  80010. **
  80011. ** Pragmas are of this form:
  80012. **
  80013. ** PRAGMA [database.]id [= value]
  80014. **
  80015. ** The identifier might also be a string. The value is a string, and
  80016. ** identifier, or a number. If minusFlag is true, then the value is
  80017. ** a number that was preceded by a minus sign.
  80018. **
  80019. ** If the left side is "database.id" then pId1 is the database name
  80020. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  80021. ** id and pId2 is any empty string.
  80022. */
  80023. SQLITE_PRIVATE void sqlite3Pragma(
  80024. Parse *pParse,
  80025. Token *pId1, /* First part of [database.]id field */
  80026. Token *pId2, /* Second part of [database.]id field, or NULL */
  80027. Token *pValue, /* Token for <value>, or NULL */
  80028. int minusFlag /* True if a '-' sign preceded <value> */
  80029. ){
  80030. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  80031. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  80032. const char *zDb = 0; /* The database name */
  80033. Token *pId; /* Pointer to <id> token */
  80034. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  80035. int iDb; /* Database index for <database> */
  80036. int lwr, upr, mid; /* Binary search bounds */
  80037. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  80038. sqlite3 *db = pParse->db; /* The database connection */
  80039. Db *pDb; /* The specific database being pragmaed */
  80040. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  80041. if( v==0 ) return;
  80042. sqlite3VdbeRunOnlyOnce(v);
  80043. pParse->nMem = 2;
  80044. /* Interpret the [database.] part of the pragma statement. iDb is the
  80045. ** index of the database this pragma is being applied to in db.aDb[]. */
  80046. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  80047. if( iDb<0 ) return;
  80048. pDb = &db->aDb[iDb];
  80049. /* If the temp database has been explicitly named as part of the
  80050. ** pragma, make sure it is open.
  80051. */
  80052. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  80053. return;
  80054. }
  80055. zLeft = sqlite3NameFromToken(db, pId);
  80056. if( !zLeft ) return;
  80057. if( minusFlag ){
  80058. zRight = sqlite3MPrintf(db, "-%T", pValue);
  80059. }else{
  80060. zRight = sqlite3NameFromToken(db, pValue);
  80061. }
  80062. assert( pId2 );
  80063. zDb = pId2->n>0 ? pDb->zName : 0;
  80064. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  80065. goto pragma_out;
  80066. }
  80067. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  80068. ** connection. If it returns SQLITE_OK, then assume that the VFS
  80069. ** handled the pragma and generate a no-op prepared statement.
  80070. */
  80071. aFcntl[0] = 0;
  80072. aFcntl[1] = zLeft;
  80073. aFcntl[2] = zRight;
  80074. aFcntl[3] = 0;
  80075. db->busyHandler.nBusy = 0;
  80076. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  80077. if( rc==SQLITE_OK ){
  80078. if( aFcntl[0] ){
  80079. int mem = ++pParse->nMem;
  80080. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  80081. sqlite3VdbeSetNumCols(v, 1);
  80082. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  80083. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  80084. sqlite3_free(aFcntl[0]);
  80085. }
  80086. goto pragma_out;
  80087. }
  80088. if( rc!=SQLITE_NOTFOUND ){
  80089. if( aFcntl[0] ){
  80090. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  80091. sqlite3_free(aFcntl[0]);
  80092. }
  80093. pParse->nErr++;
  80094. pParse->rc = rc;
  80095. goto pragma_out;
  80096. }
  80097. /* Locate the pragma in the lookup table */
  80098. lwr = 0;
  80099. upr = ArraySize(aPragmaNames)-1;
  80100. while( lwr<=upr ){
  80101. mid = (lwr+upr)/2;
  80102. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  80103. if( rc==0 ) break;
  80104. if( rc<0 ){
  80105. upr = mid - 1;
  80106. }else{
  80107. lwr = mid + 1;
  80108. }
  80109. }
  80110. if( lwr>upr ) goto pragma_out;
  80111. /* Make sure the database schema is loaded if the pragma requires that */
  80112. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  80113. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  80114. }
  80115. /* Jump to the appropriate pragma handler */
  80116. switch( aPragmaNames[mid].ePragTyp ){
  80117. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  80118. /*
  80119. ** PRAGMA [database.]default_cache_size
  80120. ** PRAGMA [database.]default_cache_size=N
  80121. **
  80122. ** The first form reports the current persistent setting for the
  80123. ** page cache size. The value returned is the maximum number of
  80124. ** pages in the page cache. The second form sets both the current
  80125. ** page cache size value and the persistent page cache size value
  80126. ** stored in the database file.
  80127. **
  80128. ** Older versions of SQLite would set the default cache size to a
  80129. ** negative number to indicate synchronous=OFF. These days, synchronous
  80130. ** is always on by default regardless of the sign of the default cache
  80131. ** size. But continue to take the absolute value of the default cache
  80132. ** size of historical compatibility.
  80133. */
  80134. case PragTyp_DEFAULT_CACHE_SIZE: {
  80135. static const VdbeOpList getCacheSize[] = {
  80136. { OP_Transaction, 0, 0, 0}, /* 0 */
  80137. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  80138. { OP_IfPos, 1, 8, 0},
  80139. { OP_Integer, 0, 2, 0},
  80140. { OP_Subtract, 1, 2, 1},
  80141. { OP_IfPos, 1, 8, 0},
  80142. { OP_Integer, 0, 1, 0}, /* 6 */
  80143. { OP_Noop, 0, 0, 0},
  80144. { OP_ResultRow, 1, 1, 0},
  80145. };
  80146. int addr;
  80147. sqlite3VdbeUsesBtree(v, iDb);
  80148. if( !zRight ){
  80149. sqlite3VdbeSetNumCols(v, 1);
  80150. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  80151. pParse->nMem += 2;
  80152. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  80153. sqlite3VdbeChangeP1(v, addr, iDb);
  80154. sqlite3VdbeChangeP1(v, addr+1, iDb);
  80155. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  80156. }else{
  80157. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  80158. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80159. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  80160. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  80161. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80162. pDb->pSchema->cache_size = size;
  80163. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  80164. }
  80165. break;
  80166. }
  80167. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  80168. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  80169. /*
  80170. ** PRAGMA [database.]page_size
  80171. ** PRAGMA [database.]page_size=N
  80172. **
  80173. ** The first form reports the current setting for the
  80174. ** database page size in bytes. The second form sets the
  80175. ** database page size value. The value can only be set if
  80176. ** the database has not yet been created.
  80177. */
  80178. case PragTyp_PAGE_SIZE: {
  80179. Btree *pBt = pDb->pBt;
  80180. assert( pBt!=0 );
  80181. if( !zRight ){
  80182. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  80183. returnSingleInt(pParse, "page_size", size);
  80184. }else{
  80185. /* Malloc may fail when setting the page-size, as there is an internal
  80186. ** buffer that the pager module resizes using sqlite3_realloc().
  80187. */
  80188. db->nextPagesize = sqlite3Atoi(zRight);
  80189. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  80190. db->mallocFailed = 1;
  80191. }
  80192. }
  80193. break;
  80194. }
  80195. /*
  80196. ** PRAGMA [database.]secure_delete
  80197. ** PRAGMA [database.]secure_delete=ON/OFF
  80198. **
  80199. ** The first form reports the current setting for the
  80200. ** secure_delete flag. The second form changes the secure_delete
  80201. ** flag setting and reports thenew value.
  80202. */
  80203. case PragTyp_SECURE_DELETE: {
  80204. Btree *pBt = pDb->pBt;
  80205. int b = -1;
  80206. assert( pBt!=0 );
  80207. if( zRight ){
  80208. b = sqlite3GetBoolean(zRight, 0);
  80209. }
  80210. if( pId2->n==0 && b>=0 ){
  80211. int ii;
  80212. for(ii=0; ii<db->nDb; ii++){
  80213. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  80214. }
  80215. }
  80216. b = sqlite3BtreeSecureDelete(pBt, b);
  80217. returnSingleInt(pParse, "secure_delete", b);
  80218. break;
  80219. }
  80220. /*
  80221. ** PRAGMA [database.]max_page_count
  80222. ** PRAGMA [database.]max_page_count=N
  80223. **
  80224. ** The first form reports the current setting for the
  80225. ** maximum number of pages in the database file. The
  80226. ** second form attempts to change this setting. Both
  80227. ** forms return the current setting.
  80228. **
  80229. ** The absolute value of N is used. This is undocumented and might
  80230. ** change. The only purpose is to provide an easy way to test
  80231. ** the sqlite3AbsInt32() function.
  80232. **
  80233. ** PRAGMA [database.]page_count
  80234. **
  80235. ** Return the number of pages in the specified database.
  80236. */
  80237. case PragTyp_PAGE_COUNT: {
  80238. int iReg;
  80239. sqlite3CodeVerifySchema(pParse, iDb);
  80240. iReg = ++pParse->nMem;
  80241. if( sqlite3Tolower(zLeft[0])=='p' ){
  80242. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  80243. }else{
  80244. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  80245. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  80246. }
  80247. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  80248. sqlite3VdbeSetNumCols(v, 1);
  80249. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  80250. break;
  80251. }
  80252. /*
  80253. ** PRAGMA [database.]locking_mode
  80254. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  80255. */
  80256. case PragTyp_LOCKING_MODE: {
  80257. const char *zRet = "normal";
  80258. int eMode = getLockingMode(zRight);
  80259. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  80260. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  80261. ** the current default locking mode (which may be different to
  80262. ** the locking-mode of the main database).
  80263. */
  80264. eMode = db->dfltLockMode;
  80265. }else{
  80266. Pager *pPager;
  80267. if( pId2->n==0 ){
  80268. /* This indicates that no database name was specified as part
  80269. ** of the PRAGMA command. In this case the locking-mode must be
  80270. ** set on all attached databases, as well as the main db file.
  80271. **
  80272. ** Also, the sqlite3.dfltLockMode variable is set so that
  80273. ** any subsequently attached databases also use the specified
  80274. ** locking mode.
  80275. */
  80276. int ii;
  80277. assert(pDb==&db->aDb[0]);
  80278. for(ii=2; ii<db->nDb; ii++){
  80279. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  80280. sqlite3PagerLockingMode(pPager, eMode);
  80281. }
  80282. db->dfltLockMode = (u8)eMode;
  80283. }
  80284. pPager = sqlite3BtreePager(pDb->pBt);
  80285. eMode = sqlite3PagerLockingMode(pPager, eMode);
  80286. }
  80287. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  80288. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  80289. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  80290. zRet = "exclusive";
  80291. }
  80292. sqlite3VdbeSetNumCols(v, 1);
  80293. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  80294. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  80295. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80296. break;
  80297. }
  80298. /*
  80299. ** PRAGMA [database.]journal_mode
  80300. ** PRAGMA [database.]journal_mode =
  80301. ** (delete|persist|off|truncate|memory|wal|off)
  80302. */
  80303. case PragTyp_JOURNAL_MODE: {
  80304. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  80305. int ii; /* Loop counter */
  80306. sqlite3VdbeSetNumCols(v, 1);
  80307. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  80308. if( zRight==0 ){
  80309. /* If there is no "=MODE" part of the pragma, do a query for the
  80310. ** current mode */
  80311. eMode = PAGER_JOURNALMODE_QUERY;
  80312. }else{
  80313. const char *zMode;
  80314. int n = sqlite3Strlen30(zRight);
  80315. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  80316. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  80317. }
  80318. if( !zMode ){
  80319. /* If the "=MODE" part does not match any known journal mode,
  80320. ** then do a query */
  80321. eMode = PAGER_JOURNALMODE_QUERY;
  80322. }
  80323. }
  80324. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  80325. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  80326. iDb = 0;
  80327. pId2->n = 1;
  80328. }
  80329. for(ii=db->nDb-1; ii>=0; ii--){
  80330. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  80331. sqlite3VdbeUsesBtree(v, ii);
  80332. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  80333. }
  80334. }
  80335. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80336. break;
  80337. }
  80338. /*
  80339. ** PRAGMA [database.]journal_size_limit
  80340. ** PRAGMA [database.]journal_size_limit=N
  80341. **
  80342. ** Get or set the size limit on rollback journal files.
  80343. */
  80344. case PragTyp_JOURNAL_SIZE_LIMIT: {
  80345. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80346. i64 iLimit = -2;
  80347. if( zRight ){
  80348. sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
  80349. if( iLimit<-1 ) iLimit = -1;
  80350. }
  80351. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  80352. returnSingleInt(pParse, "journal_size_limit", iLimit);
  80353. break;
  80354. }
  80355. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  80356. /*
  80357. ** PRAGMA [database.]auto_vacuum
  80358. ** PRAGMA [database.]auto_vacuum=N
  80359. **
  80360. ** Get or set the value of the database 'auto-vacuum' parameter.
  80361. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  80362. */
  80363. #ifndef SQLITE_OMIT_AUTOVACUUM
  80364. case PragTyp_AUTO_VACUUM: {
  80365. Btree *pBt = pDb->pBt;
  80366. assert( pBt!=0 );
  80367. if( !zRight ){
  80368. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  80369. }else{
  80370. int eAuto = getAutoVacuum(zRight);
  80371. assert( eAuto>=0 && eAuto<=2 );
  80372. db->nextAutovac = (u8)eAuto;
  80373. /* Call SetAutoVacuum() to set initialize the internal auto and
  80374. ** incr-vacuum flags. This is required in case this connection
  80375. ** creates the database file. It is important that it is created
  80376. ** as an auto-vacuum capable db.
  80377. */
  80378. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  80379. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  80380. /* When setting the auto_vacuum mode to either "full" or
  80381. ** "incremental", write the value of meta[6] in the database
  80382. ** file. Before writing to meta[6], check that meta[3] indicates
  80383. ** that this really is an auto-vacuum capable database.
  80384. */
  80385. static const VdbeOpList setMeta6[] = {
  80386. { OP_Transaction, 0, 1, 0}, /* 0 */
  80387. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  80388. { OP_If, 1, 0, 0}, /* 2 */
  80389. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  80390. { OP_Integer, 0, 1, 0}, /* 4 */
  80391. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  80392. };
  80393. int iAddr;
  80394. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  80395. sqlite3VdbeChangeP1(v, iAddr, iDb);
  80396. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  80397. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  80398. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  80399. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  80400. sqlite3VdbeUsesBtree(v, iDb);
  80401. }
  80402. }
  80403. break;
  80404. }
  80405. #endif
  80406. /*
  80407. ** PRAGMA [database.]incremental_vacuum(N)
  80408. **
  80409. ** Do N steps of incremental vacuuming on a database.
  80410. */
  80411. #ifndef SQLITE_OMIT_AUTOVACUUM
  80412. case PragTyp_INCREMENTAL_VACUUM: {
  80413. int iLimit, addr;
  80414. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  80415. iLimit = 0x7fffffff;
  80416. }
  80417. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80418. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  80419. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  80420. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  80421. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  80422. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  80423. sqlite3VdbeJumpHere(v, addr);
  80424. break;
  80425. }
  80426. #endif
  80427. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80428. /*
  80429. ** PRAGMA [database.]cache_size
  80430. ** PRAGMA [database.]cache_size=N
  80431. **
  80432. ** The first form reports the current local setting for the
  80433. ** page cache size. The second form sets the local
  80434. ** page cache size value. If N is positive then that is the
  80435. ** number of pages in the cache. If N is negative, then the
  80436. ** number of pages is adjusted so that the cache uses -N kibibytes
  80437. ** of memory.
  80438. */
  80439. case PragTyp_CACHE_SIZE: {
  80440. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80441. if( !zRight ){
  80442. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  80443. }else{
  80444. int size = sqlite3Atoi(zRight);
  80445. pDb->pSchema->cache_size = size;
  80446. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  80447. }
  80448. break;
  80449. }
  80450. /*
  80451. ** PRAGMA [database.]mmap_size(N)
  80452. **
  80453. ** Used to set mapping size limit. The mapping size limit is
  80454. ** used to limit the aggregate size of all memory mapped regions of the
  80455. ** database file. If this parameter is set to zero, then memory mapping
  80456. ** is not used at all. If N is negative, then the default memory map
  80457. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  80458. ** The parameter N is measured in bytes.
  80459. **
  80460. ** This value is advisory. The underlying VFS is free to memory map
  80461. ** as little or as much as it wants. Except, if N is set to 0 then the
  80462. ** upper layers will never invoke the xFetch interfaces to the VFS.
  80463. */
  80464. case PragTyp_MMAP_SIZE: {
  80465. sqlite3_int64 sz;
  80466. #if SQLITE_MAX_MMAP_SIZE>0
  80467. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80468. if( zRight ){
  80469. int ii;
  80470. sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
  80471. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  80472. if( pId2->n==0 ) db->szMmap = sz;
  80473. for(ii=db->nDb-1; ii>=0; ii--){
  80474. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  80475. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  80476. }
  80477. }
  80478. }
  80479. sz = -1;
  80480. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  80481. #else
  80482. sz = 0;
  80483. rc = SQLITE_OK;
  80484. #endif
  80485. if( rc==SQLITE_OK ){
  80486. returnSingleInt(pParse, "mmap_size", sz);
  80487. }else if( rc!=SQLITE_NOTFOUND ){
  80488. pParse->nErr++;
  80489. pParse->rc = rc;
  80490. }
  80491. break;
  80492. }
  80493. /*
  80494. ** PRAGMA temp_store
  80495. ** PRAGMA temp_store = "default"|"memory"|"file"
  80496. **
  80497. ** Return or set the local value of the temp_store flag. Changing
  80498. ** the local value does not make changes to the disk file and the default
  80499. ** value will be restored the next time the database is opened.
  80500. **
  80501. ** Note that it is possible for the library compile-time options to
  80502. ** override this setting
  80503. */
  80504. case PragTyp_TEMP_STORE: {
  80505. if( !zRight ){
  80506. returnSingleInt(pParse, "temp_store", db->temp_store);
  80507. }else{
  80508. changeTempStorage(pParse, zRight);
  80509. }
  80510. break;
  80511. }
  80512. /*
  80513. ** PRAGMA temp_store_directory
  80514. ** PRAGMA temp_store_directory = ""|"directory_name"
  80515. **
  80516. ** Return or set the local value of the temp_store_directory flag. Changing
  80517. ** the value sets a specific directory to be used for temporary files.
  80518. ** Setting to a null string reverts to the default temporary directory search.
  80519. ** If temporary directory is changed, then invalidateTempStorage.
  80520. **
  80521. */
  80522. case PragTyp_TEMP_STORE_DIRECTORY: {
  80523. if( !zRight ){
  80524. if( sqlite3_temp_directory ){
  80525. sqlite3VdbeSetNumCols(v, 1);
  80526. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80527. "temp_store_directory", SQLITE_STATIC);
  80528. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  80529. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80530. }
  80531. }else{
  80532. #ifndef SQLITE_OMIT_WSD
  80533. if( zRight[0] ){
  80534. int res;
  80535. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  80536. if( rc!=SQLITE_OK || res==0 ){
  80537. sqlite3ErrorMsg(pParse, "not a writable directory");
  80538. goto pragma_out;
  80539. }
  80540. }
  80541. if( SQLITE_TEMP_STORE==0
  80542. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  80543. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  80544. ){
  80545. invalidateTempStorage(pParse);
  80546. }
  80547. sqlite3_free(sqlite3_temp_directory);
  80548. if( zRight[0] ){
  80549. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  80550. }else{
  80551. sqlite3_temp_directory = 0;
  80552. }
  80553. #endif /* SQLITE_OMIT_WSD */
  80554. }
  80555. break;
  80556. }
  80557. #if SQLITE_OS_WIN
  80558. /*
  80559. ** PRAGMA data_store_directory
  80560. ** PRAGMA data_store_directory = ""|"directory_name"
  80561. **
  80562. ** Return or set the local value of the data_store_directory flag. Changing
  80563. ** the value sets a specific directory to be used for database files that
  80564. ** were specified with a relative pathname. Setting to a null string reverts
  80565. ** to the default database directory, which for database files specified with
  80566. ** a relative path will probably be based on the current directory for the
  80567. ** process. Database file specified with an absolute path are not impacted
  80568. ** by this setting, regardless of its value.
  80569. **
  80570. */
  80571. case PragTyp_DATA_STORE_DIRECTORY: {
  80572. if( !zRight ){
  80573. if( sqlite3_data_directory ){
  80574. sqlite3VdbeSetNumCols(v, 1);
  80575. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80576. "data_store_directory", SQLITE_STATIC);
  80577. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  80578. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80579. }
  80580. }else{
  80581. #ifndef SQLITE_OMIT_WSD
  80582. if( zRight[0] ){
  80583. int res;
  80584. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  80585. if( rc!=SQLITE_OK || res==0 ){
  80586. sqlite3ErrorMsg(pParse, "not a writable directory");
  80587. goto pragma_out;
  80588. }
  80589. }
  80590. sqlite3_free(sqlite3_data_directory);
  80591. if( zRight[0] ){
  80592. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  80593. }else{
  80594. sqlite3_data_directory = 0;
  80595. }
  80596. #endif /* SQLITE_OMIT_WSD */
  80597. }
  80598. break;
  80599. }
  80600. #endif
  80601. #if SQLITE_ENABLE_LOCKING_STYLE
  80602. /*
  80603. ** PRAGMA [database.]lock_proxy_file
  80604. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  80605. **
  80606. ** Return or set the value of the lock_proxy_file flag. Changing
  80607. ** the value sets a specific file to be used for database access locks.
  80608. **
  80609. */
  80610. case PragTyp_LOCK_PROXY_FILE: {
  80611. if( !zRight ){
  80612. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80613. char *proxy_file_path = NULL;
  80614. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  80615. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  80616. &proxy_file_path);
  80617. if( proxy_file_path ){
  80618. sqlite3VdbeSetNumCols(v, 1);
  80619. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  80620. "lock_proxy_file", SQLITE_STATIC);
  80621. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  80622. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  80623. }
  80624. }else{
  80625. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  80626. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  80627. int res;
  80628. if( zRight[0] ){
  80629. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  80630. zRight);
  80631. } else {
  80632. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  80633. NULL);
  80634. }
  80635. if( res!=SQLITE_OK ){
  80636. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  80637. goto pragma_out;
  80638. }
  80639. }
  80640. break;
  80641. }
  80642. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  80643. /*
  80644. ** PRAGMA [database.]synchronous
  80645. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  80646. **
  80647. ** Return or set the local value of the synchronous flag. Changing
  80648. ** the local value does not make changes to the disk file and the
  80649. ** default value will be restored the next time the database is
  80650. ** opened.
  80651. */
  80652. case PragTyp_SYNCHRONOUS: {
  80653. if( !zRight ){
  80654. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  80655. }else{
  80656. if( !db->autoCommit ){
  80657. sqlite3ErrorMsg(pParse,
  80658. "Safety level may not be changed inside a transaction");
  80659. }else{
  80660. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  80661. setAllPagerFlags(db);
  80662. }
  80663. }
  80664. break;
  80665. }
  80666. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  80667. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  80668. case PragTyp_FLAG: {
  80669. if( zRight==0 ){
  80670. returnSingleInt(pParse, aPragmaNames[mid].zName,
  80671. (db->flags & aPragmaNames[mid].iArg)!=0 );
  80672. }else{
  80673. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  80674. if( db->autoCommit==0 ){
  80675. /* Foreign key support may not be enabled or disabled while not
  80676. ** in auto-commit mode. */
  80677. mask &= ~(SQLITE_ForeignKeys);
  80678. }
  80679. if( sqlite3GetBoolean(zRight, 0) ){
  80680. db->flags |= mask;
  80681. }else{
  80682. db->flags &= ~mask;
  80683. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  80684. }
  80685. /* Many of the flag-pragmas modify the code generated by the SQL
  80686. ** compiler (eg. count_changes). So add an opcode to expire all
  80687. ** compiled SQL statements after modifying a pragma value.
  80688. */
  80689. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  80690. setAllPagerFlags(db);
  80691. }
  80692. break;
  80693. }
  80694. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  80695. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  80696. /*
  80697. ** PRAGMA table_info(<table>)
  80698. **
  80699. ** Return a single row for each column of the named table. The columns of
  80700. ** the returned data set are:
  80701. **
  80702. ** cid: Column id (numbered from left to right, starting at 0)
  80703. ** name: Column name
  80704. ** type: Column declaration type.
  80705. ** notnull: True if 'NOT NULL' is part of column declaration
  80706. ** dflt_value: The default value for the column, if any.
  80707. */
  80708. case PragTyp_TABLE_INFO: if( zRight ){
  80709. Table *pTab;
  80710. pTab = sqlite3FindTable(db, zRight, zDb);
  80711. if( pTab ){
  80712. int i, k;
  80713. int nHidden = 0;
  80714. Column *pCol;
  80715. Index *pPk;
  80716. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  80717. sqlite3VdbeSetNumCols(v, 6);
  80718. pParse->nMem = 6;
  80719. sqlite3CodeVerifySchema(pParse, iDb);
  80720. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  80721. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80722. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  80723. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  80724. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  80725. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  80726. sqlite3ViewGetColumnNames(pParse, pTab);
  80727. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  80728. if( IsHiddenColumn(pCol) ){
  80729. nHidden++;
  80730. continue;
  80731. }
  80732. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  80733. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  80734. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  80735. pCol->zType ? pCol->zType : "", 0);
  80736. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  80737. if( pCol->zDflt ){
  80738. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  80739. }else{
  80740. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  80741. }
  80742. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  80743. k = 0;
  80744. }else if( pPk==0 ){
  80745. k = 1;
  80746. }else{
  80747. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  80748. }
  80749. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  80750. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  80751. }
  80752. }
  80753. }
  80754. break;
  80755. case PragTyp_STATS: {
  80756. Index *pIdx;
  80757. HashElem *i;
  80758. v = sqlite3GetVdbe(pParse);
  80759. sqlite3VdbeSetNumCols(v, 4);
  80760. pParse->nMem = 4;
  80761. sqlite3CodeVerifySchema(pParse, iDb);
  80762. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  80763. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  80764. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  80765. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  80766. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  80767. Table *pTab = sqliteHashData(i);
  80768. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  80769. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  80770. sqlite3VdbeAddOp2(v, OP_Integer,
  80771. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  80772. sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
  80773. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  80774. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80775. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  80776. sqlite3VdbeAddOp2(v, OP_Integer,
  80777. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  80778. sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
  80779. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  80780. }
  80781. }
  80782. }
  80783. break;
  80784. case PragTyp_INDEX_INFO: if( zRight ){
  80785. Index *pIdx;
  80786. Table *pTab;
  80787. pIdx = sqlite3FindIndex(db, zRight, zDb);
  80788. if( pIdx ){
  80789. int i;
  80790. pTab = pIdx->pTable;
  80791. sqlite3VdbeSetNumCols(v, 3);
  80792. pParse->nMem = 3;
  80793. sqlite3CodeVerifySchema(pParse, iDb);
  80794. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  80795. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  80796. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  80797. for(i=0; i<pIdx->nColumn; i++){
  80798. int cnum = pIdx->aiColumn[i];
  80799. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80800. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  80801. assert( pTab->nCol>cnum );
  80802. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  80803. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80804. }
  80805. }
  80806. }
  80807. break;
  80808. case PragTyp_INDEX_LIST: if( zRight ){
  80809. Index *pIdx;
  80810. Table *pTab;
  80811. int i;
  80812. pTab = sqlite3FindTable(db, zRight, zDb);
  80813. if( pTab ){
  80814. v = sqlite3GetVdbe(pParse);
  80815. sqlite3VdbeSetNumCols(v, 3);
  80816. pParse->nMem = 3;
  80817. sqlite3CodeVerifySchema(pParse, iDb);
  80818. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80819. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80820. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  80821. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  80822. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80823. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  80824. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  80825. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80826. }
  80827. }
  80828. }
  80829. break;
  80830. case PragTyp_DATABASE_LIST: {
  80831. int i;
  80832. sqlite3VdbeSetNumCols(v, 3);
  80833. pParse->nMem = 3;
  80834. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80835. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80836. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  80837. for(i=0; i<db->nDb; i++){
  80838. if( db->aDb[i].pBt==0 ) continue;
  80839. assert( db->aDb[i].zName!=0 );
  80840. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80841. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  80842. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  80843. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  80844. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  80845. }
  80846. }
  80847. break;
  80848. case PragTyp_COLLATION_LIST: {
  80849. int i = 0;
  80850. HashElem *p;
  80851. sqlite3VdbeSetNumCols(v, 2);
  80852. pParse->nMem = 2;
  80853. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  80854. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  80855. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  80856. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  80857. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  80858. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  80859. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  80860. }
  80861. }
  80862. break;
  80863. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  80864. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80865. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  80866. FKey *pFK;
  80867. Table *pTab;
  80868. pTab = sqlite3FindTable(db, zRight, zDb);
  80869. if( pTab ){
  80870. v = sqlite3GetVdbe(pParse);
  80871. pFK = pTab->pFKey;
  80872. if( pFK ){
  80873. int i = 0;
  80874. sqlite3VdbeSetNumCols(v, 8);
  80875. pParse->nMem = 8;
  80876. sqlite3CodeVerifySchema(pParse, iDb);
  80877. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  80878. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  80879. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  80880. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  80881. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  80882. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  80883. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  80884. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  80885. while(pFK){
  80886. int j;
  80887. for(j=0; j<pFK->nCol; j++){
  80888. char *zCol = pFK->aCol[j].zCol;
  80889. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  80890. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  80891. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  80892. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  80893. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  80894. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  80895. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  80896. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  80897. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  80898. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  80899. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  80900. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  80901. }
  80902. ++i;
  80903. pFK = pFK->pNextFrom;
  80904. }
  80905. }
  80906. }
  80907. }
  80908. break;
  80909. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  80910. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80911. #ifndef SQLITE_OMIT_TRIGGER
  80912. case PragTyp_FOREIGN_KEY_CHECK: {
  80913. FKey *pFK; /* A foreign key constraint */
  80914. Table *pTab; /* Child table contain "REFERENCES" keyword */
  80915. Table *pParent; /* Parent table that child points to */
  80916. Index *pIdx; /* Index in the parent table */
  80917. int i; /* Loop counter: Foreign key number for pTab */
  80918. int j; /* Loop counter: Field of the foreign key */
  80919. HashElem *k; /* Loop counter: Next table in schema */
  80920. int x; /* result variable */
  80921. int regResult; /* 3 registers to hold a result row */
  80922. int regKey; /* Register to hold key for checking the FK */
  80923. int regRow; /* Registers to hold a row from pTab */
  80924. int addrTop; /* Top of a loop checking foreign keys */
  80925. int addrOk; /* Jump here if the key is OK */
  80926. int *aiCols; /* child to parent column mapping */
  80927. regResult = pParse->nMem+1;
  80928. pParse->nMem += 4;
  80929. regKey = ++pParse->nMem;
  80930. regRow = ++pParse->nMem;
  80931. v = sqlite3GetVdbe(pParse);
  80932. sqlite3VdbeSetNumCols(v, 4);
  80933. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  80934. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  80935. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  80936. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  80937. sqlite3CodeVerifySchema(pParse, iDb);
  80938. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  80939. while( k ){
  80940. if( zRight ){
  80941. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  80942. k = 0;
  80943. }else{
  80944. pTab = (Table*)sqliteHashData(k);
  80945. k = sqliteHashNext(k);
  80946. }
  80947. if( pTab==0 || pTab->pFKey==0 ) continue;
  80948. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  80949. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  80950. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  80951. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  80952. P4_TRANSIENT);
  80953. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  80954. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  80955. if( pParent==0 ) continue;
  80956. pIdx = 0;
  80957. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  80958. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  80959. if( x==0 ){
  80960. if( pIdx==0 ){
  80961. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  80962. }else{
  80963. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  80964. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  80965. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  80966. }
  80967. }else{
  80968. k = 0;
  80969. break;
  80970. }
  80971. }
  80972. assert( pParse->nErr>0 || pFK==0 );
  80973. if( pFK ) break;
  80974. if( pParse->nTab<i ) pParse->nTab = i;
  80975. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  80976. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  80977. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  80978. pIdx = 0;
  80979. aiCols = 0;
  80980. if( pParent ){
  80981. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  80982. assert( x==0 );
  80983. }
  80984. addrOk = sqlite3VdbeMakeLabel(v);
  80985. if( pParent && pIdx==0 ){
  80986. int iKey = pFK->aCol[0].iFrom;
  80987. assert( iKey>=0 && iKey<pTab->nCol );
  80988. if( iKey!=pTab->iPKey ){
  80989. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  80990. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  80991. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  80992. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  80993. sqlite3VdbeCurrentAddr(v)+3);
  80994. }else{
  80995. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  80996. }
  80997. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  80998. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  80999. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  81000. }else{
  81001. for(j=0; j<pFK->nCol; j++){
  81002. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  81003. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  81004. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  81005. }
  81006. if( pParent ){
  81007. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  81008. sqlite3VdbeChangeP4(v, -1,
  81009. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  81010. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  81011. }
  81012. }
  81013. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  81014. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  81015. pFK->zTo, P4_TRANSIENT);
  81016. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  81017. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  81018. sqlite3VdbeResolveLabel(v, addrOk);
  81019. sqlite3DbFree(db, aiCols);
  81020. }
  81021. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  81022. sqlite3VdbeJumpHere(v, addrTop);
  81023. }
  81024. }
  81025. break;
  81026. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  81027. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  81028. #ifndef NDEBUG
  81029. case PragTyp_PARSER_TRACE: {
  81030. if( zRight ){
  81031. if( sqlite3GetBoolean(zRight, 0) ){
  81032. sqlite3ParserTrace(stderr, "parser: ");
  81033. }else{
  81034. sqlite3ParserTrace(0, 0);
  81035. }
  81036. }
  81037. }
  81038. break;
  81039. #endif
  81040. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  81041. ** used will be case sensitive or not depending on the RHS.
  81042. */
  81043. case PragTyp_CASE_SENSITIVE_LIKE: {
  81044. if( zRight ){
  81045. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  81046. }
  81047. }
  81048. break;
  81049. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  81050. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  81051. #endif
  81052. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  81053. /* Pragma "quick_check" is reduced version of
  81054. ** integrity_check designed to detect most database corruption
  81055. ** without most of the overhead of a full integrity-check.
  81056. */
  81057. case PragTyp_INTEGRITY_CHECK: {
  81058. int i, j, addr, mxErr;
  81059. /* Code that appears at the end of the integrity check. If no error
  81060. ** messages have been generated, output OK. Otherwise output the
  81061. ** error message
  81062. */
  81063. static const VdbeOpList endCode[] = {
  81064. { OP_AddImm, 1, 0, 0}, /* 0 */
  81065. { OP_IfNeg, 1, 0, 0}, /* 1 */
  81066. { OP_String8, 0, 3, 0}, /* 2 */
  81067. { OP_ResultRow, 3, 1, 0},
  81068. };
  81069. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  81070. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  81071. ** then iDb is set to the index of the database identified by <db>.
  81072. ** In this case, the integrity of database iDb only is verified by
  81073. ** the VDBE created below.
  81074. **
  81075. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  81076. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  81077. ** to -1 here, to indicate that the VDBE should verify the integrity
  81078. ** of all attached databases. */
  81079. assert( iDb>=0 );
  81080. assert( iDb==0 || pId2->z );
  81081. if( pId2->z==0 ) iDb = -1;
  81082. /* Initialize the VDBE program */
  81083. pParse->nMem = 6;
  81084. sqlite3VdbeSetNumCols(v, 1);
  81085. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  81086. /* Set the maximum error count */
  81087. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  81088. if( zRight ){
  81089. sqlite3GetInt32(zRight, &mxErr);
  81090. if( mxErr<=0 ){
  81091. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  81092. }
  81093. }
  81094. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  81095. /* Do an integrity check on each database file */
  81096. for(i=0; i<db->nDb; i++){
  81097. HashElem *x;
  81098. Hash *pTbls;
  81099. int cnt = 0;
  81100. if( OMIT_TEMPDB && i==1 ) continue;
  81101. if( iDb>=0 && i!=iDb ) continue;
  81102. sqlite3CodeVerifySchema(pParse, i);
  81103. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  81104. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81105. sqlite3VdbeJumpHere(v, addr);
  81106. /* Do an integrity check of the B-Tree
  81107. **
  81108. ** Begin by filling registers 2, 3, ... with the root pages numbers
  81109. ** for all tables and indices in the database.
  81110. */
  81111. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  81112. pTbls = &db->aDb[i].pSchema->tblHash;
  81113. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  81114. Table *pTab = sqliteHashData(x);
  81115. Index *pIdx;
  81116. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  81117. cnt++;
  81118. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81119. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  81120. cnt++;
  81121. }
  81122. }
  81123. /* Make sure sufficient number of registers have been allocated */
  81124. pParse->nMem = MAX( pParse->nMem, cnt+7 );
  81125. /* Do the b-tree integrity checks */
  81126. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  81127. sqlite3VdbeChangeP5(v, (u8)i);
  81128. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  81129. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  81130. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  81131. P4_DYNAMIC);
  81132. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  81133. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  81134. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  81135. sqlite3VdbeJumpHere(v, addr);
  81136. /* Make sure all the indices are constructed correctly.
  81137. */
  81138. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  81139. Table *pTab = sqliteHashData(x);
  81140. Index *pIdx;
  81141. int loopTop;
  81142. if( pTab->pIndex==0 ) continue;
  81143. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  81144. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81145. sqlite3VdbeJumpHere(v, addr);
  81146. sqlite3ExprCacheClear(pParse);
  81147. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  81148. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81149. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
  81150. }
  81151. pParse->nMem = MAX(pParse->nMem, 7+j);
  81152. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  81153. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81154. int jmp2, jmp3;
  81155. int r1;
  81156. static const VdbeOpList idxErr[] = {
  81157. { OP_AddImm, 1, -1, 0},
  81158. { OP_String8, 0, 3, 0}, /* 1 */
  81159. { OP_Rowid, 1, 4, 0},
  81160. { OP_String8, 0, 5, 0}, /* 3 */
  81161. { OP_String8, 0, 6, 0}, /* 4 */
  81162. { OP_Concat, 4, 3, 3},
  81163. { OP_Concat, 5, 3, 3},
  81164. { OP_Concat, 6, 3, 3},
  81165. { OP_ResultRow, 3, 1, 0},
  81166. { OP_IfPos, 1, 0, 0}, /* 9 */
  81167. { OP_Halt, 0, 0, 0},
  81168. };
  81169. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
  81170. sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
  81171. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  81172. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  81173. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  81174. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  81175. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  81176. sqlite3VdbeJumpHere(v, addr+9);
  81177. sqlite3VdbeJumpHere(v, jmp2);
  81178. sqlite3VdbeResolveLabel(v, jmp3);
  81179. }
  81180. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
  81181. sqlite3VdbeJumpHere(v, loopTop-1);
  81182. #ifndef SQLITE_OMIT_BTREECOUNT
  81183. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  81184. "wrong # of entries in index ", P4_STATIC);
  81185. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  81186. addr = sqlite3VdbeCurrentAddr(v);
  81187. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  81188. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  81189. sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
  81190. sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
  81191. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  81192. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  81193. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  81194. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  81195. }
  81196. #endif /* SQLITE_OMIT_BTREECOUNT */
  81197. }
  81198. }
  81199. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  81200. sqlite3VdbeChangeP2(v, addr, -mxErr);
  81201. sqlite3VdbeJumpHere(v, addr+1);
  81202. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  81203. }
  81204. break;
  81205. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  81206. #ifndef SQLITE_OMIT_UTF16
  81207. /*
  81208. ** PRAGMA encoding
  81209. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  81210. **
  81211. ** In its first form, this pragma returns the encoding of the main
  81212. ** database. If the database is not initialized, it is initialized now.
  81213. **
  81214. ** The second form of this pragma is a no-op if the main database file
  81215. ** has not already been initialized. In this case it sets the default
  81216. ** encoding that will be used for the main database file if a new file
  81217. ** is created. If an existing main database file is opened, then the
  81218. ** default text encoding for the existing database is used.
  81219. **
  81220. ** In all cases new databases created using the ATTACH command are
  81221. ** created to use the same default text encoding as the main database. If
  81222. ** the main database has not been initialized and/or created when ATTACH
  81223. ** is executed, this is done before the ATTACH operation.
  81224. **
  81225. ** In the second form this pragma sets the text encoding to be used in
  81226. ** new database files created using this database handle. It is only
  81227. ** useful if invoked immediately after the main database i
  81228. */
  81229. case PragTyp_ENCODING: {
  81230. static const struct EncName {
  81231. char *zName;
  81232. u8 enc;
  81233. } encnames[] = {
  81234. { "UTF8", SQLITE_UTF8 },
  81235. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  81236. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  81237. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  81238. { "UTF16le", SQLITE_UTF16LE },
  81239. { "UTF16be", SQLITE_UTF16BE },
  81240. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  81241. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  81242. { 0, 0 }
  81243. };
  81244. const struct EncName *pEnc;
  81245. if( !zRight ){ /* "PRAGMA encoding" */
  81246. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  81247. sqlite3VdbeSetNumCols(v, 1);
  81248. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  81249. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  81250. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  81251. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  81252. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  81253. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  81254. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  81255. }else{ /* "PRAGMA encoding = XXX" */
  81256. /* Only change the value of sqlite.enc if the database handle is not
  81257. ** initialized. If the main database exists, the new sqlite.enc value
  81258. ** will be overwritten when the schema is next loaded. If it does not
  81259. ** already exists, it will be created to use the new encoding value.
  81260. */
  81261. if(
  81262. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  81263. DbHasProperty(db, 0, DB_Empty)
  81264. ){
  81265. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  81266. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  81267. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  81268. break;
  81269. }
  81270. }
  81271. if( !pEnc->zName ){
  81272. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  81273. }
  81274. }
  81275. }
  81276. }
  81277. break;
  81278. #endif /* SQLITE_OMIT_UTF16 */
  81279. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  81280. /*
  81281. ** PRAGMA [database.]schema_version
  81282. ** PRAGMA [database.]schema_version = <integer>
  81283. **
  81284. ** PRAGMA [database.]user_version
  81285. ** PRAGMA [database.]user_version = <integer>
  81286. **
  81287. ** PRAGMA [database.]freelist_count = <integer>
  81288. **
  81289. ** PRAGMA [database.]application_id
  81290. ** PRAGMA [database.]application_id = <integer>
  81291. **
  81292. ** The pragma's schema_version and user_version are used to set or get
  81293. ** the value of the schema-version and user-version, respectively. Both
  81294. ** the schema-version and the user-version are 32-bit signed integers
  81295. ** stored in the database header.
  81296. **
  81297. ** The schema-cookie is usually only manipulated internally by SQLite. It
  81298. ** is incremented by SQLite whenever the database schema is modified (by
  81299. ** creating or dropping a table or index). The schema version is used by
  81300. ** SQLite each time a query is executed to ensure that the internal cache
  81301. ** of the schema used when compiling the SQL query matches the schema of
  81302. ** the database against which the compiled query is actually executed.
  81303. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  81304. ** the schema-version is potentially dangerous and may lead to program
  81305. ** crashes or database corruption. Use with caution!
  81306. **
  81307. ** The user-version is not used internally by SQLite. It may be used by
  81308. ** applications for any purpose.
  81309. */
  81310. case PragTyp_HEADER_VALUE: {
  81311. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  81312. sqlite3VdbeUsesBtree(v, iDb);
  81313. switch( zLeft[0] ){
  81314. case 'a': case 'A':
  81315. iCookie = BTREE_APPLICATION_ID;
  81316. break;
  81317. case 'f': case 'F':
  81318. iCookie = BTREE_FREE_PAGE_COUNT;
  81319. break;
  81320. case 's': case 'S':
  81321. iCookie = BTREE_SCHEMA_VERSION;
  81322. break;
  81323. default:
  81324. iCookie = BTREE_USER_VERSION;
  81325. break;
  81326. }
  81327. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  81328. /* Write the specified cookie value */
  81329. static const VdbeOpList setCookie[] = {
  81330. { OP_Transaction, 0, 1, 0}, /* 0 */
  81331. { OP_Integer, 0, 1, 0}, /* 1 */
  81332. { OP_SetCookie, 0, 0, 1}, /* 2 */
  81333. };
  81334. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  81335. sqlite3VdbeChangeP1(v, addr, iDb);
  81336. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  81337. sqlite3VdbeChangeP1(v, addr+2, iDb);
  81338. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  81339. }else{
  81340. /* Read the specified cookie value */
  81341. static const VdbeOpList readCookie[] = {
  81342. { OP_Transaction, 0, 0, 0}, /* 0 */
  81343. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  81344. { OP_ResultRow, 1, 1, 0}
  81345. };
  81346. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  81347. sqlite3VdbeChangeP1(v, addr, iDb);
  81348. sqlite3VdbeChangeP1(v, addr+1, iDb);
  81349. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  81350. sqlite3VdbeSetNumCols(v, 1);
  81351. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  81352. }
  81353. }
  81354. break;
  81355. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  81356. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  81357. /*
  81358. ** PRAGMA compile_options
  81359. **
  81360. ** Return the names of all compile-time options used in this build,
  81361. ** one option per row.
  81362. */
  81363. case PragTyp_COMPILE_OPTIONS: {
  81364. int i = 0;
  81365. const char *zOpt;
  81366. sqlite3VdbeSetNumCols(v, 1);
  81367. pParse->nMem = 1;
  81368. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  81369. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  81370. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  81371. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  81372. }
  81373. }
  81374. break;
  81375. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  81376. #ifndef SQLITE_OMIT_WAL
  81377. /*
  81378. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  81379. **
  81380. ** Checkpoint the database.
  81381. */
  81382. case PragTyp_WAL_CHECKPOINT: {
  81383. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  81384. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  81385. if( zRight ){
  81386. if( sqlite3StrICmp(zRight, "full")==0 ){
  81387. eMode = SQLITE_CHECKPOINT_FULL;
  81388. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  81389. eMode = SQLITE_CHECKPOINT_RESTART;
  81390. }
  81391. }
  81392. sqlite3VdbeSetNumCols(v, 3);
  81393. pParse->nMem = 3;
  81394. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  81395. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  81396. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  81397. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  81398. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  81399. }
  81400. break;
  81401. /*
  81402. ** PRAGMA wal_autocheckpoint
  81403. ** PRAGMA wal_autocheckpoint = N
  81404. **
  81405. ** Configure a database connection to automatically checkpoint a database
  81406. ** after accumulating N frames in the log. Or query for the current value
  81407. ** of N.
  81408. */
  81409. case PragTyp_WAL_AUTOCHECKPOINT: {
  81410. if( zRight ){
  81411. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  81412. }
  81413. returnSingleInt(pParse, "wal_autocheckpoint",
  81414. db->xWalCallback==sqlite3WalDefaultHook ?
  81415. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  81416. }
  81417. break;
  81418. #endif
  81419. /*
  81420. ** PRAGMA shrink_memory
  81421. **
  81422. ** This pragma attempts to free as much memory as possible from the
  81423. ** current database connection.
  81424. */
  81425. case PragTyp_SHRINK_MEMORY: {
  81426. sqlite3_db_release_memory(db);
  81427. break;
  81428. }
  81429. /*
  81430. ** PRAGMA busy_timeout
  81431. ** PRAGMA busy_timeout = N
  81432. **
  81433. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  81434. ** if one is set. If no busy handler or a different busy handler is set
  81435. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  81436. ** disables the timeout.
  81437. */
  81438. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  81439. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  81440. if( zRight ){
  81441. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  81442. }
  81443. returnSingleInt(pParse, "timeout", db->busyTimeout);
  81444. break;
  81445. }
  81446. /*
  81447. ** PRAGMA soft_heap_limit
  81448. ** PRAGMA soft_heap_limit = N
  81449. **
  81450. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  81451. ** use -1.
  81452. */
  81453. case PragTyp_SOFT_HEAP_LIMIT: {
  81454. sqlite3_int64 N;
  81455. if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
  81456. sqlite3_soft_heap_limit64(N);
  81457. }
  81458. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  81459. break;
  81460. }
  81461. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  81462. /*
  81463. ** Report the current state of file logs for all databases
  81464. */
  81465. case PragTyp_LOCK_STATUS: {
  81466. static const char *const azLockName[] = {
  81467. "unlocked", "shared", "reserved", "pending", "exclusive"
  81468. };
  81469. int i;
  81470. sqlite3VdbeSetNumCols(v, 2);
  81471. pParse->nMem = 2;
  81472. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  81473. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  81474. for(i=0; i<db->nDb; i++){
  81475. Btree *pBt;
  81476. const char *zState = "unknown";
  81477. int j;
  81478. if( db->aDb[i].zName==0 ) continue;
  81479. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  81480. pBt = db->aDb[i].pBt;
  81481. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  81482. zState = "closed";
  81483. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  81484. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  81485. zState = azLockName[j];
  81486. }
  81487. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  81488. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  81489. }
  81490. break;
  81491. }
  81492. #endif
  81493. #ifdef SQLITE_HAS_CODEC
  81494. case PragTyp_KEY: {
  81495. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  81496. break;
  81497. }
  81498. case PragTyp_REKEY: {
  81499. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  81500. break;
  81501. }
  81502. case PragTyp_HEXKEY: {
  81503. if( zRight ){
  81504. u8 iByte;
  81505. int i;
  81506. char zKey[40];
  81507. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  81508. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  81509. if( (i&1)!=0 ) zKey[i/2] = iByte;
  81510. }
  81511. if( (zLeft[3] & 0xf)==0xb ){
  81512. sqlite3_key_v2(db, zDb, zKey, i/2);
  81513. }else{
  81514. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  81515. }
  81516. }
  81517. break;
  81518. }
  81519. #endif
  81520. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  81521. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  81522. #ifdef SQLITE_HAS_CODEC
  81523. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  81524. sqlite3_activate_see(&zRight[4]);
  81525. }
  81526. #endif
  81527. #ifdef SQLITE_ENABLE_CEROD
  81528. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  81529. sqlite3_activate_cerod(&zRight[6]);
  81530. }
  81531. #endif
  81532. }
  81533. break;
  81534. #endif
  81535. } /* End of the PRAGMA switch */
  81536. pragma_out:
  81537. sqlite3DbFree(db, zLeft);
  81538. sqlite3DbFree(db, zRight);
  81539. }
  81540. #endif /* SQLITE_OMIT_PRAGMA */
  81541. /************** End of pragma.c **********************************************/
  81542. /************** Begin file prepare.c *****************************************/
  81543. /*
  81544. ** 2005 May 25
  81545. **
  81546. ** The author disclaims copyright to this source code. In place of
  81547. ** a legal notice, here is a blessing:
  81548. **
  81549. ** May you do good and not evil.
  81550. ** May you find forgiveness for yourself and forgive others.
  81551. ** May you share freely, never taking more than you give.
  81552. **
  81553. *************************************************************************
  81554. ** This file contains the implementation of the sqlite3_prepare()
  81555. ** interface, and routines that contribute to loading the database schema
  81556. ** from disk.
  81557. */
  81558. /*
  81559. ** Fill the InitData structure with an error message that indicates
  81560. ** that the database is corrupt.
  81561. */
  81562. static void corruptSchema(
  81563. InitData *pData, /* Initialization context */
  81564. const char *zObj, /* Object being parsed at the point of error */
  81565. const char *zExtra /* Error information */
  81566. ){
  81567. sqlite3 *db = pData->db;
  81568. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  81569. if( zObj==0 ) zObj = "?";
  81570. sqlite3SetString(pData->pzErrMsg, db,
  81571. "malformed database schema (%s)", zObj);
  81572. if( zExtra ){
  81573. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  81574. "%s - %s", *pData->pzErrMsg, zExtra);
  81575. }
  81576. }
  81577. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  81578. }
  81579. /*
  81580. ** This is the callback routine for the code that initializes the
  81581. ** database. See sqlite3Init() below for additional information.
  81582. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  81583. **
  81584. ** Each callback contains the following information:
  81585. **
  81586. ** argv[0] = name of thing being created
  81587. ** argv[1] = root page number for table or index. 0 for trigger or view.
  81588. ** argv[2] = SQL text for the CREATE statement.
  81589. **
  81590. */
  81591. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  81592. InitData *pData = (InitData*)pInit;
  81593. sqlite3 *db = pData->db;
  81594. int iDb = pData->iDb;
  81595. assert( argc==3 );
  81596. UNUSED_PARAMETER2(NotUsed, argc);
  81597. assert( sqlite3_mutex_held(db->mutex) );
  81598. DbClearProperty(db, iDb, DB_Empty);
  81599. if( db->mallocFailed ){
  81600. corruptSchema(pData, argv[0], 0);
  81601. return 1;
  81602. }
  81603. assert( iDb>=0 && iDb<db->nDb );
  81604. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  81605. if( argv[1]==0 ){
  81606. corruptSchema(pData, argv[0], 0);
  81607. }else if( argv[2] && argv[2][0] ){
  81608. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  81609. ** But because db->init.busy is set to 1, no VDBE code is generated
  81610. ** or executed. All the parser does is build the internal data
  81611. ** structures that describe the table, index, or view.
  81612. */
  81613. int rc;
  81614. sqlite3_stmt *pStmt;
  81615. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  81616. assert( db->init.busy );
  81617. db->init.iDb = iDb;
  81618. db->init.newTnum = sqlite3Atoi(argv[1]);
  81619. db->init.orphanTrigger = 0;
  81620. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  81621. rc = db->errCode;
  81622. assert( (rc&0xFF)==(rcp&0xFF) );
  81623. db->init.iDb = 0;
  81624. if( SQLITE_OK!=rc ){
  81625. if( db->init.orphanTrigger ){
  81626. assert( iDb==1 );
  81627. }else{
  81628. pData->rc = rc;
  81629. if( rc==SQLITE_NOMEM ){
  81630. db->mallocFailed = 1;
  81631. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  81632. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  81633. }
  81634. }
  81635. }
  81636. sqlite3_finalize(pStmt);
  81637. }else if( argv[0]==0 ){
  81638. corruptSchema(pData, 0, 0);
  81639. }else{
  81640. /* If the SQL column is blank it means this is an index that
  81641. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  81642. ** constraint for a CREATE TABLE. The index should have already
  81643. ** been created when we processed the CREATE TABLE. All we have
  81644. ** to do here is record the root page number for that index.
  81645. */
  81646. Index *pIndex;
  81647. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  81648. if( pIndex==0 ){
  81649. /* This can occur if there exists an index on a TEMP table which
  81650. ** has the same name as another index on a permanent index. Since
  81651. ** the permanent table is hidden by the TEMP table, we can also
  81652. ** safely ignore the index on the permanent table.
  81653. */
  81654. /* Do Nothing */;
  81655. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  81656. corruptSchema(pData, argv[0], "invalid rootpage");
  81657. }
  81658. }
  81659. return 0;
  81660. }
  81661. /*
  81662. ** Attempt to read the database schema and initialize internal
  81663. ** data structures for a single database file. The index of the
  81664. ** database file is given by iDb. iDb==0 is used for the main
  81665. ** database. iDb==1 should never be used. iDb>=2 is used for
  81666. ** auxiliary databases. Return one of the SQLITE_ error codes to
  81667. ** indicate success or failure.
  81668. */
  81669. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  81670. int rc;
  81671. int i;
  81672. #ifndef SQLITE_OMIT_DEPRECATED
  81673. int size;
  81674. #endif
  81675. Table *pTab;
  81676. Db *pDb;
  81677. char const *azArg[4];
  81678. int meta[5];
  81679. InitData initData;
  81680. char const *zMasterSchema;
  81681. char const *zMasterName;
  81682. int openedTransaction = 0;
  81683. /*
  81684. ** The master database table has a structure like this
  81685. */
  81686. static const char master_schema[] =
  81687. "CREATE TABLE sqlite_master(\n"
  81688. " type text,\n"
  81689. " name text,\n"
  81690. " tbl_name text,\n"
  81691. " rootpage integer,\n"
  81692. " sql text\n"
  81693. ")"
  81694. ;
  81695. #ifndef SQLITE_OMIT_TEMPDB
  81696. static const char temp_master_schema[] =
  81697. "CREATE TEMP TABLE sqlite_temp_master(\n"
  81698. " type text,\n"
  81699. " name text,\n"
  81700. " tbl_name text,\n"
  81701. " rootpage integer,\n"
  81702. " sql text\n"
  81703. ")"
  81704. ;
  81705. #else
  81706. #define temp_master_schema 0
  81707. #endif
  81708. assert( iDb>=0 && iDb<db->nDb );
  81709. assert( db->aDb[iDb].pSchema );
  81710. assert( sqlite3_mutex_held(db->mutex) );
  81711. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  81712. /* zMasterSchema and zInitScript are set to point at the master schema
  81713. ** and initialisation script appropriate for the database being
  81714. ** initialized. zMasterName is the name of the master table.
  81715. */
  81716. if( !OMIT_TEMPDB && iDb==1 ){
  81717. zMasterSchema = temp_master_schema;
  81718. }else{
  81719. zMasterSchema = master_schema;
  81720. }
  81721. zMasterName = SCHEMA_TABLE(iDb);
  81722. /* Construct the schema tables. */
  81723. azArg[0] = zMasterName;
  81724. azArg[1] = "1";
  81725. azArg[2] = zMasterSchema;
  81726. azArg[3] = 0;
  81727. initData.db = db;
  81728. initData.iDb = iDb;
  81729. initData.rc = SQLITE_OK;
  81730. initData.pzErrMsg = pzErrMsg;
  81731. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  81732. if( initData.rc ){
  81733. rc = initData.rc;
  81734. goto error_out;
  81735. }
  81736. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  81737. if( ALWAYS(pTab) ){
  81738. pTab->tabFlags |= TF_Readonly;
  81739. }
  81740. /* Create a cursor to hold the database open
  81741. */
  81742. pDb = &db->aDb[iDb];
  81743. if( pDb->pBt==0 ){
  81744. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  81745. DbSetProperty(db, 1, DB_SchemaLoaded);
  81746. }
  81747. return SQLITE_OK;
  81748. }
  81749. /* If there is not already a read-only (or read-write) transaction opened
  81750. ** on the b-tree database, open one now. If a transaction is opened, it
  81751. ** will be closed before this function returns. */
  81752. sqlite3BtreeEnter(pDb->pBt);
  81753. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  81754. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  81755. if( rc!=SQLITE_OK ){
  81756. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  81757. goto initone_error_out;
  81758. }
  81759. openedTransaction = 1;
  81760. }
  81761. /* Get the database meta information.
  81762. **
  81763. ** Meta values are as follows:
  81764. ** meta[0] Schema cookie. Changes with each schema change.
  81765. ** meta[1] File format of schema layer.
  81766. ** meta[2] Size of the page cache.
  81767. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  81768. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  81769. ** meta[5] User version
  81770. ** meta[6] Incremental vacuum mode
  81771. ** meta[7] unused
  81772. ** meta[8] unused
  81773. ** meta[9] unused
  81774. **
  81775. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  81776. ** the possible values of meta[4].
  81777. */
  81778. for(i=0; i<ArraySize(meta); i++){
  81779. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  81780. }
  81781. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  81782. /* If opening a non-empty database, check the text encoding. For the
  81783. ** main database, set sqlite3.enc to the encoding of the main database.
  81784. ** For an attached db, it is an error if the encoding is not the same
  81785. ** as sqlite3.enc.
  81786. */
  81787. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  81788. if( iDb==0 ){
  81789. #ifndef SQLITE_OMIT_UTF16
  81790. u8 encoding;
  81791. /* If opening the main database, set ENC(db). */
  81792. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  81793. if( encoding==0 ) encoding = SQLITE_UTF8;
  81794. ENC(db) = encoding;
  81795. #else
  81796. ENC(db) = SQLITE_UTF8;
  81797. #endif
  81798. }else{
  81799. /* If opening an attached database, the encoding much match ENC(db) */
  81800. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  81801. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  81802. " text encoding as main database");
  81803. rc = SQLITE_ERROR;
  81804. goto initone_error_out;
  81805. }
  81806. }
  81807. }else{
  81808. DbSetProperty(db, iDb, DB_Empty);
  81809. }
  81810. pDb->pSchema->enc = ENC(db);
  81811. if( pDb->pSchema->cache_size==0 ){
  81812. #ifndef SQLITE_OMIT_DEPRECATED
  81813. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  81814. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  81815. pDb->pSchema->cache_size = size;
  81816. #else
  81817. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  81818. #endif
  81819. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  81820. }
  81821. /*
  81822. ** file_format==1 Version 3.0.0.
  81823. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  81824. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  81825. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  81826. */
  81827. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  81828. if( pDb->pSchema->file_format==0 ){
  81829. pDb->pSchema->file_format = 1;
  81830. }
  81831. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  81832. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  81833. rc = SQLITE_ERROR;
  81834. goto initone_error_out;
  81835. }
  81836. /* Ticket #2804: When we open a database in the newer file format,
  81837. ** clear the legacy_file_format pragma flag so that a VACUUM will
  81838. ** not downgrade the database and thus invalidate any descending
  81839. ** indices that the user might have created.
  81840. */
  81841. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  81842. db->flags &= ~SQLITE_LegacyFileFmt;
  81843. }
  81844. /* Read the schema information out of the schema tables
  81845. */
  81846. assert( db->init.busy );
  81847. {
  81848. char *zSql;
  81849. zSql = sqlite3MPrintf(db,
  81850. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  81851. db->aDb[iDb].zName, zMasterName);
  81852. #ifndef SQLITE_OMIT_AUTHORIZATION
  81853. {
  81854. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  81855. xAuth = db->xAuth;
  81856. db->xAuth = 0;
  81857. #endif
  81858. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  81859. #ifndef SQLITE_OMIT_AUTHORIZATION
  81860. db->xAuth = xAuth;
  81861. }
  81862. #endif
  81863. if( rc==SQLITE_OK ) rc = initData.rc;
  81864. sqlite3DbFree(db, zSql);
  81865. #ifndef SQLITE_OMIT_ANALYZE
  81866. if( rc==SQLITE_OK ){
  81867. sqlite3AnalysisLoad(db, iDb);
  81868. }
  81869. #endif
  81870. }
  81871. if( db->mallocFailed ){
  81872. rc = SQLITE_NOMEM;
  81873. sqlite3ResetAllSchemasOfConnection(db);
  81874. }
  81875. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  81876. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  81877. ** the schema loaded, even if errors occurred. In this situation the
  81878. ** current sqlite3_prepare() operation will fail, but the following one
  81879. ** will attempt to compile the supplied statement against whatever subset
  81880. ** of the schema was loaded before the error occurred. The primary
  81881. ** purpose of this is to allow access to the sqlite_master table
  81882. ** even when its contents have been corrupted.
  81883. */
  81884. DbSetProperty(db, iDb, DB_SchemaLoaded);
  81885. rc = SQLITE_OK;
  81886. }
  81887. /* Jump here for an error that occurs after successfully allocating
  81888. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  81889. ** before that point, jump to error_out.
  81890. */
  81891. initone_error_out:
  81892. if( openedTransaction ){
  81893. sqlite3BtreeCommit(pDb->pBt);
  81894. }
  81895. sqlite3BtreeLeave(pDb->pBt);
  81896. error_out:
  81897. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  81898. db->mallocFailed = 1;
  81899. }
  81900. return rc;
  81901. }
  81902. /*
  81903. ** Initialize all database files - the main database file, the file
  81904. ** used to store temporary tables, and any additional database files
  81905. ** created using ATTACH statements. Return a success code. If an
  81906. ** error occurs, write an error message into *pzErrMsg.
  81907. **
  81908. ** After a database is initialized, the DB_SchemaLoaded bit is set
  81909. ** bit is set in the flags field of the Db structure. If the database
  81910. ** file was of zero-length, then the DB_Empty flag is also set.
  81911. */
  81912. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  81913. int i, rc;
  81914. int commit_internal = !(db->flags&SQLITE_InternChanges);
  81915. assert( sqlite3_mutex_held(db->mutex) );
  81916. rc = SQLITE_OK;
  81917. db->init.busy = 1;
  81918. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  81919. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  81920. rc = sqlite3InitOne(db, i, pzErrMsg);
  81921. if( rc ){
  81922. sqlite3ResetOneSchema(db, i);
  81923. }
  81924. }
  81925. /* Once all the other databases have been initialized, load the schema
  81926. ** for the TEMP database. This is loaded last, as the TEMP database
  81927. ** schema may contain references to objects in other databases.
  81928. */
  81929. #ifndef SQLITE_OMIT_TEMPDB
  81930. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  81931. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  81932. rc = sqlite3InitOne(db, 1, pzErrMsg);
  81933. if( rc ){
  81934. sqlite3ResetOneSchema(db, 1);
  81935. }
  81936. }
  81937. #endif
  81938. db->init.busy = 0;
  81939. if( rc==SQLITE_OK && commit_internal ){
  81940. sqlite3CommitInternalChanges(db);
  81941. }
  81942. return rc;
  81943. }
  81944. /*
  81945. ** This routine is a no-op if the database schema is already initialized.
  81946. ** Otherwise, the schema is loaded. An error code is returned.
  81947. */
  81948. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  81949. int rc = SQLITE_OK;
  81950. sqlite3 *db = pParse->db;
  81951. assert( sqlite3_mutex_held(db->mutex) );
  81952. if( !db->init.busy ){
  81953. rc = sqlite3Init(db, &pParse->zErrMsg);
  81954. }
  81955. if( rc!=SQLITE_OK ){
  81956. pParse->rc = rc;
  81957. pParse->nErr++;
  81958. }
  81959. return rc;
  81960. }
  81961. /*
  81962. ** Check schema cookies in all databases. If any cookie is out
  81963. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  81964. ** make no changes to pParse->rc.
  81965. */
  81966. static void schemaIsValid(Parse *pParse){
  81967. sqlite3 *db = pParse->db;
  81968. int iDb;
  81969. int rc;
  81970. int cookie;
  81971. assert( pParse->checkSchema );
  81972. assert( sqlite3_mutex_held(db->mutex) );
  81973. for(iDb=0; iDb<db->nDb; iDb++){
  81974. int openedTransaction = 0; /* True if a transaction is opened */
  81975. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  81976. if( pBt==0 ) continue;
  81977. /* If there is not already a read-only (or read-write) transaction opened
  81978. ** on the b-tree database, open one now. If a transaction is opened, it
  81979. ** will be closed immediately after reading the meta-value. */
  81980. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  81981. rc = sqlite3BtreeBeginTrans(pBt, 0);
  81982. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  81983. db->mallocFailed = 1;
  81984. }
  81985. if( rc!=SQLITE_OK ) return;
  81986. openedTransaction = 1;
  81987. }
  81988. /* Read the schema cookie from the database. If it does not match the
  81989. ** value stored as part of the in-memory schema representation,
  81990. ** set Parse.rc to SQLITE_SCHEMA. */
  81991. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  81992. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81993. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  81994. sqlite3ResetOneSchema(db, iDb);
  81995. pParse->rc = SQLITE_SCHEMA;
  81996. }
  81997. /* Close the transaction, if one was opened. */
  81998. if( openedTransaction ){
  81999. sqlite3BtreeCommit(pBt);
  82000. }
  82001. }
  82002. }
  82003. /*
  82004. ** Convert a schema pointer into the iDb index that indicates
  82005. ** which database file in db->aDb[] the schema refers to.
  82006. **
  82007. ** If the same database is attached more than once, the first
  82008. ** attached database is returned.
  82009. */
  82010. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  82011. int i = -1000000;
  82012. /* If pSchema is NULL, then return -1000000. This happens when code in
  82013. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  82014. ** created by a sub-select). In this case the return value of this
  82015. ** function should never be used.
  82016. **
  82017. ** We return -1000000 instead of the more usual -1 simply because using
  82018. ** -1000000 as the incorrect index into db->aDb[] is much
  82019. ** more likely to cause a segfault than -1 (of course there are assert()
  82020. ** statements too, but it never hurts to play the odds).
  82021. */
  82022. assert( sqlite3_mutex_held(db->mutex) );
  82023. if( pSchema ){
  82024. for(i=0; ALWAYS(i<db->nDb); i++){
  82025. if( db->aDb[i].pSchema==pSchema ){
  82026. break;
  82027. }
  82028. }
  82029. assert( i>=0 && i<db->nDb );
  82030. }
  82031. return i;
  82032. }
  82033. /*
  82034. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  82035. */
  82036. static int sqlite3Prepare(
  82037. sqlite3 *db, /* Database handle. */
  82038. const char *zSql, /* UTF-8 encoded SQL statement. */
  82039. int nBytes, /* Length of zSql in bytes. */
  82040. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  82041. Vdbe *pReprepare, /* VM being reprepared */
  82042. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82043. const char **pzTail /* OUT: End of parsed string */
  82044. ){
  82045. Parse *pParse; /* Parsing context */
  82046. char *zErrMsg = 0; /* Error message */
  82047. int rc = SQLITE_OK; /* Result code */
  82048. int i; /* Loop counter */
  82049. /* Allocate the parsing context */
  82050. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  82051. if( pParse==0 ){
  82052. rc = SQLITE_NOMEM;
  82053. goto end_prepare;
  82054. }
  82055. pParse->pReprepare = pReprepare;
  82056. assert( ppStmt && *ppStmt==0 );
  82057. assert( !db->mallocFailed );
  82058. assert( sqlite3_mutex_held(db->mutex) );
  82059. /* Check to verify that it is possible to get a read lock on all
  82060. ** database schemas. The inability to get a read lock indicates that
  82061. ** some other database connection is holding a write-lock, which in
  82062. ** turn means that the other connection has made uncommitted changes
  82063. ** to the schema.
  82064. **
  82065. ** Were we to proceed and prepare the statement against the uncommitted
  82066. ** schema changes and if those schema changes are subsequently rolled
  82067. ** back and different changes are made in their place, then when this
  82068. ** prepared statement goes to run the schema cookie would fail to detect
  82069. ** the schema change. Disaster would follow.
  82070. **
  82071. ** This thread is currently holding mutexes on all Btrees (because
  82072. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  82073. ** is not possible for another thread to start a new schema change
  82074. ** while this routine is running. Hence, we do not need to hold
  82075. ** locks on the schema, we just need to make sure nobody else is
  82076. ** holding them.
  82077. **
  82078. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  82079. ** but it does *not* override schema lock detection, so this all still
  82080. ** works even if READ_UNCOMMITTED is set.
  82081. */
  82082. for(i=0; i<db->nDb; i++) {
  82083. Btree *pBt = db->aDb[i].pBt;
  82084. if( pBt ){
  82085. assert( sqlite3BtreeHoldsMutex(pBt) );
  82086. rc = sqlite3BtreeSchemaLocked(pBt);
  82087. if( rc ){
  82088. const char *zDb = db->aDb[i].zName;
  82089. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  82090. testcase( db->flags & SQLITE_ReadUncommitted );
  82091. goto end_prepare;
  82092. }
  82093. }
  82094. }
  82095. sqlite3VtabUnlockList(db);
  82096. pParse->db = db;
  82097. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  82098. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  82099. char *zSqlCopy;
  82100. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  82101. testcase( nBytes==mxLen );
  82102. testcase( nBytes==mxLen+1 );
  82103. if( nBytes>mxLen ){
  82104. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  82105. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  82106. goto end_prepare;
  82107. }
  82108. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  82109. if( zSqlCopy ){
  82110. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  82111. sqlite3DbFree(db, zSqlCopy);
  82112. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  82113. }else{
  82114. pParse->zTail = &zSql[nBytes];
  82115. }
  82116. }else{
  82117. sqlite3RunParser(pParse, zSql, &zErrMsg);
  82118. }
  82119. assert( 0==pParse->nQueryLoop );
  82120. if( db->mallocFailed ){
  82121. pParse->rc = SQLITE_NOMEM;
  82122. }
  82123. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  82124. if( pParse->checkSchema ){
  82125. schemaIsValid(pParse);
  82126. }
  82127. if( db->mallocFailed ){
  82128. pParse->rc = SQLITE_NOMEM;
  82129. }
  82130. if( pzTail ){
  82131. *pzTail = pParse->zTail;
  82132. }
  82133. rc = pParse->rc;
  82134. #ifndef SQLITE_OMIT_EXPLAIN
  82135. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  82136. static const char * const azColName[] = {
  82137. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  82138. "selectid", "order", "from", "detail"
  82139. };
  82140. int iFirst, mx;
  82141. if( pParse->explain==2 ){
  82142. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  82143. iFirst = 8;
  82144. mx = 12;
  82145. }else{
  82146. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  82147. iFirst = 0;
  82148. mx = 8;
  82149. }
  82150. for(i=iFirst; i<mx; i++){
  82151. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  82152. azColName[i], SQLITE_STATIC);
  82153. }
  82154. }
  82155. #endif
  82156. if( db->init.busy==0 ){
  82157. Vdbe *pVdbe = pParse->pVdbe;
  82158. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  82159. }
  82160. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  82161. sqlite3VdbeFinalize(pParse->pVdbe);
  82162. assert(!(*ppStmt));
  82163. }else{
  82164. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  82165. }
  82166. if( zErrMsg ){
  82167. sqlite3Error(db, rc, "%s", zErrMsg);
  82168. sqlite3DbFree(db, zErrMsg);
  82169. }else{
  82170. sqlite3Error(db, rc, 0);
  82171. }
  82172. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  82173. while( pParse->pTriggerPrg ){
  82174. TriggerPrg *pT = pParse->pTriggerPrg;
  82175. pParse->pTriggerPrg = pT->pNext;
  82176. sqlite3DbFree(db, pT);
  82177. }
  82178. end_prepare:
  82179. sqlite3StackFree(db, pParse);
  82180. rc = sqlite3ApiExit(db, rc);
  82181. assert( (rc&db->errMask)==rc );
  82182. return rc;
  82183. }
  82184. static int sqlite3LockAndPrepare(
  82185. sqlite3 *db, /* Database handle. */
  82186. const char *zSql, /* UTF-8 encoded SQL statement. */
  82187. int nBytes, /* Length of zSql in bytes. */
  82188. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  82189. Vdbe *pOld, /* VM being reprepared */
  82190. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82191. const char **pzTail /* OUT: End of parsed string */
  82192. ){
  82193. int rc;
  82194. assert( ppStmt!=0 );
  82195. *ppStmt = 0;
  82196. if( !sqlite3SafetyCheckOk(db) ){
  82197. return SQLITE_MISUSE_BKPT;
  82198. }
  82199. sqlite3_mutex_enter(db->mutex);
  82200. sqlite3BtreeEnterAll(db);
  82201. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  82202. if( rc==SQLITE_SCHEMA ){
  82203. sqlite3_finalize(*ppStmt);
  82204. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  82205. }
  82206. sqlite3BtreeLeaveAll(db);
  82207. sqlite3_mutex_leave(db->mutex);
  82208. assert( rc==SQLITE_OK || *ppStmt==0 );
  82209. return rc;
  82210. }
  82211. /*
  82212. ** Rerun the compilation of a statement after a schema change.
  82213. **
  82214. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  82215. ** if the statement cannot be recompiled because another connection has
  82216. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  82217. ** occurs, return SQLITE_SCHEMA.
  82218. */
  82219. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  82220. int rc;
  82221. sqlite3_stmt *pNew;
  82222. const char *zSql;
  82223. sqlite3 *db;
  82224. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  82225. zSql = sqlite3_sql((sqlite3_stmt *)p);
  82226. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  82227. db = sqlite3VdbeDb(p);
  82228. assert( sqlite3_mutex_held(db->mutex) );
  82229. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  82230. if( rc ){
  82231. if( rc==SQLITE_NOMEM ){
  82232. db->mallocFailed = 1;
  82233. }
  82234. assert( pNew==0 );
  82235. return rc;
  82236. }else{
  82237. assert( pNew!=0 );
  82238. }
  82239. sqlite3VdbeSwap((Vdbe*)pNew, p);
  82240. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  82241. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  82242. sqlite3VdbeFinalize((Vdbe*)pNew);
  82243. return SQLITE_OK;
  82244. }
  82245. /*
  82246. ** Two versions of the official API. Legacy and new use. In the legacy
  82247. ** version, the original SQL text is not saved in the prepared statement
  82248. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  82249. ** sqlite3_step(). In the new version, the original SQL text is retained
  82250. ** and the statement is automatically recompiled if an schema change
  82251. ** occurs.
  82252. */
  82253. SQLITE_API int sqlite3_prepare(
  82254. sqlite3 *db, /* Database handle. */
  82255. const char *zSql, /* UTF-8 encoded SQL statement. */
  82256. int nBytes, /* Length of zSql in bytes. */
  82257. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82258. const char **pzTail /* OUT: End of parsed string */
  82259. ){
  82260. int rc;
  82261. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  82262. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82263. return rc;
  82264. }
  82265. SQLITE_API int sqlite3_prepare_v2(
  82266. sqlite3 *db, /* Database handle. */
  82267. const char *zSql, /* UTF-8 encoded SQL statement. */
  82268. int nBytes, /* Length of zSql in bytes. */
  82269. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82270. const char **pzTail /* OUT: End of parsed string */
  82271. ){
  82272. int rc;
  82273. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  82274. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82275. return rc;
  82276. }
  82277. #ifndef SQLITE_OMIT_UTF16
  82278. /*
  82279. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  82280. */
  82281. static int sqlite3Prepare16(
  82282. sqlite3 *db, /* Database handle. */
  82283. const void *zSql, /* UTF-16 encoded SQL statement. */
  82284. int nBytes, /* Length of zSql in bytes. */
  82285. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  82286. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82287. const void **pzTail /* OUT: End of parsed string */
  82288. ){
  82289. /* This function currently works by first transforming the UTF-16
  82290. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  82291. ** tricky bit is figuring out the pointer to return in *pzTail.
  82292. */
  82293. char *zSql8;
  82294. const char *zTail8 = 0;
  82295. int rc = SQLITE_OK;
  82296. assert( ppStmt );
  82297. *ppStmt = 0;
  82298. if( !sqlite3SafetyCheckOk(db) ){
  82299. return SQLITE_MISUSE_BKPT;
  82300. }
  82301. if( nBytes>=0 ){
  82302. int sz;
  82303. const char *z = (const char*)zSql;
  82304. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  82305. nBytes = sz;
  82306. }
  82307. sqlite3_mutex_enter(db->mutex);
  82308. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  82309. if( zSql8 ){
  82310. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  82311. }
  82312. if( zTail8 && pzTail ){
  82313. /* If sqlite3_prepare returns a tail pointer, we calculate the
  82314. ** equivalent pointer into the UTF-16 string by counting the unicode
  82315. ** characters between zSql8 and zTail8, and then returning a pointer
  82316. ** the same number of characters into the UTF-16 string.
  82317. */
  82318. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  82319. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  82320. }
  82321. sqlite3DbFree(db, zSql8);
  82322. rc = sqlite3ApiExit(db, rc);
  82323. sqlite3_mutex_leave(db->mutex);
  82324. return rc;
  82325. }
  82326. /*
  82327. ** Two versions of the official API. Legacy and new use. In the legacy
  82328. ** version, the original SQL text is not saved in the prepared statement
  82329. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  82330. ** sqlite3_step(). In the new version, the original SQL text is retained
  82331. ** and the statement is automatically recompiled if an schema change
  82332. ** occurs.
  82333. */
  82334. SQLITE_API int sqlite3_prepare16(
  82335. sqlite3 *db, /* Database handle. */
  82336. const void *zSql, /* UTF-16 encoded SQL statement. */
  82337. int nBytes, /* Length of zSql in bytes. */
  82338. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82339. const void **pzTail /* OUT: End of parsed string */
  82340. ){
  82341. int rc;
  82342. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  82343. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82344. return rc;
  82345. }
  82346. SQLITE_API int sqlite3_prepare16_v2(
  82347. sqlite3 *db, /* Database handle. */
  82348. const void *zSql, /* UTF-16 encoded SQL statement. */
  82349. int nBytes, /* Length of zSql in bytes. */
  82350. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  82351. const void **pzTail /* OUT: End of parsed string */
  82352. ){
  82353. int rc;
  82354. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  82355. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  82356. return rc;
  82357. }
  82358. #endif /* SQLITE_OMIT_UTF16 */
  82359. /************** End of prepare.c *********************************************/
  82360. /************** Begin file select.c ******************************************/
  82361. /*
  82362. ** 2001 September 15
  82363. **
  82364. ** The author disclaims copyright to this source code. In place of
  82365. ** a legal notice, here is a blessing:
  82366. **
  82367. ** May you do good and not evil.
  82368. ** May you find forgiveness for yourself and forgive others.
  82369. ** May you share freely, never taking more than you give.
  82370. **
  82371. *************************************************************************
  82372. ** This file contains C code routines that are called by the parser
  82373. ** to handle SELECT statements in SQLite.
  82374. */
  82375. /*
  82376. ** Delete all the content of a Select structure but do not deallocate
  82377. ** the select structure itself.
  82378. */
  82379. static void clearSelect(sqlite3 *db, Select *p){
  82380. sqlite3ExprListDelete(db, p->pEList);
  82381. sqlite3SrcListDelete(db, p->pSrc);
  82382. sqlite3ExprDelete(db, p->pWhere);
  82383. sqlite3ExprListDelete(db, p->pGroupBy);
  82384. sqlite3ExprDelete(db, p->pHaving);
  82385. sqlite3ExprListDelete(db, p->pOrderBy);
  82386. sqlite3SelectDelete(db, p->pPrior);
  82387. sqlite3ExprDelete(db, p->pLimit);
  82388. sqlite3ExprDelete(db, p->pOffset);
  82389. }
  82390. /*
  82391. ** Initialize a SelectDest structure.
  82392. */
  82393. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  82394. pDest->eDest = (u8)eDest;
  82395. pDest->iSDParm = iParm;
  82396. pDest->affSdst = 0;
  82397. pDest->iSdst = 0;
  82398. pDest->nSdst = 0;
  82399. }
  82400. /*
  82401. ** Allocate a new Select structure and return a pointer to that
  82402. ** structure.
  82403. */
  82404. SQLITE_PRIVATE Select *sqlite3SelectNew(
  82405. Parse *pParse, /* Parsing context */
  82406. ExprList *pEList, /* which columns to include in the result */
  82407. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  82408. Expr *pWhere, /* the WHERE clause */
  82409. ExprList *pGroupBy, /* the GROUP BY clause */
  82410. Expr *pHaving, /* the HAVING clause */
  82411. ExprList *pOrderBy, /* the ORDER BY clause */
  82412. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  82413. Expr *pLimit, /* LIMIT value. NULL means not used */
  82414. Expr *pOffset /* OFFSET value. NULL means no offset */
  82415. ){
  82416. Select *pNew;
  82417. Select standin;
  82418. sqlite3 *db = pParse->db;
  82419. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  82420. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  82421. if( pNew==0 ){
  82422. assert( db->mallocFailed );
  82423. pNew = &standin;
  82424. memset(pNew, 0, sizeof(*pNew));
  82425. }
  82426. if( pEList==0 ){
  82427. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  82428. }
  82429. pNew->pEList = pEList;
  82430. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  82431. pNew->pSrc = pSrc;
  82432. pNew->pWhere = pWhere;
  82433. pNew->pGroupBy = pGroupBy;
  82434. pNew->pHaving = pHaving;
  82435. pNew->pOrderBy = pOrderBy;
  82436. pNew->selFlags = selFlags;
  82437. pNew->op = TK_SELECT;
  82438. pNew->pLimit = pLimit;
  82439. pNew->pOffset = pOffset;
  82440. assert( pOffset==0 || pLimit!=0 );
  82441. pNew->addrOpenEphm[0] = -1;
  82442. pNew->addrOpenEphm[1] = -1;
  82443. pNew->addrOpenEphm[2] = -1;
  82444. if( db->mallocFailed ) {
  82445. clearSelect(db, pNew);
  82446. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  82447. pNew = 0;
  82448. }else{
  82449. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  82450. }
  82451. assert( pNew!=&standin );
  82452. return pNew;
  82453. }
  82454. /*
  82455. ** Delete the given Select structure and all of its substructures.
  82456. */
  82457. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  82458. if( p ){
  82459. clearSelect(db, p);
  82460. sqlite3DbFree(db, p);
  82461. }
  82462. }
  82463. /*
  82464. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  82465. ** type of join. Return an integer constant that expresses that type
  82466. ** in terms of the following bit values:
  82467. **
  82468. ** JT_INNER
  82469. ** JT_CROSS
  82470. ** JT_OUTER
  82471. ** JT_NATURAL
  82472. ** JT_LEFT
  82473. ** JT_RIGHT
  82474. **
  82475. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  82476. **
  82477. ** If an illegal or unsupported join type is seen, then still return
  82478. ** a join type, but put an error in the pParse structure.
  82479. */
  82480. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  82481. int jointype = 0;
  82482. Token *apAll[3];
  82483. Token *p;
  82484. /* 0123456789 123456789 123456789 123 */
  82485. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  82486. static const struct {
  82487. u8 i; /* Beginning of keyword text in zKeyText[] */
  82488. u8 nChar; /* Length of the keyword in characters */
  82489. u8 code; /* Join type mask */
  82490. } aKeyword[] = {
  82491. /* natural */ { 0, 7, JT_NATURAL },
  82492. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  82493. /* outer */ { 10, 5, JT_OUTER },
  82494. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  82495. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  82496. /* inner */ { 23, 5, JT_INNER },
  82497. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  82498. };
  82499. int i, j;
  82500. apAll[0] = pA;
  82501. apAll[1] = pB;
  82502. apAll[2] = pC;
  82503. for(i=0; i<3 && apAll[i]; i++){
  82504. p = apAll[i];
  82505. for(j=0; j<ArraySize(aKeyword); j++){
  82506. if( p->n==aKeyword[j].nChar
  82507. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  82508. jointype |= aKeyword[j].code;
  82509. break;
  82510. }
  82511. }
  82512. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  82513. if( j>=ArraySize(aKeyword) ){
  82514. jointype |= JT_ERROR;
  82515. break;
  82516. }
  82517. }
  82518. if(
  82519. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  82520. (jointype & JT_ERROR)!=0
  82521. ){
  82522. const char *zSp = " ";
  82523. assert( pB!=0 );
  82524. if( pC==0 ){ zSp++; }
  82525. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  82526. "%T %T%s%T", pA, pB, zSp, pC);
  82527. jointype = JT_INNER;
  82528. }else if( (jointype & JT_OUTER)!=0
  82529. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  82530. sqlite3ErrorMsg(pParse,
  82531. "RIGHT and FULL OUTER JOINs are not currently supported");
  82532. jointype = JT_INNER;
  82533. }
  82534. return jointype;
  82535. }
  82536. /*
  82537. ** Return the index of a column in a table. Return -1 if the column
  82538. ** is not contained in the table.
  82539. */
  82540. static int columnIndex(Table *pTab, const char *zCol){
  82541. int i;
  82542. for(i=0; i<pTab->nCol; i++){
  82543. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  82544. }
  82545. return -1;
  82546. }
  82547. /*
  82548. ** Search the first N tables in pSrc, from left to right, looking for a
  82549. ** table that has a column named zCol.
  82550. **
  82551. ** When found, set *piTab and *piCol to the table index and column index
  82552. ** of the matching column and return TRUE.
  82553. **
  82554. ** If not found, return FALSE.
  82555. */
  82556. static int tableAndColumnIndex(
  82557. SrcList *pSrc, /* Array of tables to search */
  82558. int N, /* Number of tables in pSrc->a[] to search */
  82559. const char *zCol, /* Name of the column we are looking for */
  82560. int *piTab, /* Write index of pSrc->a[] here */
  82561. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  82562. ){
  82563. int i; /* For looping over tables in pSrc */
  82564. int iCol; /* Index of column matching zCol */
  82565. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  82566. for(i=0; i<N; i++){
  82567. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  82568. if( iCol>=0 ){
  82569. if( piTab ){
  82570. *piTab = i;
  82571. *piCol = iCol;
  82572. }
  82573. return 1;
  82574. }
  82575. }
  82576. return 0;
  82577. }
  82578. /*
  82579. ** This function is used to add terms implied by JOIN syntax to the
  82580. ** WHERE clause expression of a SELECT statement. The new term, which
  82581. ** is ANDed with the existing WHERE clause, is of the form:
  82582. **
  82583. ** (tab1.col1 = tab2.col2)
  82584. **
  82585. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  82586. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  82587. ** column iColRight of tab2.
  82588. */
  82589. static void addWhereTerm(
  82590. Parse *pParse, /* Parsing context */
  82591. SrcList *pSrc, /* List of tables in FROM clause */
  82592. int iLeft, /* Index of first table to join in pSrc */
  82593. int iColLeft, /* Index of column in first table */
  82594. int iRight, /* Index of second table in pSrc */
  82595. int iColRight, /* Index of column in second table */
  82596. int isOuterJoin, /* True if this is an OUTER join */
  82597. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  82598. ){
  82599. sqlite3 *db = pParse->db;
  82600. Expr *pE1;
  82601. Expr *pE2;
  82602. Expr *pEq;
  82603. assert( iLeft<iRight );
  82604. assert( pSrc->nSrc>iRight );
  82605. assert( pSrc->a[iLeft].pTab );
  82606. assert( pSrc->a[iRight].pTab );
  82607. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  82608. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  82609. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  82610. if( pEq && isOuterJoin ){
  82611. ExprSetProperty(pEq, EP_FromJoin);
  82612. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  82613. ExprSetVVAProperty(pEq, EP_NoReduce);
  82614. pEq->iRightJoinTable = (i16)pE2->iTable;
  82615. }
  82616. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  82617. }
  82618. /*
  82619. ** Set the EP_FromJoin property on all terms of the given expression.
  82620. ** And set the Expr.iRightJoinTable to iTable for every term in the
  82621. ** expression.
  82622. **
  82623. ** The EP_FromJoin property is used on terms of an expression to tell
  82624. ** the LEFT OUTER JOIN processing logic that this term is part of the
  82625. ** join restriction specified in the ON or USING clause and not a part
  82626. ** of the more general WHERE clause. These terms are moved over to the
  82627. ** WHERE clause during join processing but we need to remember that they
  82628. ** originated in the ON or USING clause.
  82629. **
  82630. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  82631. ** expression depends on table iRightJoinTable even if that table is not
  82632. ** explicitly mentioned in the expression. That information is needed
  82633. ** for cases like this:
  82634. **
  82635. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  82636. **
  82637. ** The where clause needs to defer the handling of the t1.x=5
  82638. ** term until after the t2 loop of the join. In that way, a
  82639. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  82640. ** defer the handling of t1.x=5, it will be processed immediately
  82641. ** after the t1 loop and rows with t1.x!=5 will never appear in
  82642. ** the output, which is incorrect.
  82643. */
  82644. static void setJoinExpr(Expr *p, int iTable){
  82645. while( p ){
  82646. ExprSetProperty(p, EP_FromJoin);
  82647. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  82648. ExprSetVVAProperty(p, EP_NoReduce);
  82649. p->iRightJoinTable = (i16)iTable;
  82650. setJoinExpr(p->pLeft, iTable);
  82651. p = p->pRight;
  82652. }
  82653. }
  82654. /*
  82655. ** This routine processes the join information for a SELECT statement.
  82656. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  82657. ** NATURAL joins also create extra WHERE clause terms.
  82658. **
  82659. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  82660. ** The left most table is the first entry in Select.pSrc. The right-most
  82661. ** table is the last entry. The join operator is held in the entry to
  82662. ** the left. Thus entry 0 contains the join operator for the join between
  82663. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  82664. ** also attached to the left entry.
  82665. **
  82666. ** This routine returns the number of errors encountered.
  82667. */
  82668. static int sqliteProcessJoin(Parse *pParse, Select *p){
  82669. SrcList *pSrc; /* All tables in the FROM clause */
  82670. int i, j; /* Loop counters */
  82671. struct SrcList_item *pLeft; /* Left table being joined */
  82672. struct SrcList_item *pRight; /* Right table being joined */
  82673. pSrc = p->pSrc;
  82674. pLeft = &pSrc->a[0];
  82675. pRight = &pLeft[1];
  82676. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  82677. Table *pLeftTab = pLeft->pTab;
  82678. Table *pRightTab = pRight->pTab;
  82679. int isOuter;
  82680. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  82681. isOuter = (pRight->jointype & JT_OUTER)!=0;
  82682. /* When the NATURAL keyword is present, add WHERE clause terms for
  82683. ** every column that the two tables have in common.
  82684. */
  82685. if( pRight->jointype & JT_NATURAL ){
  82686. if( pRight->pOn || pRight->pUsing ){
  82687. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  82688. "an ON or USING clause", 0);
  82689. return 1;
  82690. }
  82691. for(j=0; j<pRightTab->nCol; j++){
  82692. char *zName; /* Name of column in the right table */
  82693. int iLeft; /* Matching left table */
  82694. int iLeftCol; /* Matching column in the left table */
  82695. zName = pRightTab->aCol[j].zName;
  82696. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  82697. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  82698. isOuter, &p->pWhere);
  82699. }
  82700. }
  82701. }
  82702. /* Disallow both ON and USING clauses in the same join
  82703. */
  82704. if( pRight->pOn && pRight->pUsing ){
  82705. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  82706. "clauses in the same join");
  82707. return 1;
  82708. }
  82709. /* Add the ON clause to the end of the WHERE clause, connected by
  82710. ** an AND operator.
  82711. */
  82712. if( pRight->pOn ){
  82713. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  82714. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  82715. pRight->pOn = 0;
  82716. }
  82717. /* Create extra terms on the WHERE clause for each column named
  82718. ** in the USING clause. Example: If the two tables to be joined are
  82719. ** A and B and the USING clause names X, Y, and Z, then add this
  82720. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  82721. ** Report an error if any column mentioned in the USING clause is
  82722. ** not contained in both tables to be joined.
  82723. */
  82724. if( pRight->pUsing ){
  82725. IdList *pList = pRight->pUsing;
  82726. for(j=0; j<pList->nId; j++){
  82727. char *zName; /* Name of the term in the USING clause */
  82728. int iLeft; /* Table on the left with matching column name */
  82729. int iLeftCol; /* Column number of matching column on the left */
  82730. int iRightCol; /* Column number of matching column on the right */
  82731. zName = pList->a[j].zName;
  82732. iRightCol = columnIndex(pRightTab, zName);
  82733. if( iRightCol<0
  82734. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  82735. ){
  82736. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  82737. "not present in both tables", zName);
  82738. return 1;
  82739. }
  82740. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  82741. isOuter, &p->pWhere);
  82742. }
  82743. }
  82744. }
  82745. return 0;
  82746. }
  82747. /*
  82748. ** Insert code into "v" that will push the record on the top of the
  82749. ** stack into the sorter.
  82750. */
  82751. static void pushOntoSorter(
  82752. Parse *pParse, /* Parser context */
  82753. ExprList *pOrderBy, /* The ORDER BY clause */
  82754. Select *pSelect, /* The whole SELECT statement */
  82755. int regData /* Register holding data to be sorted */
  82756. ){
  82757. Vdbe *v = pParse->pVdbe;
  82758. int nExpr = pOrderBy->nExpr;
  82759. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  82760. int regRecord = sqlite3GetTempReg(pParse);
  82761. int op;
  82762. sqlite3ExprCacheClear(pParse);
  82763. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  82764. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  82765. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  82766. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  82767. if( pSelect->selFlags & SF_UseSorter ){
  82768. op = OP_SorterInsert;
  82769. }else{
  82770. op = OP_IdxInsert;
  82771. }
  82772. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  82773. sqlite3ReleaseTempReg(pParse, regRecord);
  82774. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  82775. if( pSelect->iLimit ){
  82776. int addr1, addr2;
  82777. int iLimit;
  82778. if( pSelect->iOffset ){
  82779. iLimit = pSelect->iOffset+1;
  82780. }else{
  82781. iLimit = pSelect->iLimit;
  82782. }
  82783. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  82784. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  82785. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  82786. sqlite3VdbeJumpHere(v, addr1);
  82787. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  82788. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  82789. sqlite3VdbeJumpHere(v, addr2);
  82790. }
  82791. }
  82792. /*
  82793. ** Add code to implement the OFFSET
  82794. */
  82795. static void codeOffset(
  82796. Vdbe *v, /* Generate code into this VM */
  82797. Select *p, /* The SELECT statement being coded */
  82798. int iContinue /* Jump here to skip the current record */
  82799. ){
  82800. if( p->iOffset && iContinue!=0 ){
  82801. int addr;
  82802. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  82803. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  82804. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  82805. VdbeComment((v, "skip OFFSET records"));
  82806. sqlite3VdbeJumpHere(v, addr);
  82807. }
  82808. }
  82809. /*
  82810. ** Add code that will check to make sure the N registers starting at iMem
  82811. ** form a distinct entry. iTab is a sorting index that holds previously
  82812. ** seen combinations of the N values. A new entry is made in iTab
  82813. ** if the current N values are new.
  82814. **
  82815. ** A jump to addrRepeat is made and the N+1 values are popped from the
  82816. ** stack if the top N elements are not distinct.
  82817. */
  82818. static void codeDistinct(
  82819. Parse *pParse, /* Parsing and code generating context */
  82820. int iTab, /* A sorting index used to test for distinctness */
  82821. int addrRepeat, /* Jump to here if not distinct */
  82822. int N, /* Number of elements */
  82823. int iMem /* First element */
  82824. ){
  82825. Vdbe *v;
  82826. int r1;
  82827. v = pParse->pVdbe;
  82828. r1 = sqlite3GetTempReg(pParse);
  82829. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  82830. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  82831. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  82832. sqlite3ReleaseTempReg(pParse, r1);
  82833. }
  82834. #ifndef SQLITE_OMIT_SUBQUERY
  82835. /*
  82836. ** Generate an error message when a SELECT is used within a subexpression
  82837. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  82838. ** column. We do this in a subroutine because the error used to occur
  82839. ** in multiple places. (The error only occurs in one place now, but we
  82840. ** retain the subroutine to minimize code disruption.)
  82841. */
  82842. static int checkForMultiColumnSelectError(
  82843. Parse *pParse, /* Parse context. */
  82844. SelectDest *pDest, /* Destination of SELECT results */
  82845. int nExpr /* Number of result columns returned by SELECT */
  82846. ){
  82847. int eDest = pDest->eDest;
  82848. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  82849. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  82850. "a SELECT that is part of an expression");
  82851. return 1;
  82852. }else{
  82853. return 0;
  82854. }
  82855. }
  82856. #endif
  82857. /*
  82858. ** An instance of the following object is used to record information about
  82859. ** how to process the DISTINCT keyword, to simplify passing that information
  82860. ** into the selectInnerLoop() routine.
  82861. */
  82862. typedef struct DistinctCtx DistinctCtx;
  82863. struct DistinctCtx {
  82864. u8 isTnct; /* True if the DISTINCT keyword is present */
  82865. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  82866. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  82867. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  82868. };
  82869. /*
  82870. ** This routine generates the code for the inside of the inner loop
  82871. ** of a SELECT.
  82872. **
  82873. ** If srcTab and nColumn are both zero, then the pEList expressions
  82874. ** are evaluated in order to get the data for this row. If nColumn>0
  82875. ** then data is pulled from srcTab and pEList is used only to get the
  82876. ** datatypes for each column.
  82877. */
  82878. static void selectInnerLoop(
  82879. Parse *pParse, /* The parser context */
  82880. Select *p, /* The complete select statement being coded */
  82881. ExprList *pEList, /* List of values being extracted */
  82882. int srcTab, /* Pull data from this table */
  82883. int nColumn, /* Number of columns in the source table */
  82884. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  82885. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  82886. SelectDest *pDest, /* How to dispose of the results */
  82887. int iContinue, /* Jump here to continue with next row */
  82888. int iBreak /* Jump here to break out of the inner loop */
  82889. ){
  82890. Vdbe *v = pParse->pVdbe;
  82891. int i;
  82892. int hasDistinct; /* True if the DISTINCT keyword is present */
  82893. int regResult; /* Start of memory holding result set */
  82894. int eDest = pDest->eDest; /* How to dispose of results */
  82895. int iParm = pDest->iSDParm; /* First argument to disposal method */
  82896. int nResultCol; /* Number of result columns */
  82897. assert( v );
  82898. if( NEVER(v==0) ) return;
  82899. assert( pEList!=0 );
  82900. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  82901. if( pOrderBy==0 && !hasDistinct ){
  82902. codeOffset(v, p, iContinue);
  82903. }
  82904. /* Pull the requested columns.
  82905. */
  82906. if( nColumn>0 ){
  82907. nResultCol = nColumn;
  82908. }else{
  82909. nResultCol = pEList->nExpr;
  82910. }
  82911. if( pDest->iSdst==0 ){
  82912. pDest->iSdst = pParse->nMem+1;
  82913. pDest->nSdst = nResultCol;
  82914. pParse->nMem += nResultCol;
  82915. }else{
  82916. assert( pDest->nSdst==nResultCol );
  82917. }
  82918. regResult = pDest->iSdst;
  82919. if( nColumn>0 ){
  82920. for(i=0; i<nColumn; i++){
  82921. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  82922. }
  82923. }else if( eDest!=SRT_Exists ){
  82924. /* If the destination is an EXISTS(...) expression, the actual
  82925. ** values returned by the SELECT are not required.
  82926. */
  82927. sqlite3ExprCacheClear(pParse);
  82928. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  82929. }
  82930. nColumn = nResultCol;
  82931. /* If the DISTINCT keyword was present on the SELECT statement
  82932. ** and this row has been seen before, then do not make this row
  82933. ** part of the result.
  82934. */
  82935. if( hasDistinct ){
  82936. assert( pEList!=0 );
  82937. assert( pEList->nExpr==nColumn );
  82938. switch( pDistinct->eTnctType ){
  82939. case WHERE_DISTINCT_ORDERED: {
  82940. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  82941. int iJump; /* Jump destination */
  82942. int regPrev; /* Previous row content */
  82943. /* Allocate space for the previous row */
  82944. regPrev = pParse->nMem+1;
  82945. pParse->nMem += nColumn;
  82946. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  82947. ** sets the MEM_Cleared bit on the first register of the
  82948. ** previous value. This will cause the OP_Ne below to always
  82949. ** fail on the first iteration of the loop even if the first
  82950. ** row is all NULLs.
  82951. */
  82952. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  82953. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  82954. pOp->opcode = OP_Null;
  82955. pOp->p1 = 1;
  82956. pOp->p2 = regPrev;
  82957. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  82958. for(i=0; i<nColumn; i++){
  82959. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  82960. if( i<nColumn-1 ){
  82961. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  82962. }else{
  82963. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  82964. }
  82965. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  82966. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  82967. }
  82968. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  82969. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  82970. break;
  82971. }
  82972. case WHERE_DISTINCT_UNIQUE: {
  82973. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  82974. break;
  82975. }
  82976. default: {
  82977. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  82978. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  82979. break;
  82980. }
  82981. }
  82982. if( pOrderBy==0 ){
  82983. codeOffset(v, p, iContinue);
  82984. }
  82985. }
  82986. switch( eDest ){
  82987. /* In this mode, write each query result to the key of the temporary
  82988. ** table iParm.
  82989. */
  82990. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  82991. case SRT_Union: {
  82992. int r1;
  82993. r1 = sqlite3GetTempReg(pParse);
  82994. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  82995. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  82996. sqlite3ReleaseTempReg(pParse, r1);
  82997. break;
  82998. }
  82999. /* Construct a record from the query result, but instead of
  83000. ** saving that record, use it as a key to delete elements from
  83001. ** the temporary table iParm.
  83002. */
  83003. case SRT_Except: {
  83004. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  83005. break;
  83006. }
  83007. #endif
  83008. /* Store the result as data using a unique key.
  83009. */
  83010. case SRT_Table:
  83011. case SRT_EphemTab: {
  83012. int r1 = sqlite3GetTempReg(pParse);
  83013. testcase( eDest==SRT_Table );
  83014. testcase( eDest==SRT_EphemTab );
  83015. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  83016. if( pOrderBy ){
  83017. pushOntoSorter(pParse, pOrderBy, p, r1);
  83018. }else{
  83019. int r2 = sqlite3GetTempReg(pParse);
  83020. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  83021. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  83022. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83023. sqlite3ReleaseTempReg(pParse, r2);
  83024. }
  83025. sqlite3ReleaseTempReg(pParse, r1);
  83026. break;
  83027. }
  83028. #ifndef SQLITE_OMIT_SUBQUERY
  83029. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  83030. ** then there should be a single item on the stack. Write this
  83031. ** item into the set table with bogus data.
  83032. */
  83033. case SRT_Set: {
  83034. assert( nColumn==1 );
  83035. pDest->affSdst =
  83036. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  83037. if( pOrderBy ){
  83038. /* At first glance you would think we could optimize out the
  83039. ** ORDER BY in this case since the order of entries in the set
  83040. ** does not matter. But there might be a LIMIT clause, in which
  83041. ** case the order does matter */
  83042. pushOntoSorter(pParse, pOrderBy, p, regResult);
  83043. }else{
  83044. int r1 = sqlite3GetTempReg(pParse);
  83045. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  83046. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  83047. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  83048. sqlite3ReleaseTempReg(pParse, r1);
  83049. }
  83050. break;
  83051. }
  83052. /* If any row exist in the result set, record that fact and abort.
  83053. */
  83054. case SRT_Exists: {
  83055. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  83056. /* The LIMIT clause will terminate the loop for us */
  83057. break;
  83058. }
  83059. /* If this is a scalar select that is part of an expression, then
  83060. ** store the results in the appropriate memory cell and break out
  83061. ** of the scan loop.
  83062. */
  83063. case SRT_Mem: {
  83064. assert( nColumn==1 );
  83065. if( pOrderBy ){
  83066. pushOntoSorter(pParse, pOrderBy, p, regResult);
  83067. }else{
  83068. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  83069. /* The LIMIT clause will jump out of the loop for us */
  83070. }
  83071. break;
  83072. }
  83073. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  83074. /* Send the data to the callback function or to a subroutine. In the
  83075. ** case of a subroutine, the subroutine itself is responsible for
  83076. ** popping the data from the stack.
  83077. */
  83078. case SRT_Coroutine:
  83079. case SRT_Output: {
  83080. testcase( eDest==SRT_Coroutine );
  83081. testcase( eDest==SRT_Output );
  83082. if( pOrderBy ){
  83083. int r1 = sqlite3GetTempReg(pParse);
  83084. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  83085. pushOntoSorter(pParse, pOrderBy, p, r1);
  83086. sqlite3ReleaseTempReg(pParse, r1);
  83087. }else if( eDest==SRT_Coroutine ){
  83088. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  83089. }else{
  83090. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  83091. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  83092. }
  83093. break;
  83094. }
  83095. #if !defined(SQLITE_OMIT_TRIGGER)
  83096. /* Discard the results. This is used for SELECT statements inside
  83097. ** the body of a TRIGGER. The purpose of such selects is to call
  83098. ** user-defined functions that have side effects. We do not care
  83099. ** about the actual results of the select.
  83100. */
  83101. default: {
  83102. assert( eDest==SRT_Discard );
  83103. break;
  83104. }
  83105. #endif
  83106. }
  83107. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  83108. ** there is a sorter, in which case the sorter has already limited
  83109. ** the output for us.
  83110. */
  83111. if( pOrderBy==0 && p->iLimit ){
  83112. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  83113. }
  83114. }
  83115. /*
  83116. ** Allocate a KeyInfo object sufficient for an index of N columns.
  83117. **
  83118. ** Actually, always allocate one extra column for the rowid at the end
  83119. ** of the index. So the KeyInfo returned will have space sufficient for
  83120. ** N+1 columns.
  83121. */
  83122. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
  83123. KeyInfo *p = sqlite3DbMallocZero(db,
  83124. sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
  83125. if( p ){
  83126. p->aSortOrder = (u8*)&p->aColl[N+1];
  83127. p->nField = (u16)N;
  83128. p->enc = ENC(db);
  83129. p->db = db;
  83130. }
  83131. return p;
  83132. }
  83133. /*
  83134. ** Given an expression list, generate a KeyInfo structure that records
  83135. ** the collating sequence for each expression in that expression list.
  83136. **
  83137. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  83138. ** KeyInfo structure is appropriate for initializing a virtual index to
  83139. ** implement that clause. If the ExprList is the result set of a SELECT
  83140. ** then the KeyInfo structure is appropriate for initializing a virtual
  83141. ** index to implement a DISTINCT test.
  83142. **
  83143. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  83144. ** function is responsible for seeing that this structure is eventually
  83145. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  83146. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  83147. */
  83148. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  83149. int nExpr;
  83150. KeyInfo *pInfo;
  83151. struct ExprList_item *pItem;
  83152. sqlite3 *db = pParse->db;
  83153. int i;
  83154. nExpr = pList->nExpr;
  83155. pInfo = sqlite3KeyInfoAlloc(db, nExpr);
  83156. if( pInfo ){
  83157. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  83158. CollSeq *pColl;
  83159. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  83160. if( !pColl ) pColl = db->pDfltColl;
  83161. pInfo->aColl[i] = pColl;
  83162. pInfo->aSortOrder[i] = pItem->sortOrder;
  83163. }
  83164. }
  83165. return pInfo;
  83166. }
  83167. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83168. /*
  83169. ** Name of the connection operator, used for error messages.
  83170. */
  83171. static const char *selectOpName(int id){
  83172. char *z;
  83173. switch( id ){
  83174. case TK_ALL: z = "UNION ALL"; break;
  83175. case TK_INTERSECT: z = "INTERSECT"; break;
  83176. case TK_EXCEPT: z = "EXCEPT"; break;
  83177. default: z = "UNION"; break;
  83178. }
  83179. return z;
  83180. }
  83181. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  83182. #ifndef SQLITE_OMIT_EXPLAIN
  83183. /*
  83184. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  83185. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  83186. ** where the caption is of the form:
  83187. **
  83188. ** "USE TEMP B-TREE FOR xxx"
  83189. **
  83190. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  83191. ** is determined by the zUsage argument.
  83192. */
  83193. static void explainTempTable(Parse *pParse, const char *zUsage){
  83194. if( pParse->explain==2 ){
  83195. Vdbe *v = pParse->pVdbe;
  83196. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  83197. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  83198. }
  83199. }
  83200. /*
  83201. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  83202. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  83203. ** in sqlite3Select() to assign values to structure member variables that
  83204. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  83205. ** code with #ifndef directives.
  83206. */
  83207. # define explainSetInteger(a, b) a = b
  83208. #else
  83209. /* No-op versions of the explainXXX() functions and macros. */
  83210. # define explainTempTable(y,z)
  83211. # define explainSetInteger(y,z)
  83212. #endif
  83213. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  83214. /*
  83215. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  83216. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  83217. ** where the caption is of one of the two forms:
  83218. **
  83219. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  83220. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  83221. **
  83222. ** where iSub1 and iSub2 are the integers passed as the corresponding
  83223. ** function parameters, and op is the text representation of the parameter
  83224. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  83225. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  83226. ** false, or the second form if it is true.
  83227. */
  83228. static void explainComposite(
  83229. Parse *pParse, /* Parse context */
  83230. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  83231. int iSub1, /* Subquery id 1 */
  83232. int iSub2, /* Subquery id 2 */
  83233. int bUseTmp /* True if a temp table was used */
  83234. ){
  83235. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  83236. if( pParse->explain==2 ){
  83237. Vdbe *v = pParse->pVdbe;
  83238. char *zMsg = sqlite3MPrintf(
  83239. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  83240. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  83241. );
  83242. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  83243. }
  83244. }
  83245. #else
  83246. /* No-op versions of the explainXXX() functions and macros. */
  83247. # define explainComposite(v,w,x,y,z)
  83248. #endif
  83249. /*
  83250. ** If the inner loop was generated using a non-null pOrderBy argument,
  83251. ** then the results were placed in a sorter. After the loop is terminated
  83252. ** we need to run the sorter and output the results. The following
  83253. ** routine generates the code needed to do that.
  83254. */
  83255. static void generateSortTail(
  83256. Parse *pParse, /* Parsing context */
  83257. Select *p, /* The SELECT statement */
  83258. Vdbe *v, /* Generate code into this VDBE */
  83259. int nColumn, /* Number of columns of data */
  83260. SelectDest *pDest /* Write the sorted results here */
  83261. ){
  83262. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  83263. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  83264. int addr;
  83265. int iTab;
  83266. int pseudoTab = 0;
  83267. ExprList *pOrderBy = p->pOrderBy;
  83268. int eDest = pDest->eDest;
  83269. int iParm = pDest->iSDParm;
  83270. int regRow;
  83271. int regRowid;
  83272. iTab = pOrderBy->iECursor;
  83273. regRow = sqlite3GetTempReg(pParse);
  83274. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  83275. pseudoTab = pParse->nTab++;
  83276. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  83277. regRowid = 0;
  83278. }else{
  83279. regRowid = sqlite3GetTempReg(pParse);
  83280. }
  83281. if( p->selFlags & SF_UseSorter ){
  83282. int regSortOut = ++pParse->nMem;
  83283. int ptab2 = pParse->nTab++;
  83284. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  83285. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  83286. codeOffset(v, p, addrContinue);
  83287. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  83288. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  83289. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  83290. }else{
  83291. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  83292. codeOffset(v, p, addrContinue);
  83293. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  83294. }
  83295. switch( eDest ){
  83296. case SRT_Table:
  83297. case SRT_EphemTab: {
  83298. testcase( eDest==SRT_Table );
  83299. testcase( eDest==SRT_EphemTab );
  83300. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  83301. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  83302. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83303. break;
  83304. }
  83305. #ifndef SQLITE_OMIT_SUBQUERY
  83306. case SRT_Set: {
  83307. assert( nColumn==1 );
  83308. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  83309. &pDest->affSdst, 1);
  83310. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  83311. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  83312. break;
  83313. }
  83314. case SRT_Mem: {
  83315. assert( nColumn==1 );
  83316. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  83317. /* The LIMIT clause will terminate the loop for us */
  83318. break;
  83319. }
  83320. #endif
  83321. default: {
  83322. int i;
  83323. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  83324. testcase( eDest==SRT_Output );
  83325. testcase( eDest==SRT_Coroutine );
  83326. for(i=0; i<nColumn; i++){
  83327. assert( regRow!=pDest->iSdst+i );
  83328. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  83329. if( i==0 ){
  83330. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  83331. }
  83332. }
  83333. if( eDest==SRT_Output ){
  83334. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  83335. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  83336. }else{
  83337. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  83338. }
  83339. break;
  83340. }
  83341. }
  83342. sqlite3ReleaseTempReg(pParse, regRow);
  83343. sqlite3ReleaseTempReg(pParse, regRowid);
  83344. /* The bottom of the loop
  83345. */
  83346. sqlite3VdbeResolveLabel(v, addrContinue);
  83347. if( p->selFlags & SF_UseSorter ){
  83348. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  83349. }else{
  83350. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  83351. }
  83352. sqlite3VdbeResolveLabel(v, addrBreak);
  83353. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  83354. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  83355. }
  83356. }
  83357. /*
  83358. ** Return a pointer to a string containing the 'declaration type' of the
  83359. ** expression pExpr. The string may be treated as static by the caller.
  83360. **
  83361. ** Also try to estimate the size of the returned value and return that
  83362. ** result in *pEstWidth.
  83363. **
  83364. ** The declaration type is the exact datatype definition extracted from the
  83365. ** original CREATE TABLE statement if the expression is a column. The
  83366. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  83367. ** is considered a column can be complex in the presence of subqueries. The
  83368. ** result-set expression in all of the following SELECT statements is
  83369. ** considered a column by this function.
  83370. **
  83371. ** SELECT col FROM tbl;
  83372. ** SELECT (SELECT col FROM tbl;
  83373. ** SELECT (SELECT col FROM tbl);
  83374. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  83375. **
  83376. ** The declaration type for any expression other than a column is NULL.
  83377. **
  83378. ** This routine has either 3 or 6 parameters depending on whether or not
  83379. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  83380. */
  83381. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83382. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  83383. static const char *columnTypeImpl(
  83384. NameContext *pNC,
  83385. Expr *pExpr,
  83386. const char **pzOrigDb,
  83387. const char **pzOrigTab,
  83388. const char **pzOrigCol,
  83389. u8 *pEstWidth
  83390. ){
  83391. char const *zOrigDb = 0;
  83392. char const *zOrigTab = 0;
  83393. char const *zOrigCol = 0;
  83394. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  83395. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  83396. static const char *columnTypeImpl(
  83397. NameContext *pNC,
  83398. Expr *pExpr,
  83399. u8 *pEstWidth
  83400. ){
  83401. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  83402. char const *zType = 0;
  83403. int j;
  83404. u8 estWidth = 1;
  83405. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  83406. switch( pExpr->op ){
  83407. case TK_AGG_COLUMN:
  83408. case TK_COLUMN: {
  83409. /* The expression is a column. Locate the table the column is being
  83410. ** extracted from in NameContext.pSrcList. This table may be real
  83411. ** database table or a subquery.
  83412. */
  83413. Table *pTab = 0; /* Table structure column is extracted from */
  83414. Select *pS = 0; /* Select the column is extracted from */
  83415. int iCol = pExpr->iColumn; /* Index of column in pTab */
  83416. testcase( pExpr->op==TK_AGG_COLUMN );
  83417. testcase( pExpr->op==TK_COLUMN );
  83418. while( pNC && !pTab ){
  83419. SrcList *pTabList = pNC->pSrcList;
  83420. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  83421. if( j<pTabList->nSrc ){
  83422. pTab = pTabList->a[j].pTab;
  83423. pS = pTabList->a[j].pSelect;
  83424. }else{
  83425. pNC = pNC->pNext;
  83426. }
  83427. }
  83428. if( pTab==0 ){
  83429. /* At one time, code such as "SELECT new.x" within a trigger would
  83430. ** cause this condition to run. Since then, we have restructured how
  83431. ** trigger code is generated and so this condition is no longer
  83432. ** possible. However, it can still be true for statements like
  83433. ** the following:
  83434. **
  83435. ** CREATE TABLE t1(col INTEGER);
  83436. ** SELECT (SELECT t1.col) FROM FROM t1;
  83437. **
  83438. ** when columnType() is called on the expression "t1.col" in the
  83439. ** sub-select. In this case, set the column type to NULL, even
  83440. ** though it should really be "INTEGER".
  83441. **
  83442. ** This is not a problem, as the column type of "t1.col" is never
  83443. ** used. When columnType() is called on the expression
  83444. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  83445. ** branch below. */
  83446. break;
  83447. }
  83448. assert( pTab && pExpr->pTab==pTab );
  83449. if( pS ){
  83450. /* The "table" is actually a sub-select or a view in the FROM clause
  83451. ** of the SELECT statement. Return the declaration type and origin
  83452. ** data for the result-set column of the sub-select.
  83453. */
  83454. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  83455. /* If iCol is less than zero, then the expression requests the
  83456. ** rowid of the sub-select or view. This expression is legal (see
  83457. ** test case misc2.2.2) - it always evaluates to NULL.
  83458. */
  83459. NameContext sNC;
  83460. Expr *p = pS->pEList->a[iCol].pExpr;
  83461. sNC.pSrcList = pS->pSrc;
  83462. sNC.pNext = pNC;
  83463. sNC.pParse = pNC->pParse;
  83464. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  83465. }
  83466. }else if( ALWAYS(pTab->pSchema) ){
  83467. /* A real table */
  83468. assert( !pS );
  83469. if( iCol<0 ) iCol = pTab->iPKey;
  83470. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  83471. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83472. if( iCol<0 ){
  83473. zType = "INTEGER";
  83474. zOrigCol = "rowid";
  83475. }else{
  83476. zType = pTab->aCol[iCol].zType;
  83477. zOrigCol = pTab->aCol[iCol].zName;
  83478. estWidth = pTab->aCol[iCol].szEst;
  83479. }
  83480. zOrigTab = pTab->zName;
  83481. if( pNC->pParse ){
  83482. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  83483. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  83484. }
  83485. #else
  83486. if( iCol<0 ){
  83487. zType = "INTEGER";
  83488. }else{
  83489. zType = pTab->aCol[iCol].zType;
  83490. estWidth = pTab->aCol[iCol].szEst;
  83491. }
  83492. #endif
  83493. }
  83494. break;
  83495. }
  83496. #ifndef SQLITE_OMIT_SUBQUERY
  83497. case TK_SELECT: {
  83498. /* The expression is a sub-select. Return the declaration type and
  83499. ** origin info for the single column in the result set of the SELECT
  83500. ** statement.
  83501. */
  83502. NameContext sNC;
  83503. Select *pS = pExpr->x.pSelect;
  83504. Expr *p = pS->pEList->a[0].pExpr;
  83505. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  83506. sNC.pSrcList = pS->pSrc;
  83507. sNC.pNext = pNC;
  83508. sNC.pParse = pNC->pParse;
  83509. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  83510. break;
  83511. }
  83512. #endif
  83513. }
  83514. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83515. if( pzOrigDb ){
  83516. assert( pzOrigTab && pzOrigCol );
  83517. *pzOrigDb = zOrigDb;
  83518. *pzOrigTab = zOrigTab;
  83519. *pzOrigCol = zOrigCol;
  83520. }
  83521. #endif
  83522. if( pEstWidth ) *pEstWidth = estWidth;
  83523. return zType;
  83524. }
  83525. /*
  83526. ** Generate code that will tell the VDBE the declaration types of columns
  83527. ** in the result set.
  83528. */
  83529. static void generateColumnTypes(
  83530. Parse *pParse, /* Parser context */
  83531. SrcList *pTabList, /* List of tables */
  83532. ExprList *pEList /* Expressions defining the result set */
  83533. ){
  83534. #ifndef SQLITE_OMIT_DECLTYPE
  83535. Vdbe *v = pParse->pVdbe;
  83536. int i;
  83537. NameContext sNC;
  83538. sNC.pSrcList = pTabList;
  83539. sNC.pParse = pParse;
  83540. for(i=0; i<pEList->nExpr; i++){
  83541. Expr *p = pEList->a[i].pExpr;
  83542. const char *zType;
  83543. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  83544. const char *zOrigDb = 0;
  83545. const char *zOrigTab = 0;
  83546. const char *zOrigCol = 0;
  83547. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  83548. /* The vdbe must make its own copy of the column-type and other
  83549. ** column specific strings, in case the schema is reset before this
  83550. ** virtual machine is deleted.
  83551. */
  83552. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  83553. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  83554. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  83555. #else
  83556. zType = columnType(&sNC, p, 0, 0, 0, 0);
  83557. #endif
  83558. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  83559. }
  83560. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  83561. }
  83562. /*
  83563. ** Generate code that will tell the VDBE the names of columns
  83564. ** in the result set. This information is used to provide the
  83565. ** azCol[] values in the callback.
  83566. */
  83567. static void generateColumnNames(
  83568. Parse *pParse, /* Parser context */
  83569. SrcList *pTabList, /* List of tables */
  83570. ExprList *pEList /* Expressions defining the result set */
  83571. ){
  83572. Vdbe *v = pParse->pVdbe;
  83573. int i, j;
  83574. sqlite3 *db = pParse->db;
  83575. int fullNames, shortNames;
  83576. #ifndef SQLITE_OMIT_EXPLAIN
  83577. /* If this is an EXPLAIN, skip this step */
  83578. if( pParse->explain ){
  83579. return;
  83580. }
  83581. #endif
  83582. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  83583. pParse->colNamesSet = 1;
  83584. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  83585. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  83586. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  83587. for(i=0; i<pEList->nExpr; i++){
  83588. Expr *p;
  83589. p = pEList->a[i].pExpr;
  83590. if( NEVER(p==0) ) continue;
  83591. if( pEList->a[i].zName ){
  83592. char *zName = pEList->a[i].zName;
  83593. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  83594. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  83595. Table *pTab;
  83596. char *zCol;
  83597. int iCol = p->iColumn;
  83598. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  83599. if( pTabList->a[j].iCursor==p->iTable ) break;
  83600. }
  83601. assert( j<pTabList->nSrc );
  83602. pTab = pTabList->a[j].pTab;
  83603. if( iCol<0 ) iCol = pTab->iPKey;
  83604. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  83605. if( iCol<0 ){
  83606. zCol = "rowid";
  83607. }else{
  83608. zCol = pTab->aCol[iCol].zName;
  83609. }
  83610. if( !shortNames && !fullNames ){
  83611. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  83612. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  83613. }else if( fullNames ){
  83614. char *zName = 0;
  83615. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  83616. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  83617. }else{
  83618. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  83619. }
  83620. }else{
  83621. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  83622. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  83623. }
  83624. }
  83625. generateColumnTypes(pParse, pTabList, pEList);
  83626. }
  83627. /*
  83628. ** Given a an expression list (which is really the list of expressions
  83629. ** that form the result set of a SELECT statement) compute appropriate
  83630. ** column names for a table that would hold the expression list.
  83631. **
  83632. ** All column names will be unique.
  83633. **
  83634. ** Only the column names are computed. Column.zType, Column.zColl,
  83635. ** and other fields of Column are zeroed.
  83636. **
  83637. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  83638. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  83639. */
  83640. static int selectColumnsFromExprList(
  83641. Parse *pParse, /* Parsing context */
  83642. ExprList *pEList, /* Expr list from which to derive column names */
  83643. i16 *pnCol, /* Write the number of columns here */
  83644. Column **paCol /* Write the new column list here */
  83645. ){
  83646. sqlite3 *db = pParse->db; /* Database connection */
  83647. int i, j; /* Loop counters */
  83648. int cnt; /* Index added to make the name unique */
  83649. Column *aCol, *pCol; /* For looping over result columns */
  83650. int nCol; /* Number of columns in the result set */
  83651. Expr *p; /* Expression for a single result column */
  83652. char *zName; /* Column name */
  83653. int nName; /* Size of name in zName[] */
  83654. if( pEList ){
  83655. nCol = pEList->nExpr;
  83656. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  83657. testcase( aCol==0 );
  83658. }else{
  83659. nCol = 0;
  83660. aCol = 0;
  83661. }
  83662. *pnCol = nCol;
  83663. *paCol = aCol;
  83664. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  83665. /* Get an appropriate name for the column
  83666. */
  83667. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  83668. if( (zName = pEList->a[i].zName)!=0 ){
  83669. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  83670. zName = sqlite3DbStrDup(db, zName);
  83671. }else{
  83672. Expr *pColExpr = p; /* The expression that is the result column name */
  83673. Table *pTab; /* Table associated with this expression */
  83674. while( pColExpr->op==TK_DOT ){
  83675. pColExpr = pColExpr->pRight;
  83676. assert( pColExpr!=0 );
  83677. }
  83678. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  83679. /* For columns use the column name name */
  83680. int iCol = pColExpr->iColumn;
  83681. pTab = pColExpr->pTab;
  83682. if( iCol<0 ) iCol = pTab->iPKey;
  83683. zName = sqlite3MPrintf(db, "%s",
  83684. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  83685. }else if( pColExpr->op==TK_ID ){
  83686. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  83687. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  83688. }else{
  83689. /* Use the original text of the column expression as its name */
  83690. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  83691. }
  83692. }
  83693. if( db->mallocFailed ){
  83694. sqlite3DbFree(db, zName);
  83695. break;
  83696. }
  83697. /* Make sure the column name is unique. If the name is not unique,
  83698. ** append a integer to the name so that it becomes unique.
  83699. */
  83700. nName = sqlite3Strlen30(zName);
  83701. for(j=cnt=0; j<i; j++){
  83702. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  83703. char *zNewName;
  83704. int k;
  83705. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  83706. if( zName[k]==':' ) nName = k;
  83707. zName[nName] = 0;
  83708. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  83709. sqlite3DbFree(db, zName);
  83710. zName = zNewName;
  83711. j = -1;
  83712. if( zName==0 ) break;
  83713. }
  83714. }
  83715. pCol->zName = zName;
  83716. }
  83717. if( db->mallocFailed ){
  83718. for(j=0; j<i; j++){
  83719. sqlite3DbFree(db, aCol[j].zName);
  83720. }
  83721. sqlite3DbFree(db, aCol);
  83722. *paCol = 0;
  83723. *pnCol = 0;
  83724. return SQLITE_NOMEM;
  83725. }
  83726. return SQLITE_OK;
  83727. }
  83728. /*
  83729. ** Add type and collation information to a column list based on
  83730. ** a SELECT statement.
  83731. **
  83732. ** The column list presumably came from selectColumnNamesFromExprList().
  83733. ** The column list has only names, not types or collations. This
  83734. ** routine goes through and adds the types and collations.
  83735. **
  83736. ** This routine requires that all identifiers in the SELECT
  83737. ** statement be resolved.
  83738. */
  83739. static void selectAddColumnTypeAndCollation(
  83740. Parse *pParse, /* Parsing contexts */
  83741. Table *pTab, /* Add column type information to this table */
  83742. Select *pSelect /* SELECT used to determine types and collations */
  83743. ){
  83744. sqlite3 *db = pParse->db;
  83745. NameContext sNC;
  83746. Column *pCol;
  83747. CollSeq *pColl;
  83748. int i;
  83749. Expr *p;
  83750. struct ExprList_item *a;
  83751. u64 szAll = 0;
  83752. assert( pSelect!=0 );
  83753. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  83754. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  83755. if( db->mallocFailed ) return;
  83756. memset(&sNC, 0, sizeof(sNC));
  83757. sNC.pSrcList = pSelect->pSrc;
  83758. a = pSelect->pEList->a;
  83759. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  83760. p = a[i].pExpr;
  83761. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  83762. szAll += pCol->szEst;
  83763. pCol->affinity = sqlite3ExprAffinity(p);
  83764. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  83765. pColl = sqlite3ExprCollSeq(pParse, p);
  83766. if( pColl ){
  83767. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  83768. }
  83769. }
  83770. pTab->szTabRow = sqlite3LogEst(szAll*4);
  83771. }
  83772. /*
  83773. ** Given a SELECT statement, generate a Table structure that describes
  83774. ** the result set of that SELECT.
  83775. */
  83776. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  83777. Table *pTab;
  83778. sqlite3 *db = pParse->db;
  83779. int savedFlags;
  83780. savedFlags = db->flags;
  83781. db->flags &= ~SQLITE_FullColNames;
  83782. db->flags |= SQLITE_ShortColNames;
  83783. sqlite3SelectPrep(pParse, pSelect, 0);
  83784. if( pParse->nErr ) return 0;
  83785. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  83786. db->flags = savedFlags;
  83787. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  83788. if( pTab==0 ){
  83789. return 0;
  83790. }
  83791. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  83792. ** is disabled */
  83793. assert( db->lookaside.bEnabled==0 );
  83794. pTab->nRef = 1;
  83795. pTab->zName = 0;
  83796. pTab->nRowEst = 1048576;
  83797. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  83798. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  83799. pTab->iPKey = -1;
  83800. if( db->mallocFailed ){
  83801. sqlite3DeleteTable(db, pTab);
  83802. return 0;
  83803. }
  83804. return pTab;
  83805. }
  83806. /*
  83807. ** Get a VDBE for the given parser context. Create a new one if necessary.
  83808. ** If an error occurs, return NULL and leave a message in pParse.
  83809. */
  83810. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  83811. Vdbe *v = pParse->pVdbe;
  83812. if( v==0 ){
  83813. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  83814. #ifndef SQLITE_OMIT_TRACE
  83815. if( v ){
  83816. sqlite3VdbeAddOp0(v, OP_Trace);
  83817. }
  83818. #endif
  83819. }
  83820. return v;
  83821. }
  83822. /*
  83823. ** Compute the iLimit and iOffset fields of the SELECT based on the
  83824. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  83825. ** that appear in the original SQL statement after the LIMIT and OFFSET
  83826. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  83827. ** are the integer memory register numbers for counters used to compute
  83828. ** the limit and offset. If there is no limit and/or offset, then
  83829. ** iLimit and iOffset are negative.
  83830. **
  83831. ** This routine changes the values of iLimit and iOffset only if
  83832. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  83833. ** iOffset should have been preset to appropriate default values
  83834. ** (usually but not always -1) prior to calling this routine.
  83835. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  83836. ** redefined. The UNION ALL operator uses this property to force
  83837. ** the reuse of the same limit and offset registers across multiple
  83838. ** SELECT statements.
  83839. */
  83840. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  83841. Vdbe *v = 0;
  83842. int iLimit = 0;
  83843. int iOffset;
  83844. int addr1, n;
  83845. if( p->iLimit ) return;
  83846. /*
  83847. ** "LIMIT -1" always shows all rows. There is some
  83848. ** controversy about what the correct behavior should be.
  83849. ** The current implementation interprets "LIMIT 0" to mean
  83850. ** no rows.
  83851. */
  83852. sqlite3ExprCacheClear(pParse);
  83853. assert( p->pOffset==0 || p->pLimit!=0 );
  83854. if( p->pLimit ){
  83855. p->iLimit = iLimit = ++pParse->nMem;
  83856. v = sqlite3GetVdbe(pParse);
  83857. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  83858. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  83859. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  83860. VdbeComment((v, "LIMIT counter"));
  83861. if( n==0 ){
  83862. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  83863. }else if( n>=0 && p->nSelectRow>(u64)n ){
  83864. p->nSelectRow = n;
  83865. }
  83866. }else{
  83867. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  83868. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  83869. VdbeComment((v, "LIMIT counter"));
  83870. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  83871. }
  83872. if( p->pOffset ){
  83873. p->iOffset = iOffset = ++pParse->nMem;
  83874. pParse->nMem++; /* Allocate an extra register for limit+offset */
  83875. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  83876. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  83877. VdbeComment((v, "OFFSET counter"));
  83878. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  83879. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  83880. sqlite3VdbeJumpHere(v, addr1);
  83881. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  83882. VdbeComment((v, "LIMIT+OFFSET"));
  83883. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  83884. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  83885. sqlite3VdbeJumpHere(v, addr1);
  83886. }
  83887. }
  83888. }
  83889. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83890. /*
  83891. ** Return the appropriate collating sequence for the iCol-th column of
  83892. ** the result set for the compound-select statement "p". Return NULL if
  83893. ** the column has no default collating sequence.
  83894. **
  83895. ** The collating sequence for the compound select is taken from the
  83896. ** left-most term of the select that has a collating sequence.
  83897. */
  83898. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  83899. CollSeq *pRet;
  83900. if( p->pPrior ){
  83901. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  83902. }else{
  83903. pRet = 0;
  83904. }
  83905. assert( iCol>=0 );
  83906. if( pRet==0 && iCol<p->pEList->nExpr ){
  83907. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  83908. }
  83909. return pRet;
  83910. }
  83911. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  83912. /* Forward reference */
  83913. static int multiSelectOrderBy(
  83914. Parse *pParse, /* Parsing context */
  83915. Select *p, /* The right-most of SELECTs to be coded */
  83916. SelectDest *pDest /* What to do with query results */
  83917. );
  83918. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  83919. /*
  83920. ** This routine is called to process a compound query form from
  83921. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  83922. ** INTERSECT
  83923. **
  83924. ** "p" points to the right-most of the two queries. the query on the
  83925. ** left is p->pPrior. The left query could also be a compound query
  83926. ** in which case this routine will be called recursively.
  83927. **
  83928. ** The results of the total query are to be written into a destination
  83929. ** of type eDest with parameter iParm.
  83930. **
  83931. ** Example 1: Consider a three-way compound SQL statement.
  83932. **
  83933. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  83934. **
  83935. ** This statement is parsed up as follows:
  83936. **
  83937. ** SELECT c FROM t3
  83938. ** |
  83939. ** `-----> SELECT b FROM t2
  83940. ** |
  83941. ** `------> SELECT a FROM t1
  83942. **
  83943. ** The arrows in the diagram above represent the Select.pPrior pointer.
  83944. ** So if this routine is called with p equal to the t3 query, then
  83945. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  83946. **
  83947. ** Notice that because of the way SQLite parses compound SELECTs, the
  83948. ** individual selects always group from left to right.
  83949. */
  83950. static int multiSelect(
  83951. Parse *pParse, /* Parsing context */
  83952. Select *p, /* The right-most of SELECTs to be coded */
  83953. SelectDest *pDest /* What to do with query results */
  83954. ){
  83955. int rc = SQLITE_OK; /* Success code from a subroutine */
  83956. Select *pPrior; /* Another SELECT immediately to our left */
  83957. Vdbe *v; /* Generate code to this VDBE */
  83958. SelectDest dest; /* Alternative data destination */
  83959. Select *pDelete = 0; /* Chain of simple selects to delete */
  83960. sqlite3 *db; /* Database connection */
  83961. #ifndef SQLITE_OMIT_EXPLAIN
  83962. int iSub1; /* EQP id of left-hand query */
  83963. int iSub2; /* EQP id of right-hand query */
  83964. #endif
  83965. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  83966. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  83967. */
  83968. assert( p && p->pPrior ); /* Calling function guarantees this much */
  83969. db = pParse->db;
  83970. pPrior = p->pPrior;
  83971. assert( pPrior->pRightmost!=pPrior );
  83972. assert( pPrior->pRightmost==p->pRightmost );
  83973. dest = *pDest;
  83974. if( pPrior->pOrderBy ){
  83975. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  83976. selectOpName(p->op));
  83977. rc = 1;
  83978. goto multi_select_end;
  83979. }
  83980. if( pPrior->pLimit ){
  83981. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  83982. selectOpName(p->op));
  83983. rc = 1;
  83984. goto multi_select_end;
  83985. }
  83986. v = sqlite3GetVdbe(pParse);
  83987. assert( v!=0 ); /* The VDBE already created by calling function */
  83988. /* Create the destination temporary table if necessary
  83989. */
  83990. if( dest.eDest==SRT_EphemTab ){
  83991. assert( p->pEList );
  83992. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  83993. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  83994. dest.eDest = SRT_Table;
  83995. }
  83996. /* Make sure all SELECTs in the statement have the same number of elements
  83997. ** in their result sets.
  83998. */
  83999. assert( p->pEList && pPrior->pEList );
  84000. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  84001. if( p->selFlags & SF_Values ){
  84002. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  84003. }else{
  84004. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  84005. " do not have the same number of result columns", selectOpName(p->op));
  84006. }
  84007. rc = 1;
  84008. goto multi_select_end;
  84009. }
  84010. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  84011. */
  84012. if( p->pOrderBy ){
  84013. return multiSelectOrderBy(pParse, p, pDest);
  84014. }
  84015. /* Generate code for the left and right SELECT statements.
  84016. */
  84017. switch( p->op ){
  84018. case TK_ALL: {
  84019. int addr = 0;
  84020. int nLimit;
  84021. assert( !pPrior->pLimit );
  84022. pPrior->iLimit = p->iLimit;
  84023. pPrior->iOffset = p->iOffset;
  84024. pPrior->pLimit = p->pLimit;
  84025. pPrior->pOffset = p->pOffset;
  84026. explainSetInteger(iSub1, pParse->iNextSelectId);
  84027. rc = sqlite3Select(pParse, pPrior, &dest);
  84028. p->pLimit = 0;
  84029. p->pOffset = 0;
  84030. if( rc ){
  84031. goto multi_select_end;
  84032. }
  84033. p->pPrior = 0;
  84034. p->iLimit = pPrior->iLimit;
  84035. p->iOffset = pPrior->iOffset;
  84036. if( p->iLimit ){
  84037. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  84038. VdbeComment((v, "Jump ahead if LIMIT reached"));
  84039. }
  84040. explainSetInteger(iSub2, pParse->iNextSelectId);
  84041. rc = sqlite3Select(pParse, p, &dest);
  84042. testcase( rc!=SQLITE_OK );
  84043. pDelete = p->pPrior;
  84044. p->pPrior = pPrior;
  84045. p->nSelectRow += pPrior->nSelectRow;
  84046. if( pPrior->pLimit
  84047. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  84048. && nLimit>0 && p->nSelectRow > (u64)nLimit
  84049. ){
  84050. p->nSelectRow = nLimit;
  84051. }
  84052. if( addr ){
  84053. sqlite3VdbeJumpHere(v, addr);
  84054. }
  84055. break;
  84056. }
  84057. case TK_EXCEPT:
  84058. case TK_UNION: {
  84059. int unionTab; /* Cursor number of the temporary table holding result */
  84060. u8 op = 0; /* One of the SRT_ operations to apply to self */
  84061. int priorOp; /* The SRT_ operation to apply to prior selects */
  84062. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  84063. int addr;
  84064. SelectDest uniondest;
  84065. testcase( p->op==TK_EXCEPT );
  84066. testcase( p->op==TK_UNION );
  84067. priorOp = SRT_Union;
  84068. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  84069. /* We can reuse a temporary table generated by a SELECT to our
  84070. ** right.
  84071. */
  84072. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  84073. ** of a 3-way or more compound */
  84074. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  84075. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  84076. unionTab = dest.iSDParm;
  84077. }else{
  84078. /* We will need to create our own temporary table to hold the
  84079. ** intermediate results.
  84080. */
  84081. unionTab = pParse->nTab++;
  84082. assert( p->pOrderBy==0 );
  84083. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  84084. assert( p->addrOpenEphm[0] == -1 );
  84085. p->addrOpenEphm[0] = addr;
  84086. p->pRightmost->selFlags |= SF_UsesEphemeral;
  84087. assert( p->pEList );
  84088. }
  84089. /* Code the SELECT statements to our left
  84090. */
  84091. assert( !pPrior->pOrderBy );
  84092. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  84093. explainSetInteger(iSub1, pParse->iNextSelectId);
  84094. rc = sqlite3Select(pParse, pPrior, &uniondest);
  84095. if( rc ){
  84096. goto multi_select_end;
  84097. }
  84098. /* Code the current SELECT statement
  84099. */
  84100. if( p->op==TK_EXCEPT ){
  84101. op = SRT_Except;
  84102. }else{
  84103. assert( p->op==TK_UNION );
  84104. op = SRT_Union;
  84105. }
  84106. p->pPrior = 0;
  84107. pLimit = p->pLimit;
  84108. p->pLimit = 0;
  84109. pOffset = p->pOffset;
  84110. p->pOffset = 0;
  84111. uniondest.eDest = op;
  84112. explainSetInteger(iSub2, pParse->iNextSelectId);
  84113. rc = sqlite3Select(pParse, p, &uniondest);
  84114. testcase( rc!=SQLITE_OK );
  84115. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  84116. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  84117. sqlite3ExprListDelete(db, p->pOrderBy);
  84118. pDelete = p->pPrior;
  84119. p->pPrior = pPrior;
  84120. p->pOrderBy = 0;
  84121. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  84122. sqlite3ExprDelete(db, p->pLimit);
  84123. p->pLimit = pLimit;
  84124. p->pOffset = pOffset;
  84125. p->iLimit = 0;
  84126. p->iOffset = 0;
  84127. /* Convert the data in the temporary table into whatever form
  84128. ** it is that we currently need.
  84129. */
  84130. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  84131. if( dest.eDest!=priorOp ){
  84132. int iCont, iBreak, iStart;
  84133. assert( p->pEList );
  84134. if( dest.eDest==SRT_Output ){
  84135. Select *pFirst = p;
  84136. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84137. generateColumnNames(pParse, 0, pFirst->pEList);
  84138. }
  84139. iBreak = sqlite3VdbeMakeLabel(v);
  84140. iCont = sqlite3VdbeMakeLabel(v);
  84141. computeLimitRegisters(pParse, p, iBreak);
  84142. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  84143. iStart = sqlite3VdbeCurrentAddr(v);
  84144. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  84145. 0, 0, &dest, iCont, iBreak);
  84146. sqlite3VdbeResolveLabel(v, iCont);
  84147. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  84148. sqlite3VdbeResolveLabel(v, iBreak);
  84149. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  84150. }
  84151. break;
  84152. }
  84153. default: assert( p->op==TK_INTERSECT ); {
  84154. int tab1, tab2;
  84155. int iCont, iBreak, iStart;
  84156. Expr *pLimit, *pOffset;
  84157. int addr;
  84158. SelectDest intersectdest;
  84159. int r1;
  84160. /* INTERSECT is different from the others since it requires
  84161. ** two temporary tables. Hence it has its own case. Begin
  84162. ** by allocating the tables we will need.
  84163. */
  84164. tab1 = pParse->nTab++;
  84165. tab2 = pParse->nTab++;
  84166. assert( p->pOrderBy==0 );
  84167. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  84168. assert( p->addrOpenEphm[0] == -1 );
  84169. p->addrOpenEphm[0] = addr;
  84170. p->pRightmost->selFlags |= SF_UsesEphemeral;
  84171. assert( p->pEList );
  84172. /* Code the SELECTs to our left into temporary table "tab1".
  84173. */
  84174. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  84175. explainSetInteger(iSub1, pParse->iNextSelectId);
  84176. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  84177. if( rc ){
  84178. goto multi_select_end;
  84179. }
  84180. /* Code the current SELECT into temporary table "tab2"
  84181. */
  84182. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  84183. assert( p->addrOpenEphm[1] == -1 );
  84184. p->addrOpenEphm[1] = addr;
  84185. p->pPrior = 0;
  84186. pLimit = p->pLimit;
  84187. p->pLimit = 0;
  84188. pOffset = p->pOffset;
  84189. p->pOffset = 0;
  84190. intersectdest.iSDParm = tab2;
  84191. explainSetInteger(iSub2, pParse->iNextSelectId);
  84192. rc = sqlite3Select(pParse, p, &intersectdest);
  84193. testcase( rc!=SQLITE_OK );
  84194. pDelete = p->pPrior;
  84195. p->pPrior = pPrior;
  84196. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  84197. sqlite3ExprDelete(db, p->pLimit);
  84198. p->pLimit = pLimit;
  84199. p->pOffset = pOffset;
  84200. /* Generate code to take the intersection of the two temporary
  84201. ** tables.
  84202. */
  84203. assert( p->pEList );
  84204. if( dest.eDest==SRT_Output ){
  84205. Select *pFirst = p;
  84206. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84207. generateColumnNames(pParse, 0, pFirst->pEList);
  84208. }
  84209. iBreak = sqlite3VdbeMakeLabel(v);
  84210. iCont = sqlite3VdbeMakeLabel(v);
  84211. computeLimitRegisters(pParse, p, iBreak);
  84212. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  84213. r1 = sqlite3GetTempReg(pParse);
  84214. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  84215. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  84216. sqlite3ReleaseTempReg(pParse, r1);
  84217. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  84218. 0, 0, &dest, iCont, iBreak);
  84219. sqlite3VdbeResolveLabel(v, iCont);
  84220. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  84221. sqlite3VdbeResolveLabel(v, iBreak);
  84222. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  84223. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  84224. break;
  84225. }
  84226. }
  84227. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  84228. /* Compute collating sequences used by
  84229. ** temporary tables needed to implement the compound select.
  84230. ** Attach the KeyInfo structure to all temporary tables.
  84231. **
  84232. ** This section is run by the right-most SELECT statement only.
  84233. ** SELECT statements to the left always skip this part. The right-most
  84234. ** SELECT might also skip this part if it has no ORDER BY clause and
  84235. ** no temp tables are required.
  84236. */
  84237. if( p->selFlags & SF_UsesEphemeral ){
  84238. int i; /* Loop counter */
  84239. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  84240. Select *pLoop; /* For looping through SELECT statements */
  84241. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  84242. int nCol; /* Number of columns in result set */
  84243. assert( p->pRightmost==p );
  84244. nCol = p->pEList->nExpr;
  84245. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  84246. if( !pKeyInfo ){
  84247. rc = SQLITE_NOMEM;
  84248. goto multi_select_end;
  84249. }
  84250. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  84251. *apColl = multiSelectCollSeq(pParse, p, i);
  84252. if( 0==*apColl ){
  84253. *apColl = db->pDfltColl;
  84254. }
  84255. }
  84256. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  84257. for(i=0; i<2; i++){
  84258. int addr = pLoop->addrOpenEphm[i];
  84259. if( addr<0 ){
  84260. /* If [0] is unused then [1] is also unused. So we can
  84261. ** always safely abort as soon as the first unused slot is found */
  84262. assert( pLoop->addrOpenEphm[1]<0 );
  84263. break;
  84264. }
  84265. sqlite3VdbeChangeP2(v, addr, nCol);
  84266. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  84267. pLoop->addrOpenEphm[i] = -1;
  84268. }
  84269. }
  84270. sqlite3DbFree(db, pKeyInfo);
  84271. }
  84272. multi_select_end:
  84273. pDest->iSdst = dest.iSdst;
  84274. pDest->nSdst = dest.nSdst;
  84275. sqlite3SelectDelete(db, pDelete);
  84276. return rc;
  84277. }
  84278. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  84279. /*
  84280. ** Code an output subroutine for a coroutine implementation of a
  84281. ** SELECT statment.
  84282. **
  84283. ** The data to be output is contained in pIn->iSdst. There are
  84284. ** pIn->nSdst columns to be output. pDest is where the output should
  84285. ** be sent.
  84286. **
  84287. ** regReturn is the number of the register holding the subroutine
  84288. ** return address.
  84289. **
  84290. ** If regPrev>0 then it is the first register in a vector that
  84291. ** records the previous output. mem[regPrev] is a flag that is false
  84292. ** if there has been no previous output. If regPrev>0 then code is
  84293. ** generated to suppress duplicates. pKeyInfo is used for comparing
  84294. ** keys.
  84295. **
  84296. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  84297. ** iBreak.
  84298. */
  84299. static int generateOutputSubroutine(
  84300. Parse *pParse, /* Parsing context */
  84301. Select *p, /* The SELECT statement */
  84302. SelectDest *pIn, /* Coroutine supplying data */
  84303. SelectDest *pDest, /* Where to send the data */
  84304. int regReturn, /* The return address register */
  84305. int regPrev, /* Previous result register. No uniqueness if 0 */
  84306. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  84307. int p4type, /* The p4 type for pKeyInfo */
  84308. int iBreak /* Jump here if we hit the LIMIT */
  84309. ){
  84310. Vdbe *v = pParse->pVdbe;
  84311. int iContinue;
  84312. int addr;
  84313. addr = sqlite3VdbeCurrentAddr(v);
  84314. iContinue = sqlite3VdbeMakeLabel(v);
  84315. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  84316. */
  84317. if( regPrev ){
  84318. int j1, j2;
  84319. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  84320. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  84321. (char*)pKeyInfo, p4type);
  84322. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  84323. sqlite3VdbeJumpHere(v, j1);
  84324. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  84325. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  84326. }
  84327. if( pParse->db->mallocFailed ) return 0;
  84328. /* Suppress the first OFFSET entries if there is an OFFSET clause
  84329. */
  84330. codeOffset(v, p, iContinue);
  84331. switch( pDest->eDest ){
  84332. /* Store the result as data using a unique key.
  84333. */
  84334. case SRT_Table:
  84335. case SRT_EphemTab: {
  84336. int r1 = sqlite3GetTempReg(pParse);
  84337. int r2 = sqlite3GetTempReg(pParse);
  84338. testcase( pDest->eDest==SRT_Table );
  84339. testcase( pDest->eDest==SRT_EphemTab );
  84340. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  84341. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  84342. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  84343. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84344. sqlite3ReleaseTempReg(pParse, r2);
  84345. sqlite3ReleaseTempReg(pParse, r1);
  84346. break;
  84347. }
  84348. #ifndef SQLITE_OMIT_SUBQUERY
  84349. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  84350. ** then there should be a single item on the stack. Write this
  84351. ** item into the set table with bogus data.
  84352. */
  84353. case SRT_Set: {
  84354. int r1;
  84355. assert( pIn->nSdst==1 );
  84356. pDest->affSdst =
  84357. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  84358. r1 = sqlite3GetTempReg(pParse);
  84359. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  84360. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  84361. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  84362. sqlite3ReleaseTempReg(pParse, r1);
  84363. break;
  84364. }
  84365. #if 0 /* Never occurs on an ORDER BY query */
  84366. /* If any row exist in the result set, record that fact and abort.
  84367. */
  84368. case SRT_Exists: {
  84369. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  84370. /* The LIMIT clause will terminate the loop for us */
  84371. break;
  84372. }
  84373. #endif
  84374. /* If this is a scalar select that is part of an expression, then
  84375. ** store the results in the appropriate memory cell and break out
  84376. ** of the scan loop.
  84377. */
  84378. case SRT_Mem: {
  84379. assert( pIn->nSdst==1 );
  84380. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  84381. /* The LIMIT clause will jump out of the loop for us */
  84382. break;
  84383. }
  84384. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  84385. /* The results are stored in a sequence of registers
  84386. ** starting at pDest->iSdst. Then the co-routine yields.
  84387. */
  84388. case SRT_Coroutine: {
  84389. if( pDest->iSdst==0 ){
  84390. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  84391. pDest->nSdst = pIn->nSdst;
  84392. }
  84393. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  84394. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  84395. break;
  84396. }
  84397. /* If none of the above, then the result destination must be
  84398. ** SRT_Output. This routine is never called with any other
  84399. ** destination other than the ones handled above or SRT_Output.
  84400. **
  84401. ** For SRT_Output, results are stored in a sequence of registers.
  84402. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  84403. ** return the next row of result.
  84404. */
  84405. default: {
  84406. assert( pDest->eDest==SRT_Output );
  84407. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  84408. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  84409. break;
  84410. }
  84411. }
  84412. /* Jump to the end of the loop if the LIMIT is reached.
  84413. */
  84414. if( p->iLimit ){
  84415. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  84416. }
  84417. /* Generate the subroutine return
  84418. */
  84419. sqlite3VdbeResolveLabel(v, iContinue);
  84420. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  84421. return addr;
  84422. }
  84423. /*
  84424. ** Alternative compound select code generator for cases when there
  84425. ** is an ORDER BY clause.
  84426. **
  84427. ** We assume a query of the following form:
  84428. **
  84429. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  84430. **
  84431. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  84432. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  84433. ** co-routines. Then run the co-routines in parallel and merge the results
  84434. ** into the output. In addition to the two coroutines (called selectA and
  84435. ** selectB) there are 7 subroutines:
  84436. **
  84437. ** outA: Move the output of the selectA coroutine into the output
  84438. ** of the compound query.
  84439. **
  84440. ** outB: Move the output of the selectB coroutine into the output
  84441. ** of the compound query. (Only generated for UNION and
  84442. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  84443. ** appears only in B.)
  84444. **
  84445. ** AltB: Called when there is data from both coroutines and A<B.
  84446. **
  84447. ** AeqB: Called when there is data from both coroutines and A==B.
  84448. **
  84449. ** AgtB: Called when there is data from both coroutines and A>B.
  84450. **
  84451. ** EofA: Called when data is exhausted from selectA.
  84452. **
  84453. ** EofB: Called when data is exhausted from selectB.
  84454. **
  84455. ** The implementation of the latter five subroutines depend on which
  84456. ** <operator> is used:
  84457. **
  84458. **
  84459. ** UNION ALL UNION EXCEPT INTERSECT
  84460. ** ------------- ----------------- -------------- -----------------
  84461. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  84462. **
  84463. ** AeqB: outA, nextA nextA nextA outA, nextA
  84464. **
  84465. ** AgtB: outB, nextB outB, nextB nextB nextB
  84466. **
  84467. ** EofA: outB, nextB outB, nextB halt halt
  84468. **
  84469. ** EofB: outA, nextA outA, nextA outA, nextA halt
  84470. **
  84471. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  84472. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  84473. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  84474. ** following nextX causes a jump to the end of the select processing.
  84475. **
  84476. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  84477. ** within the output subroutine. The regPrev register set holds the previously
  84478. ** output value. A comparison is made against this value and the output
  84479. ** is skipped if the next results would be the same as the previous.
  84480. **
  84481. ** The implementation plan is to implement the two coroutines and seven
  84482. ** subroutines first, then put the control logic at the bottom. Like this:
  84483. **
  84484. ** goto Init
  84485. ** coA: coroutine for left query (A)
  84486. ** coB: coroutine for right query (B)
  84487. ** outA: output one row of A
  84488. ** outB: output one row of B (UNION and UNION ALL only)
  84489. ** EofA: ...
  84490. ** EofB: ...
  84491. ** AltB: ...
  84492. ** AeqB: ...
  84493. ** AgtB: ...
  84494. ** Init: initialize coroutine registers
  84495. ** yield coA
  84496. ** if eof(A) goto EofA
  84497. ** yield coB
  84498. ** if eof(B) goto EofB
  84499. ** Cmpr: Compare A, B
  84500. ** Jump AltB, AeqB, AgtB
  84501. ** End: ...
  84502. **
  84503. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  84504. ** actually called using Gosub and they do not Return. EofA and EofB loop
  84505. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  84506. ** and AgtB jump to either L2 or to one of EofA or EofB.
  84507. */
  84508. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  84509. static int multiSelectOrderBy(
  84510. Parse *pParse, /* Parsing context */
  84511. Select *p, /* The right-most of SELECTs to be coded */
  84512. SelectDest *pDest /* What to do with query results */
  84513. ){
  84514. int i, j; /* Loop counters */
  84515. Select *pPrior; /* Another SELECT immediately to our left */
  84516. Vdbe *v; /* Generate code to this VDBE */
  84517. SelectDest destA; /* Destination for coroutine A */
  84518. SelectDest destB; /* Destination for coroutine B */
  84519. int regAddrA; /* Address register for select-A coroutine */
  84520. int regEofA; /* Flag to indicate when select-A is complete */
  84521. int regAddrB; /* Address register for select-B coroutine */
  84522. int regEofB; /* Flag to indicate when select-B is complete */
  84523. int addrSelectA; /* Address of the select-A coroutine */
  84524. int addrSelectB; /* Address of the select-B coroutine */
  84525. int regOutA; /* Address register for the output-A subroutine */
  84526. int regOutB; /* Address register for the output-B subroutine */
  84527. int addrOutA; /* Address of the output-A subroutine */
  84528. int addrOutB = 0; /* Address of the output-B subroutine */
  84529. int addrEofA; /* Address of the select-A-exhausted subroutine */
  84530. int addrEofB; /* Address of the select-B-exhausted subroutine */
  84531. int addrAltB; /* Address of the A<B subroutine */
  84532. int addrAeqB; /* Address of the A==B subroutine */
  84533. int addrAgtB; /* Address of the A>B subroutine */
  84534. int regLimitA; /* Limit register for select-A */
  84535. int regLimitB; /* Limit register for select-A */
  84536. int regPrev; /* A range of registers to hold previous output */
  84537. int savedLimit; /* Saved value of p->iLimit */
  84538. int savedOffset; /* Saved value of p->iOffset */
  84539. int labelCmpr; /* Label for the start of the merge algorithm */
  84540. int labelEnd; /* Label for the end of the overall SELECT stmt */
  84541. int j1; /* Jump instructions that get retargetted */
  84542. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  84543. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  84544. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  84545. sqlite3 *db; /* Database connection */
  84546. ExprList *pOrderBy; /* The ORDER BY clause */
  84547. int nOrderBy; /* Number of terms in the ORDER BY clause */
  84548. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  84549. #ifndef SQLITE_OMIT_EXPLAIN
  84550. int iSub1; /* EQP id of left-hand query */
  84551. int iSub2; /* EQP id of right-hand query */
  84552. #endif
  84553. assert( p->pOrderBy!=0 );
  84554. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  84555. db = pParse->db;
  84556. v = pParse->pVdbe;
  84557. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  84558. labelEnd = sqlite3VdbeMakeLabel(v);
  84559. labelCmpr = sqlite3VdbeMakeLabel(v);
  84560. /* Patch up the ORDER BY clause
  84561. */
  84562. op = p->op;
  84563. pPrior = p->pPrior;
  84564. assert( pPrior->pOrderBy==0 );
  84565. pOrderBy = p->pOrderBy;
  84566. assert( pOrderBy );
  84567. nOrderBy = pOrderBy->nExpr;
  84568. /* For operators other than UNION ALL we have to make sure that
  84569. ** the ORDER BY clause covers every term of the result set. Add
  84570. ** terms to the ORDER BY clause as necessary.
  84571. */
  84572. if( op!=TK_ALL ){
  84573. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  84574. struct ExprList_item *pItem;
  84575. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  84576. assert( pItem->iOrderByCol>0 );
  84577. if( pItem->iOrderByCol==i ) break;
  84578. }
  84579. if( j==nOrderBy ){
  84580. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  84581. if( pNew==0 ) return SQLITE_NOMEM;
  84582. pNew->flags |= EP_IntValue;
  84583. pNew->u.iValue = i;
  84584. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  84585. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  84586. }
  84587. }
  84588. }
  84589. /* Compute the comparison permutation and keyinfo that is used with
  84590. ** the permutation used to determine if the next
  84591. ** row of results comes from selectA or selectB. Also add explicit
  84592. ** collations to the ORDER BY clause terms so that when the subqueries
  84593. ** to the right and the left are evaluated, they use the correct
  84594. ** collation.
  84595. */
  84596. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  84597. if( aPermute ){
  84598. struct ExprList_item *pItem;
  84599. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  84600. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  84601. aPermute[i] = pItem->iOrderByCol - 1;
  84602. }
  84603. pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  84604. if( pKeyMerge ){
  84605. for(i=0; i<nOrderBy; i++){
  84606. CollSeq *pColl;
  84607. Expr *pTerm = pOrderBy->a[i].pExpr;
  84608. if( pTerm->flags & EP_Collate ){
  84609. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  84610. }else{
  84611. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  84612. if( pColl==0 ) pColl = db->pDfltColl;
  84613. pOrderBy->a[i].pExpr =
  84614. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  84615. }
  84616. pKeyMerge->aColl[i] = pColl;
  84617. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  84618. }
  84619. }
  84620. }else{
  84621. pKeyMerge = 0;
  84622. }
  84623. /* Reattach the ORDER BY clause to the query.
  84624. */
  84625. p->pOrderBy = pOrderBy;
  84626. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  84627. /* Allocate a range of temporary registers and the KeyInfo needed
  84628. ** for the logic that removes duplicate result rows when the
  84629. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  84630. */
  84631. if( op==TK_ALL ){
  84632. regPrev = 0;
  84633. }else{
  84634. int nExpr = p->pEList->nExpr;
  84635. assert( nOrderBy>=nExpr || db->mallocFailed );
  84636. regPrev = pParse->nMem+1;
  84637. pParse->nMem += nExpr+1;
  84638. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  84639. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  84640. if( pKeyDup ){
  84641. for(i=0; i<nExpr; i++){
  84642. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  84643. pKeyDup->aSortOrder[i] = 0;
  84644. }
  84645. }
  84646. }
  84647. /* Separate the left and the right query from one another
  84648. */
  84649. p->pPrior = 0;
  84650. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  84651. if( pPrior->pPrior==0 ){
  84652. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  84653. }
  84654. /* Compute the limit registers */
  84655. computeLimitRegisters(pParse, p, labelEnd);
  84656. if( p->iLimit && op==TK_ALL ){
  84657. regLimitA = ++pParse->nMem;
  84658. regLimitB = ++pParse->nMem;
  84659. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  84660. regLimitA);
  84661. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  84662. }else{
  84663. regLimitA = regLimitB = 0;
  84664. }
  84665. sqlite3ExprDelete(db, p->pLimit);
  84666. p->pLimit = 0;
  84667. sqlite3ExprDelete(db, p->pOffset);
  84668. p->pOffset = 0;
  84669. regAddrA = ++pParse->nMem;
  84670. regEofA = ++pParse->nMem;
  84671. regAddrB = ++pParse->nMem;
  84672. regEofB = ++pParse->nMem;
  84673. regOutA = ++pParse->nMem;
  84674. regOutB = ++pParse->nMem;
  84675. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  84676. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  84677. /* Jump past the various subroutines and coroutines to the main
  84678. ** merge loop
  84679. */
  84680. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  84681. addrSelectA = sqlite3VdbeCurrentAddr(v);
  84682. /* Generate a coroutine to evaluate the SELECT statement to the
  84683. ** left of the compound operator - the "A" select.
  84684. */
  84685. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  84686. pPrior->iLimit = regLimitA;
  84687. explainSetInteger(iSub1, pParse->iNextSelectId);
  84688. sqlite3Select(pParse, pPrior, &destA);
  84689. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  84690. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84691. VdbeNoopComment((v, "End coroutine for left SELECT"));
  84692. /* Generate a coroutine to evaluate the SELECT statement on
  84693. ** the right - the "B" select
  84694. */
  84695. addrSelectB = sqlite3VdbeCurrentAddr(v);
  84696. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  84697. savedLimit = p->iLimit;
  84698. savedOffset = p->iOffset;
  84699. p->iLimit = regLimitB;
  84700. p->iOffset = 0;
  84701. explainSetInteger(iSub2, pParse->iNextSelectId);
  84702. sqlite3Select(pParse, p, &destB);
  84703. p->iLimit = savedLimit;
  84704. p->iOffset = savedOffset;
  84705. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  84706. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84707. VdbeNoopComment((v, "End coroutine for right SELECT"));
  84708. /* Generate a subroutine that outputs the current row of the A
  84709. ** select as the next output row of the compound select.
  84710. */
  84711. VdbeNoopComment((v, "Output routine for A"));
  84712. addrOutA = generateOutputSubroutine(pParse,
  84713. p, &destA, pDest, regOutA,
  84714. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  84715. /* Generate a subroutine that outputs the current row of the B
  84716. ** select as the next output row of the compound select.
  84717. */
  84718. if( op==TK_ALL || op==TK_UNION ){
  84719. VdbeNoopComment((v, "Output routine for B"));
  84720. addrOutB = generateOutputSubroutine(pParse,
  84721. p, &destB, pDest, regOutB,
  84722. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  84723. }
  84724. /* Generate a subroutine to run when the results from select A
  84725. ** are exhausted and only data in select B remains.
  84726. */
  84727. VdbeNoopComment((v, "eof-A subroutine"));
  84728. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  84729. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  84730. }else{
  84731. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  84732. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  84733. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84734. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  84735. p->nSelectRow += pPrior->nSelectRow;
  84736. }
  84737. /* Generate a subroutine to run when the results from select B
  84738. ** are exhausted and only data in select A remains.
  84739. */
  84740. if( op==TK_INTERSECT ){
  84741. addrEofB = addrEofA;
  84742. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  84743. }else{
  84744. VdbeNoopComment((v, "eof-B subroutine"));
  84745. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  84746. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  84747. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84748. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  84749. }
  84750. /* Generate code to handle the case of A<B
  84751. */
  84752. VdbeNoopComment((v, "A-lt-B subroutine"));
  84753. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  84754. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84755. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84756. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84757. /* Generate code to handle the case of A==B
  84758. */
  84759. if( op==TK_ALL ){
  84760. addrAeqB = addrAltB;
  84761. }else if( op==TK_INTERSECT ){
  84762. addrAeqB = addrAltB;
  84763. addrAltB++;
  84764. }else{
  84765. VdbeNoopComment((v, "A-eq-B subroutine"));
  84766. addrAeqB =
  84767. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  84768. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84769. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84770. }
  84771. /* Generate code to handle the case of A>B
  84772. */
  84773. VdbeNoopComment((v, "A-gt-B subroutine"));
  84774. addrAgtB = sqlite3VdbeCurrentAddr(v);
  84775. if( op==TK_ALL || op==TK_UNION ){
  84776. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  84777. }
  84778. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  84779. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  84780. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  84781. /* This code runs once to initialize everything.
  84782. */
  84783. sqlite3VdbeJumpHere(v, j1);
  84784. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  84785. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  84786. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  84787. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  84788. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  84789. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  84790. /* Implement the main merge loop
  84791. */
  84792. sqlite3VdbeResolveLabel(v, labelCmpr);
  84793. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  84794. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  84795. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  84796. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  84797. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  84798. /* Jump to the this point in order to terminate the query.
  84799. */
  84800. sqlite3VdbeResolveLabel(v, labelEnd);
  84801. /* Set the number of output columns
  84802. */
  84803. if( pDest->eDest==SRT_Output ){
  84804. Select *pFirst = pPrior;
  84805. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  84806. generateColumnNames(pParse, 0, pFirst->pEList);
  84807. }
  84808. /* Reassembly the compound query so that it will be freed correctly
  84809. ** by the calling function */
  84810. if( p->pPrior ){
  84811. sqlite3SelectDelete(db, p->pPrior);
  84812. }
  84813. p->pPrior = pPrior;
  84814. /*** TBD: Insert subroutine calls to close cursors on incomplete
  84815. **** subqueries ****/
  84816. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  84817. return SQLITE_OK;
  84818. }
  84819. #endif
  84820. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  84821. /* Forward Declarations */
  84822. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  84823. static void substSelect(sqlite3*, Select *, int, ExprList *);
  84824. /*
  84825. ** Scan through the expression pExpr. Replace every reference to
  84826. ** a column in table number iTable with a copy of the iColumn-th
  84827. ** entry in pEList. (But leave references to the ROWID column
  84828. ** unchanged.)
  84829. **
  84830. ** This routine is part of the flattening procedure. A subquery
  84831. ** whose result set is defined by pEList appears as entry in the
  84832. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  84833. ** FORM clause entry is iTable. This routine make the necessary
  84834. ** changes to pExpr so that it refers directly to the source table
  84835. ** of the subquery rather the result set of the subquery.
  84836. */
  84837. static Expr *substExpr(
  84838. sqlite3 *db, /* Report malloc errors to this connection */
  84839. Expr *pExpr, /* Expr in which substitution occurs */
  84840. int iTable, /* Table to be substituted */
  84841. ExprList *pEList /* Substitute expressions */
  84842. ){
  84843. if( pExpr==0 ) return 0;
  84844. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  84845. if( pExpr->iColumn<0 ){
  84846. pExpr->op = TK_NULL;
  84847. }else{
  84848. Expr *pNew;
  84849. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  84850. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  84851. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  84852. sqlite3ExprDelete(db, pExpr);
  84853. pExpr = pNew;
  84854. }
  84855. }else{
  84856. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  84857. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  84858. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84859. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  84860. }else{
  84861. substExprList(db, pExpr->x.pList, iTable, pEList);
  84862. }
  84863. }
  84864. return pExpr;
  84865. }
  84866. static void substExprList(
  84867. sqlite3 *db, /* Report malloc errors here */
  84868. ExprList *pList, /* List to scan and in which to make substitutes */
  84869. int iTable, /* Table to be substituted */
  84870. ExprList *pEList /* Substitute values */
  84871. ){
  84872. int i;
  84873. if( pList==0 ) return;
  84874. for(i=0; i<pList->nExpr; i++){
  84875. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  84876. }
  84877. }
  84878. static void substSelect(
  84879. sqlite3 *db, /* Report malloc errors here */
  84880. Select *p, /* SELECT statement in which to make substitutions */
  84881. int iTable, /* Table to be replaced */
  84882. ExprList *pEList /* Substitute values */
  84883. ){
  84884. SrcList *pSrc;
  84885. struct SrcList_item *pItem;
  84886. int i;
  84887. if( !p ) return;
  84888. substExprList(db, p->pEList, iTable, pEList);
  84889. substExprList(db, p->pGroupBy, iTable, pEList);
  84890. substExprList(db, p->pOrderBy, iTable, pEList);
  84891. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  84892. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  84893. substSelect(db, p->pPrior, iTable, pEList);
  84894. pSrc = p->pSrc;
  84895. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  84896. if( ALWAYS(pSrc) ){
  84897. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  84898. substSelect(db, pItem->pSelect, iTable, pEList);
  84899. }
  84900. }
  84901. }
  84902. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  84903. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  84904. /*
  84905. ** This routine attempts to flatten subqueries as a performance optimization.
  84906. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  84907. **
  84908. ** To understand the concept of flattening, consider the following
  84909. ** query:
  84910. **
  84911. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  84912. **
  84913. ** The default way of implementing this query is to execute the
  84914. ** subquery first and store the results in a temporary table, then
  84915. ** run the outer query on that temporary table. This requires two
  84916. ** passes over the data. Furthermore, because the temporary table
  84917. ** has no indices, the WHERE clause on the outer query cannot be
  84918. ** optimized.
  84919. **
  84920. ** This routine attempts to rewrite queries such as the above into
  84921. ** a single flat select, like this:
  84922. **
  84923. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  84924. **
  84925. ** The code generated for this simpification gives the same result
  84926. ** but only has to scan the data once. And because indices might
  84927. ** exist on the table t1, a complete scan of the data might be
  84928. ** avoided.
  84929. **
  84930. ** Flattening is only attempted if all of the following are true:
  84931. **
  84932. ** (1) The subquery and the outer query do not both use aggregates.
  84933. **
  84934. ** (2) The subquery is not an aggregate or the outer query is not a join.
  84935. **
  84936. ** (3) The subquery is not the right operand of a left outer join
  84937. ** (Originally ticket #306. Strengthened by ticket #3300)
  84938. **
  84939. ** (4) The subquery is not DISTINCT.
  84940. **
  84941. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  84942. ** sub-queries that were excluded from this optimization. Restriction
  84943. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  84944. **
  84945. ** (6) The subquery does not use aggregates or the outer query is not
  84946. ** DISTINCT.
  84947. **
  84948. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  84949. ** A FROM clause, consider adding a FROM close with the special
  84950. ** table sqlite_once that consists of a single row containing a
  84951. ** single NULL.
  84952. **
  84953. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  84954. **
  84955. ** (9) The subquery does not use LIMIT or the outer query does not use
  84956. ** aggregates.
  84957. **
  84958. ** (10) The subquery does not use aggregates or the outer query does not
  84959. ** use LIMIT.
  84960. **
  84961. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  84962. **
  84963. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  84964. ** a separate restriction deriving from ticket #350.
  84965. **
  84966. ** (13) The subquery and outer query do not both use LIMIT.
  84967. **
  84968. ** (14) The subquery does not use OFFSET.
  84969. **
  84970. ** (15) The outer query is not part of a compound select or the
  84971. ** subquery does not have a LIMIT clause.
  84972. ** (See ticket #2339 and ticket [02a8e81d44]).
  84973. **
  84974. ** (16) The outer query is not an aggregate or the subquery does
  84975. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  84976. ** until we introduced the group_concat() function.
  84977. **
  84978. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  84979. ** compound clause made up entirely of non-aggregate queries, and
  84980. ** the parent query:
  84981. **
  84982. ** * is not itself part of a compound select,
  84983. ** * is not an aggregate or DISTINCT query, and
  84984. ** * is not a join
  84985. **
  84986. ** The parent and sub-query may contain WHERE clauses. Subject to
  84987. ** rules (11), (13) and (14), they may also contain ORDER BY,
  84988. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  84989. ** operator other than UNION ALL because all the other compound
  84990. ** operators have an implied DISTINCT which is disallowed by
  84991. ** restriction (4).
  84992. **
  84993. ** Also, each component of the sub-query must return the same number
  84994. ** of result columns. This is actually a requirement for any compound
  84995. ** SELECT statement, but all the code here does is make sure that no
  84996. ** such (illegal) sub-query is flattened. The caller will detect the
  84997. ** syntax error and return a detailed message.
  84998. **
  84999. ** (18) If the sub-query is a compound select, then all terms of the
  85000. ** ORDER by clause of the parent must be simple references to
  85001. ** columns of the sub-query.
  85002. **
  85003. ** (19) The subquery does not use LIMIT or the outer query does not
  85004. ** have a WHERE clause.
  85005. **
  85006. ** (20) If the sub-query is a compound select, then it must not use
  85007. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  85008. ** somewhat by saying that the terms of the ORDER BY clause must
  85009. ** appear as unmodified result columns in the outer query. But we
  85010. ** have other optimizations in mind to deal with that case.
  85011. **
  85012. ** (21) The subquery does not use LIMIT or the outer query is not
  85013. ** DISTINCT. (See ticket [752e1646fc]).
  85014. **
  85015. ** In this routine, the "p" parameter is a pointer to the outer query.
  85016. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  85017. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  85018. **
  85019. ** If flattening is not attempted, this routine is a no-op and returns 0.
  85020. ** If flattening is attempted this routine returns 1.
  85021. **
  85022. ** All of the expression analysis must occur on both the outer query and
  85023. ** the subquery before this routine runs.
  85024. */
  85025. static int flattenSubquery(
  85026. Parse *pParse, /* Parsing context */
  85027. Select *p, /* The parent or outer SELECT statement */
  85028. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  85029. int isAgg, /* True if outer SELECT uses aggregate functions */
  85030. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  85031. ){
  85032. const char *zSavedAuthContext = pParse->zAuthContext;
  85033. Select *pParent;
  85034. Select *pSub; /* The inner query or "subquery" */
  85035. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  85036. SrcList *pSrc; /* The FROM clause of the outer query */
  85037. SrcList *pSubSrc; /* The FROM clause of the subquery */
  85038. ExprList *pList; /* The result set of the outer query */
  85039. int iParent; /* VDBE cursor number of the pSub result set temp table */
  85040. int i; /* Loop counter */
  85041. Expr *pWhere; /* The WHERE clause */
  85042. struct SrcList_item *pSubitem; /* The subquery */
  85043. sqlite3 *db = pParse->db;
  85044. /* Check to see if flattening is permitted. Return 0 if not.
  85045. */
  85046. assert( p!=0 );
  85047. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  85048. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  85049. pSrc = p->pSrc;
  85050. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  85051. pSubitem = &pSrc->a[iFrom];
  85052. iParent = pSubitem->iCursor;
  85053. pSub = pSubitem->pSelect;
  85054. assert( pSub!=0 );
  85055. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  85056. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  85057. pSubSrc = pSub->pSrc;
  85058. assert( pSubSrc );
  85059. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  85060. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  85061. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  85062. ** became arbitrary expressions, we were forced to add restrictions (13)
  85063. ** and (14). */
  85064. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  85065. if( pSub->pOffset ) return 0; /* Restriction (14) */
  85066. if( p->pRightmost && pSub->pLimit ){
  85067. return 0; /* Restriction (15) */
  85068. }
  85069. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  85070. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  85071. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  85072. return 0; /* Restrictions (8)(9) */
  85073. }
  85074. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  85075. return 0; /* Restriction (6) */
  85076. }
  85077. if( p->pOrderBy && pSub->pOrderBy ){
  85078. return 0; /* Restriction (11) */
  85079. }
  85080. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  85081. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  85082. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  85083. return 0; /* Restriction (21) */
  85084. }
  85085. /* OBSOLETE COMMENT 1:
  85086. ** Restriction 3: If the subquery is a join, make sure the subquery is
  85087. ** not used as the right operand of an outer join. Examples of why this
  85088. ** is not allowed:
  85089. **
  85090. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  85091. **
  85092. ** If we flatten the above, we would get
  85093. **
  85094. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  85095. **
  85096. ** which is not at all the same thing.
  85097. **
  85098. ** OBSOLETE COMMENT 2:
  85099. ** Restriction 12: If the subquery is the right operand of a left outer
  85100. ** join, make sure the subquery has no WHERE clause.
  85101. ** An examples of why this is not allowed:
  85102. **
  85103. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  85104. **
  85105. ** If we flatten the above, we would get
  85106. **
  85107. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  85108. **
  85109. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  85110. ** effectively converts the OUTER JOIN into an INNER JOIN.
  85111. **
  85112. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  85113. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  85114. ** is fraught with danger. Best to avoid the whole thing. If the
  85115. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  85116. */
  85117. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  85118. return 0;
  85119. }
  85120. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  85121. ** use only the UNION ALL operator. And none of the simple select queries
  85122. ** that make up the compound SELECT are allowed to be aggregate or distinct
  85123. ** queries.
  85124. */
  85125. if( pSub->pPrior ){
  85126. if( pSub->pOrderBy ){
  85127. return 0; /* Restriction 20 */
  85128. }
  85129. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  85130. return 0;
  85131. }
  85132. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  85133. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  85134. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  85135. assert( pSub->pSrc!=0 );
  85136. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  85137. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  85138. || pSub1->pSrc->nSrc<1
  85139. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  85140. ){
  85141. return 0;
  85142. }
  85143. testcase( pSub1->pSrc->nSrc>1 );
  85144. }
  85145. /* Restriction 18. */
  85146. if( p->pOrderBy ){
  85147. int ii;
  85148. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  85149. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  85150. }
  85151. }
  85152. }
  85153. /***** If we reach this point, flattening is permitted. *****/
  85154. /* Authorize the subquery */
  85155. pParse->zAuthContext = pSubitem->zName;
  85156. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  85157. testcase( i==SQLITE_DENY );
  85158. pParse->zAuthContext = zSavedAuthContext;
  85159. /* If the sub-query is a compound SELECT statement, then (by restrictions
  85160. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  85161. ** be of the form:
  85162. **
  85163. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  85164. **
  85165. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  85166. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  85167. ** OFFSET clauses and joins them to the left-hand-side of the original
  85168. ** using UNION ALL operators. In this case N is the number of simple
  85169. ** select statements in the compound sub-query.
  85170. **
  85171. ** Example:
  85172. **
  85173. ** SELECT a+1 FROM (
  85174. ** SELECT x FROM tab
  85175. ** UNION ALL
  85176. ** SELECT y FROM tab
  85177. ** UNION ALL
  85178. ** SELECT abs(z*2) FROM tab2
  85179. ** ) WHERE a!=5 ORDER BY 1
  85180. **
  85181. ** Transformed into:
  85182. **
  85183. ** SELECT x+1 FROM tab WHERE x+1!=5
  85184. ** UNION ALL
  85185. ** SELECT y+1 FROM tab WHERE y+1!=5
  85186. ** UNION ALL
  85187. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  85188. ** ORDER BY 1
  85189. **
  85190. ** We call this the "compound-subquery flattening".
  85191. */
  85192. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  85193. Select *pNew;
  85194. ExprList *pOrderBy = p->pOrderBy;
  85195. Expr *pLimit = p->pLimit;
  85196. Expr *pOffset = p->pOffset;
  85197. Select *pPrior = p->pPrior;
  85198. p->pOrderBy = 0;
  85199. p->pSrc = 0;
  85200. p->pPrior = 0;
  85201. p->pLimit = 0;
  85202. p->pOffset = 0;
  85203. pNew = sqlite3SelectDup(db, p, 0);
  85204. p->pOffset = pOffset;
  85205. p->pLimit = pLimit;
  85206. p->pOrderBy = pOrderBy;
  85207. p->pSrc = pSrc;
  85208. p->op = TK_ALL;
  85209. p->pRightmost = 0;
  85210. if( pNew==0 ){
  85211. pNew = pPrior;
  85212. }else{
  85213. pNew->pPrior = pPrior;
  85214. pNew->pRightmost = 0;
  85215. }
  85216. p->pPrior = pNew;
  85217. if( db->mallocFailed ) return 1;
  85218. }
  85219. /* Begin flattening the iFrom-th entry of the FROM clause
  85220. ** in the outer query.
  85221. */
  85222. pSub = pSub1 = pSubitem->pSelect;
  85223. /* Delete the transient table structure associated with the
  85224. ** subquery
  85225. */
  85226. sqlite3DbFree(db, pSubitem->zDatabase);
  85227. sqlite3DbFree(db, pSubitem->zName);
  85228. sqlite3DbFree(db, pSubitem->zAlias);
  85229. pSubitem->zDatabase = 0;
  85230. pSubitem->zName = 0;
  85231. pSubitem->zAlias = 0;
  85232. pSubitem->pSelect = 0;
  85233. /* Defer deleting the Table object associated with the
  85234. ** subquery until code generation is
  85235. ** complete, since there may still exist Expr.pTab entries that
  85236. ** refer to the subquery even after flattening. Ticket #3346.
  85237. **
  85238. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  85239. */
  85240. if( ALWAYS(pSubitem->pTab!=0) ){
  85241. Table *pTabToDel = pSubitem->pTab;
  85242. if( pTabToDel->nRef==1 ){
  85243. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  85244. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  85245. pToplevel->pZombieTab = pTabToDel;
  85246. }else{
  85247. pTabToDel->nRef--;
  85248. }
  85249. pSubitem->pTab = 0;
  85250. }
  85251. /* The following loop runs once for each term in a compound-subquery
  85252. ** flattening (as described above). If we are doing a different kind
  85253. ** of flattening - a flattening other than a compound-subquery flattening -
  85254. ** then this loop only runs once.
  85255. **
  85256. ** This loop moves all of the FROM elements of the subquery into the
  85257. ** the FROM clause of the outer query. Before doing this, remember
  85258. ** the cursor number for the original outer query FROM element in
  85259. ** iParent. The iParent cursor will never be used. Subsequent code
  85260. ** will scan expressions looking for iParent references and replace
  85261. ** those references with expressions that resolve to the subquery FROM
  85262. ** elements we are now copying in.
  85263. */
  85264. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  85265. int nSubSrc;
  85266. u8 jointype = 0;
  85267. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  85268. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  85269. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  85270. if( pSrc ){
  85271. assert( pParent==p ); /* First time through the loop */
  85272. jointype = pSubitem->jointype;
  85273. }else{
  85274. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  85275. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  85276. if( pSrc==0 ){
  85277. assert( db->mallocFailed );
  85278. break;
  85279. }
  85280. }
  85281. /* The subquery uses a single slot of the FROM clause of the outer
  85282. ** query. If the subquery has more than one element in its FROM clause,
  85283. ** then expand the outer query to make space for it to hold all elements
  85284. ** of the subquery.
  85285. **
  85286. ** Example:
  85287. **
  85288. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  85289. **
  85290. ** The outer query has 3 slots in its FROM clause. One slot of the
  85291. ** outer query (the middle slot) is used by the subquery. The next
  85292. ** block of code will expand the out query to 4 slots. The middle
  85293. ** slot is expanded to two slots in order to make space for the
  85294. ** two elements in the FROM clause of the subquery.
  85295. */
  85296. if( nSubSrc>1 ){
  85297. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  85298. if( db->mallocFailed ){
  85299. break;
  85300. }
  85301. }
  85302. /* Transfer the FROM clause terms from the subquery into the
  85303. ** outer query.
  85304. */
  85305. for(i=0; i<nSubSrc; i++){
  85306. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  85307. pSrc->a[i+iFrom] = pSubSrc->a[i];
  85308. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  85309. }
  85310. pSrc->a[iFrom].jointype = jointype;
  85311. /* Now begin substituting subquery result set expressions for
  85312. ** references to the iParent in the outer query.
  85313. **
  85314. ** Example:
  85315. **
  85316. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  85317. ** \ \_____________ subquery __________/ /
  85318. ** \_____________________ outer query ______________________________/
  85319. **
  85320. ** We look at every expression in the outer query and every place we see
  85321. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  85322. */
  85323. pList = pParent->pEList;
  85324. for(i=0; i<pList->nExpr; i++){
  85325. if( pList->a[i].zName==0 ){
  85326. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  85327. sqlite3Dequote(zName);
  85328. pList->a[i].zName = zName;
  85329. }
  85330. }
  85331. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  85332. if( isAgg ){
  85333. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  85334. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  85335. }
  85336. if( pSub->pOrderBy ){
  85337. assert( pParent->pOrderBy==0 );
  85338. pParent->pOrderBy = pSub->pOrderBy;
  85339. pSub->pOrderBy = 0;
  85340. }else if( pParent->pOrderBy ){
  85341. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  85342. }
  85343. if( pSub->pWhere ){
  85344. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  85345. }else{
  85346. pWhere = 0;
  85347. }
  85348. if( subqueryIsAgg ){
  85349. assert( pParent->pHaving==0 );
  85350. pParent->pHaving = pParent->pWhere;
  85351. pParent->pWhere = pWhere;
  85352. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  85353. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  85354. sqlite3ExprDup(db, pSub->pHaving, 0));
  85355. assert( pParent->pGroupBy==0 );
  85356. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  85357. }else{
  85358. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  85359. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  85360. }
  85361. /* The flattened query is distinct if either the inner or the
  85362. ** outer query is distinct.
  85363. */
  85364. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  85365. /*
  85366. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  85367. **
  85368. ** One is tempted to try to add a and b to combine the limits. But this
  85369. ** does not work if either limit is negative.
  85370. */
  85371. if( pSub->pLimit ){
  85372. pParent->pLimit = pSub->pLimit;
  85373. pSub->pLimit = 0;
  85374. }
  85375. }
  85376. /* Finially, delete what is left of the subquery and return
  85377. ** success.
  85378. */
  85379. sqlite3SelectDelete(db, pSub1);
  85380. return 1;
  85381. }
  85382. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  85383. /*
  85384. ** Based on the contents of the AggInfo structure indicated by the first
  85385. ** argument, this function checks if the following are true:
  85386. **
  85387. ** * the query contains just a single aggregate function,
  85388. ** * the aggregate function is either min() or max(), and
  85389. ** * the argument to the aggregate function is a column value.
  85390. **
  85391. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  85392. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  85393. ** list of arguments passed to the aggregate before returning.
  85394. **
  85395. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  85396. ** WHERE_ORDERBY_NORMAL is returned.
  85397. */
  85398. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  85399. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  85400. *ppMinMax = 0;
  85401. if( pAggInfo->nFunc==1 ){
  85402. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  85403. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  85404. assert( pExpr->op==TK_AGG_FUNCTION );
  85405. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  85406. const char *zFunc = pExpr->u.zToken;
  85407. if( sqlite3StrICmp(zFunc, "min")==0 ){
  85408. eRet = WHERE_ORDERBY_MIN;
  85409. *ppMinMax = pEList;
  85410. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  85411. eRet = WHERE_ORDERBY_MAX;
  85412. *ppMinMax = pEList;
  85413. }
  85414. }
  85415. }
  85416. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  85417. return eRet;
  85418. }
  85419. /*
  85420. ** The select statement passed as the first argument is an aggregate query.
  85421. ** The second argment is the associated aggregate-info object. This
  85422. ** function tests if the SELECT is of the form:
  85423. **
  85424. ** SELECT count(*) FROM <tbl>
  85425. **
  85426. ** where table is a database table, not a sub-select or view. If the query
  85427. ** does match this pattern, then a pointer to the Table object representing
  85428. ** <tbl> is returned. Otherwise, 0 is returned.
  85429. */
  85430. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  85431. Table *pTab;
  85432. Expr *pExpr;
  85433. assert( !p->pGroupBy );
  85434. if( p->pWhere || p->pEList->nExpr!=1
  85435. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  85436. ){
  85437. return 0;
  85438. }
  85439. pTab = p->pSrc->a[0].pTab;
  85440. pExpr = p->pEList->a[0].pExpr;
  85441. assert( pTab && !pTab->pSelect && pExpr );
  85442. if( IsVirtual(pTab) ) return 0;
  85443. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  85444. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  85445. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  85446. if( pExpr->flags&EP_Distinct ) return 0;
  85447. return pTab;
  85448. }
  85449. /*
  85450. ** If the source-list item passed as an argument was augmented with an
  85451. ** INDEXED BY clause, then try to locate the specified index. If there
  85452. ** was such a clause and the named index cannot be found, return
  85453. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  85454. ** pFrom->pIndex and return SQLITE_OK.
  85455. */
  85456. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  85457. if( pFrom->pTab && pFrom->zIndex ){
  85458. Table *pTab = pFrom->pTab;
  85459. char *zIndex = pFrom->zIndex;
  85460. Index *pIdx;
  85461. for(pIdx=pTab->pIndex;
  85462. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  85463. pIdx=pIdx->pNext
  85464. );
  85465. if( !pIdx ){
  85466. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  85467. pParse->checkSchema = 1;
  85468. return SQLITE_ERROR;
  85469. }
  85470. pFrom->pIndex = pIdx;
  85471. }
  85472. return SQLITE_OK;
  85473. }
  85474. /*
  85475. ** Detect compound SELECT statements that use an ORDER BY clause with
  85476. ** an alternative collating sequence.
  85477. **
  85478. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  85479. **
  85480. ** These are rewritten as a subquery:
  85481. **
  85482. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  85483. ** ORDER BY ... COLLATE ...
  85484. **
  85485. ** This transformation is necessary because the multiSelectOrderBy() routine
  85486. ** above that generates the code for a compound SELECT with an ORDER BY clause
  85487. ** uses a merge algorithm that requires the same collating sequence on the
  85488. ** result columns as on the ORDER BY clause. See ticket
  85489. ** http://www.sqlite.org/src/info/6709574d2a
  85490. **
  85491. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  85492. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  85493. ** there are COLLATE terms in the ORDER BY.
  85494. */
  85495. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  85496. int i;
  85497. Select *pNew;
  85498. Select *pX;
  85499. sqlite3 *db;
  85500. struct ExprList_item *a;
  85501. SrcList *pNewSrc;
  85502. Parse *pParse;
  85503. Token dummy;
  85504. if( p->pPrior==0 ) return WRC_Continue;
  85505. if( p->pOrderBy==0 ) return WRC_Continue;
  85506. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  85507. if( pX==0 ) return WRC_Continue;
  85508. a = p->pOrderBy->a;
  85509. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  85510. if( a[i].pExpr->flags & EP_Collate ) break;
  85511. }
  85512. if( i<0 ) return WRC_Continue;
  85513. /* If we reach this point, that means the transformation is required. */
  85514. pParse = pWalker->pParse;
  85515. db = pParse->db;
  85516. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  85517. if( pNew==0 ) return WRC_Abort;
  85518. memset(&dummy, 0, sizeof(dummy));
  85519. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  85520. if( pNewSrc==0 ) return WRC_Abort;
  85521. *pNew = *p;
  85522. p->pSrc = pNewSrc;
  85523. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  85524. p->op = TK_SELECT;
  85525. p->pWhere = 0;
  85526. pNew->pGroupBy = 0;
  85527. pNew->pHaving = 0;
  85528. pNew->pOrderBy = 0;
  85529. p->pPrior = 0;
  85530. pNew->pLimit = 0;
  85531. pNew->pOffset = 0;
  85532. return WRC_Continue;
  85533. }
  85534. /*
  85535. ** This routine is a Walker callback for "expanding" a SELECT statement.
  85536. ** "Expanding" means to do the following:
  85537. **
  85538. ** (1) Make sure VDBE cursor numbers have been assigned to every
  85539. ** element of the FROM clause.
  85540. **
  85541. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  85542. ** defines FROM clause. When views appear in the FROM clause,
  85543. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  85544. ** that implements the view. A copy is made of the view's SELECT
  85545. ** statement so that we can freely modify or delete that statement
  85546. ** without worrying about messing up the presistent representation
  85547. ** of the view.
  85548. **
  85549. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  85550. ** on joins and the ON and USING clause of joins.
  85551. **
  85552. ** (4) Scan the list of columns in the result set (pEList) looking
  85553. ** for instances of the "*" operator or the TABLE.* operator.
  85554. ** If found, expand each "*" to be every column in every table
  85555. ** and TABLE.* to be every column in TABLE.
  85556. **
  85557. */
  85558. static int selectExpander(Walker *pWalker, Select *p){
  85559. Parse *pParse = pWalker->pParse;
  85560. int i, j, k;
  85561. SrcList *pTabList;
  85562. ExprList *pEList;
  85563. struct SrcList_item *pFrom;
  85564. sqlite3 *db = pParse->db;
  85565. Expr *pE, *pRight, *pExpr;
  85566. u16 selFlags = p->selFlags;
  85567. p->selFlags |= SF_Expanded;
  85568. if( db->mallocFailed ){
  85569. return WRC_Abort;
  85570. }
  85571. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  85572. return WRC_Prune;
  85573. }
  85574. pTabList = p->pSrc;
  85575. pEList = p->pEList;
  85576. /* Make sure cursor numbers have been assigned to all entries in
  85577. ** the FROM clause of the SELECT statement.
  85578. */
  85579. sqlite3SrcListAssignCursors(pParse, pTabList);
  85580. /* Look up every table named in the FROM clause of the select. If
  85581. ** an entry of the FROM clause is a subquery instead of a table or view,
  85582. ** then create a transient table structure to describe the subquery.
  85583. */
  85584. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85585. Table *pTab;
  85586. if( pFrom->pTab!=0 ){
  85587. /* This statement has already been prepared. There is no need
  85588. ** to go further. */
  85589. assert( i==0 );
  85590. return WRC_Prune;
  85591. }
  85592. if( pFrom->zName==0 ){
  85593. #ifndef SQLITE_OMIT_SUBQUERY
  85594. Select *pSel = pFrom->pSelect;
  85595. /* A sub-query in the FROM clause of a SELECT */
  85596. assert( pSel!=0 );
  85597. assert( pFrom->pTab==0 );
  85598. sqlite3WalkSelect(pWalker, pSel);
  85599. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  85600. if( pTab==0 ) return WRC_Abort;
  85601. pTab->nRef = 1;
  85602. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  85603. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  85604. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  85605. pTab->iPKey = -1;
  85606. pTab->nRowEst = 1048576;
  85607. pTab->tabFlags |= TF_Ephemeral;
  85608. #endif
  85609. }else{
  85610. /* An ordinary table or view name in the FROM clause */
  85611. assert( pFrom->pTab==0 );
  85612. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  85613. if( pTab==0 ) return WRC_Abort;
  85614. if( pTab->nRef==0xffff ){
  85615. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  85616. pTab->zName);
  85617. pFrom->pTab = 0;
  85618. return WRC_Abort;
  85619. }
  85620. pTab->nRef++;
  85621. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  85622. if( pTab->pSelect || IsVirtual(pTab) ){
  85623. /* We reach here if the named table is a really a view */
  85624. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  85625. assert( pFrom->pSelect==0 );
  85626. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  85627. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  85628. }
  85629. #endif
  85630. }
  85631. /* Locate the index named by the INDEXED BY clause, if any. */
  85632. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  85633. return WRC_Abort;
  85634. }
  85635. }
  85636. /* Process NATURAL keywords, and ON and USING clauses of joins.
  85637. */
  85638. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  85639. return WRC_Abort;
  85640. }
  85641. /* For every "*" that occurs in the column list, insert the names of
  85642. ** all columns in all tables. And for every TABLE.* insert the names
  85643. ** of all columns in TABLE. The parser inserted a special expression
  85644. ** with the TK_ALL operator for each "*" that it found in the column list.
  85645. ** The following code just has to locate the TK_ALL expressions and expand
  85646. ** each one to the list of all columns in all tables.
  85647. **
  85648. ** The first loop just checks to see if there are any "*" operators
  85649. ** that need expanding.
  85650. */
  85651. for(k=0; k<pEList->nExpr; k++){
  85652. pE = pEList->a[k].pExpr;
  85653. if( pE->op==TK_ALL ) break;
  85654. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  85655. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  85656. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  85657. }
  85658. if( k<pEList->nExpr ){
  85659. /*
  85660. ** If we get here it means the result set contains one or more "*"
  85661. ** operators that need to be expanded. Loop through each expression
  85662. ** in the result set and expand them one by one.
  85663. */
  85664. struct ExprList_item *a = pEList->a;
  85665. ExprList *pNew = 0;
  85666. int flags = pParse->db->flags;
  85667. int longNames = (flags & SQLITE_FullColNames)!=0
  85668. && (flags & SQLITE_ShortColNames)==0;
  85669. /* When processing FROM-clause subqueries, it is always the case
  85670. ** that full_column_names=OFF and short_column_names=ON. The
  85671. ** sqlite3ResultSetOfSelect() routine makes it so. */
  85672. assert( (p->selFlags & SF_NestedFrom)==0
  85673. || ((flags & SQLITE_FullColNames)==0 &&
  85674. (flags & SQLITE_ShortColNames)!=0) );
  85675. for(k=0; k<pEList->nExpr; k++){
  85676. pE = a[k].pExpr;
  85677. pRight = pE->pRight;
  85678. assert( pE->op!=TK_DOT || pRight!=0 );
  85679. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  85680. /* This particular expression does not need to be expanded.
  85681. */
  85682. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  85683. if( pNew ){
  85684. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  85685. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  85686. a[k].zName = 0;
  85687. a[k].zSpan = 0;
  85688. }
  85689. a[k].pExpr = 0;
  85690. }else{
  85691. /* This expression is a "*" or a "TABLE.*" and needs to be
  85692. ** expanded. */
  85693. int tableSeen = 0; /* Set to 1 when TABLE matches */
  85694. char *zTName = 0; /* text of name of TABLE */
  85695. if( pE->op==TK_DOT ){
  85696. assert( pE->pLeft!=0 );
  85697. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  85698. zTName = pE->pLeft->u.zToken;
  85699. }
  85700. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85701. Table *pTab = pFrom->pTab;
  85702. Select *pSub = pFrom->pSelect;
  85703. char *zTabName = pFrom->zAlias;
  85704. const char *zSchemaName = 0;
  85705. int iDb;
  85706. if( zTabName==0 ){
  85707. zTabName = pTab->zName;
  85708. }
  85709. if( db->mallocFailed ) break;
  85710. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  85711. pSub = 0;
  85712. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  85713. continue;
  85714. }
  85715. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85716. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  85717. }
  85718. for(j=0; j<pTab->nCol; j++){
  85719. char *zName = pTab->aCol[j].zName;
  85720. char *zColname; /* The computed column name */
  85721. char *zToFree; /* Malloced string that needs to be freed */
  85722. Token sColname; /* Computed column name as a token */
  85723. assert( zName );
  85724. if( zTName && pSub
  85725. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  85726. ){
  85727. continue;
  85728. }
  85729. /* If a column is marked as 'hidden' (currently only possible
  85730. ** for virtual tables), do not include it in the expanded
  85731. ** result-set list.
  85732. */
  85733. if( IsHiddenColumn(&pTab->aCol[j]) ){
  85734. assert(IsVirtual(pTab));
  85735. continue;
  85736. }
  85737. tableSeen = 1;
  85738. if( i>0 && zTName==0 ){
  85739. if( (pFrom->jointype & JT_NATURAL)!=0
  85740. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  85741. ){
  85742. /* In a NATURAL join, omit the join columns from the
  85743. ** table to the right of the join */
  85744. continue;
  85745. }
  85746. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  85747. /* In a join with a USING clause, omit columns in the
  85748. ** using clause from the table on the right. */
  85749. continue;
  85750. }
  85751. }
  85752. pRight = sqlite3Expr(db, TK_ID, zName);
  85753. zColname = zName;
  85754. zToFree = 0;
  85755. if( longNames || pTabList->nSrc>1 ){
  85756. Expr *pLeft;
  85757. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  85758. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  85759. if( zSchemaName ){
  85760. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  85761. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  85762. }
  85763. if( longNames ){
  85764. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  85765. zToFree = zColname;
  85766. }
  85767. }else{
  85768. pExpr = pRight;
  85769. }
  85770. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  85771. sColname.z = zColname;
  85772. sColname.n = sqlite3Strlen30(zColname);
  85773. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  85774. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  85775. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  85776. if( pSub ){
  85777. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  85778. testcase( pX->zSpan==0 );
  85779. }else{
  85780. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  85781. zSchemaName, zTabName, zColname);
  85782. testcase( pX->zSpan==0 );
  85783. }
  85784. pX->bSpanIsTab = 1;
  85785. }
  85786. sqlite3DbFree(db, zToFree);
  85787. }
  85788. }
  85789. if( !tableSeen ){
  85790. if( zTName ){
  85791. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  85792. }else{
  85793. sqlite3ErrorMsg(pParse, "no tables specified");
  85794. }
  85795. }
  85796. }
  85797. }
  85798. sqlite3ExprListDelete(db, pEList);
  85799. p->pEList = pNew;
  85800. }
  85801. #if SQLITE_MAX_COLUMN
  85802. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  85803. sqlite3ErrorMsg(pParse, "too many columns in result set");
  85804. }
  85805. #endif
  85806. return WRC_Continue;
  85807. }
  85808. /*
  85809. ** No-op routine for the parse-tree walker.
  85810. **
  85811. ** When this routine is the Walker.xExprCallback then expression trees
  85812. ** are walked without any actions being taken at each node. Presumably,
  85813. ** when this routine is used for Walker.xExprCallback then
  85814. ** Walker.xSelectCallback is set to do something useful for every
  85815. ** subquery in the parser tree.
  85816. */
  85817. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  85818. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  85819. return WRC_Continue;
  85820. }
  85821. /*
  85822. ** This routine "expands" a SELECT statement and all of its subqueries.
  85823. ** For additional information on what it means to "expand" a SELECT
  85824. ** statement, see the comment on the selectExpand worker callback above.
  85825. **
  85826. ** Expanding a SELECT statement is the first step in processing a
  85827. ** SELECT statement. The SELECT statement must be expanded before
  85828. ** name resolution is performed.
  85829. **
  85830. ** If anything goes wrong, an error message is written into pParse.
  85831. ** The calling function can detect the problem by looking at pParse->nErr
  85832. ** and/or pParse->db->mallocFailed.
  85833. */
  85834. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  85835. Walker w;
  85836. memset(&w, 0, sizeof(w));
  85837. w.xExprCallback = exprWalkNoop;
  85838. w.pParse = pParse;
  85839. if( pParse->hasCompound ){
  85840. w.xSelectCallback = convertCompoundSelectToSubquery;
  85841. sqlite3WalkSelect(&w, pSelect);
  85842. }
  85843. w.xSelectCallback = selectExpander;
  85844. sqlite3WalkSelect(&w, pSelect);
  85845. }
  85846. #ifndef SQLITE_OMIT_SUBQUERY
  85847. /*
  85848. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  85849. ** interface.
  85850. **
  85851. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  85852. ** information to the Table structure that represents the result set
  85853. ** of that subquery.
  85854. **
  85855. ** The Table structure that represents the result set was constructed
  85856. ** by selectExpander() but the type and collation information was omitted
  85857. ** at that point because identifiers had not yet been resolved. This
  85858. ** routine is called after identifier resolution.
  85859. */
  85860. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  85861. Parse *pParse;
  85862. int i;
  85863. SrcList *pTabList;
  85864. struct SrcList_item *pFrom;
  85865. assert( p->selFlags & SF_Resolved );
  85866. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  85867. p->selFlags |= SF_HasTypeInfo;
  85868. pParse = pWalker->pParse;
  85869. pTabList = p->pSrc;
  85870. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  85871. Table *pTab = pFrom->pTab;
  85872. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  85873. /* A sub-query in the FROM clause of a SELECT */
  85874. Select *pSel = pFrom->pSelect;
  85875. assert( pSel );
  85876. while( pSel->pPrior ) pSel = pSel->pPrior;
  85877. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  85878. }
  85879. }
  85880. }
  85881. return WRC_Continue;
  85882. }
  85883. #endif
  85884. /*
  85885. ** This routine adds datatype and collating sequence information to
  85886. ** the Table structures of all FROM-clause subqueries in a
  85887. ** SELECT statement.
  85888. **
  85889. ** Use this routine after name resolution.
  85890. */
  85891. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  85892. #ifndef SQLITE_OMIT_SUBQUERY
  85893. Walker w;
  85894. memset(&w, 0, sizeof(w));
  85895. w.xSelectCallback = selectAddSubqueryTypeInfo;
  85896. w.xExprCallback = exprWalkNoop;
  85897. w.pParse = pParse;
  85898. w.bSelectDepthFirst = 1;
  85899. sqlite3WalkSelect(&w, pSelect);
  85900. #endif
  85901. }
  85902. /*
  85903. ** This routine sets up a SELECT statement for processing. The
  85904. ** following is accomplished:
  85905. **
  85906. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  85907. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  85908. ** * ON and USING clauses are shifted into WHERE statements
  85909. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  85910. ** * Identifiers in expression are matched to tables.
  85911. **
  85912. ** This routine acts recursively on all subqueries within the SELECT.
  85913. */
  85914. SQLITE_PRIVATE void sqlite3SelectPrep(
  85915. Parse *pParse, /* The parser context */
  85916. Select *p, /* The SELECT statement being coded. */
  85917. NameContext *pOuterNC /* Name context for container */
  85918. ){
  85919. sqlite3 *db;
  85920. if( NEVER(p==0) ) return;
  85921. db = pParse->db;
  85922. if( db->mallocFailed ) return;
  85923. if( p->selFlags & SF_HasTypeInfo ) return;
  85924. sqlite3SelectExpand(pParse, p);
  85925. if( pParse->nErr || db->mallocFailed ) return;
  85926. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  85927. if( pParse->nErr || db->mallocFailed ) return;
  85928. sqlite3SelectAddTypeInfo(pParse, p);
  85929. }
  85930. /*
  85931. ** Reset the aggregate accumulator.
  85932. **
  85933. ** The aggregate accumulator is a set of memory cells that hold
  85934. ** intermediate results while calculating an aggregate. This
  85935. ** routine generates code that stores NULLs in all of those memory
  85936. ** cells.
  85937. */
  85938. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  85939. Vdbe *v = pParse->pVdbe;
  85940. int i;
  85941. struct AggInfo_func *pFunc;
  85942. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  85943. return;
  85944. }
  85945. for(i=0; i<pAggInfo->nColumn; i++){
  85946. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  85947. }
  85948. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  85949. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  85950. if( pFunc->iDistinct>=0 ){
  85951. Expr *pE = pFunc->pExpr;
  85952. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  85953. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  85954. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  85955. "argument");
  85956. pFunc->iDistinct = -1;
  85957. }else{
  85958. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  85959. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  85960. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  85961. }
  85962. }
  85963. }
  85964. }
  85965. /*
  85966. ** Invoke the OP_AggFinalize opcode for every aggregate function
  85967. ** in the AggInfo structure.
  85968. */
  85969. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  85970. Vdbe *v = pParse->pVdbe;
  85971. int i;
  85972. struct AggInfo_func *pF;
  85973. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  85974. ExprList *pList = pF->pExpr->x.pList;
  85975. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  85976. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  85977. (void*)pF->pFunc, P4_FUNCDEF);
  85978. }
  85979. }
  85980. /*
  85981. ** Update the accumulator memory cells for an aggregate based on
  85982. ** the current cursor position.
  85983. */
  85984. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  85985. Vdbe *v = pParse->pVdbe;
  85986. int i;
  85987. int regHit = 0;
  85988. int addrHitTest = 0;
  85989. struct AggInfo_func *pF;
  85990. struct AggInfo_col *pC;
  85991. pAggInfo->directMode = 1;
  85992. sqlite3ExprCacheClear(pParse);
  85993. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  85994. int nArg;
  85995. int addrNext = 0;
  85996. int regAgg;
  85997. ExprList *pList = pF->pExpr->x.pList;
  85998. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  85999. if( pList ){
  86000. nArg = pList->nExpr;
  86001. regAgg = sqlite3GetTempRange(pParse, nArg);
  86002. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  86003. }else{
  86004. nArg = 0;
  86005. regAgg = 0;
  86006. }
  86007. if( pF->iDistinct>=0 ){
  86008. addrNext = sqlite3VdbeMakeLabel(v);
  86009. assert( nArg==1 );
  86010. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  86011. }
  86012. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  86013. CollSeq *pColl = 0;
  86014. struct ExprList_item *pItem;
  86015. int j;
  86016. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  86017. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  86018. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  86019. }
  86020. if( !pColl ){
  86021. pColl = pParse->db->pDfltColl;
  86022. }
  86023. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  86024. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  86025. }
  86026. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  86027. (void*)pF->pFunc, P4_FUNCDEF);
  86028. sqlite3VdbeChangeP5(v, (u8)nArg);
  86029. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  86030. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  86031. if( addrNext ){
  86032. sqlite3VdbeResolveLabel(v, addrNext);
  86033. sqlite3ExprCacheClear(pParse);
  86034. }
  86035. }
  86036. /* Before populating the accumulator registers, clear the column cache.
  86037. ** Otherwise, if any of the required column values are already present
  86038. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  86039. ** to pC->iMem. But by the time the value is used, the original register
  86040. ** may have been used, invalidating the underlying buffer holding the
  86041. ** text or blob value. See ticket [883034dcb5].
  86042. **
  86043. ** Another solution would be to change the OP_SCopy used to copy cached
  86044. ** values to an OP_Copy.
  86045. */
  86046. if( regHit ){
  86047. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  86048. }
  86049. sqlite3ExprCacheClear(pParse);
  86050. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  86051. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  86052. }
  86053. pAggInfo->directMode = 0;
  86054. sqlite3ExprCacheClear(pParse);
  86055. if( addrHitTest ){
  86056. sqlite3VdbeJumpHere(v, addrHitTest);
  86057. }
  86058. }
  86059. /*
  86060. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  86061. ** count(*) query ("SELECT count(*) FROM pTab").
  86062. */
  86063. #ifndef SQLITE_OMIT_EXPLAIN
  86064. static void explainSimpleCount(
  86065. Parse *pParse, /* Parse context */
  86066. Table *pTab, /* Table being queried */
  86067. Index *pIdx /* Index used to optimize scan, or NULL */
  86068. ){
  86069. if( pParse->explain==2 ){
  86070. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  86071. pTab->zName,
  86072. pIdx ? " USING COVERING INDEX " : "",
  86073. pIdx ? pIdx->zName : ""
  86074. );
  86075. sqlite3VdbeAddOp4(
  86076. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  86077. );
  86078. }
  86079. }
  86080. #else
  86081. # define explainSimpleCount(a,b,c)
  86082. #endif
  86083. /*
  86084. ** Generate code for the SELECT statement given in the p argument.
  86085. **
  86086. ** The results are distributed in various ways depending on the
  86087. ** contents of the SelectDest structure pointed to by argument pDest
  86088. ** as follows:
  86089. **
  86090. ** pDest->eDest Result
  86091. ** ------------ -------------------------------------------
  86092. ** SRT_Output Generate a row of output (using the OP_ResultRow
  86093. ** opcode) for each row in the result set.
  86094. **
  86095. ** SRT_Mem Only valid if the result is a single column.
  86096. ** Store the first column of the first result row
  86097. ** in register pDest->iSDParm then abandon the rest
  86098. ** of the query. This destination implies "LIMIT 1".
  86099. **
  86100. ** SRT_Set The result must be a single column. Store each
  86101. ** row of result as the key in table pDest->iSDParm.
  86102. ** Apply the affinity pDest->affSdst before storing
  86103. ** results. Used to implement "IN (SELECT ...)".
  86104. **
  86105. ** SRT_Union Store results as a key in a temporary table
  86106. ** identified by pDest->iSDParm.
  86107. **
  86108. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  86109. **
  86110. ** SRT_Table Store results in temporary table pDest->iSDParm.
  86111. ** This is like SRT_EphemTab except that the table
  86112. ** is assumed to already be open.
  86113. **
  86114. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  86115. ** the result there. The cursor is left open after
  86116. ** returning. This is like SRT_Table except that
  86117. ** this destination uses OP_OpenEphemeral to create
  86118. ** the table first.
  86119. **
  86120. ** SRT_Coroutine Generate a co-routine that returns a new row of
  86121. ** results each time it is invoked. The entry point
  86122. ** of the co-routine is stored in register pDest->iSDParm.
  86123. **
  86124. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  86125. ** set is not empty.
  86126. **
  86127. ** SRT_Discard Throw the results away. This is used by SELECT
  86128. ** statements within triggers whose only purpose is
  86129. ** the side-effects of functions.
  86130. **
  86131. ** This routine returns the number of errors. If any errors are
  86132. ** encountered, then an appropriate error message is left in
  86133. ** pParse->zErrMsg.
  86134. **
  86135. ** This routine does NOT free the Select structure passed in. The
  86136. ** calling function needs to do that.
  86137. */
  86138. SQLITE_PRIVATE int sqlite3Select(
  86139. Parse *pParse, /* The parser context */
  86140. Select *p, /* The SELECT statement being coded. */
  86141. SelectDest *pDest /* What to do with the query results */
  86142. ){
  86143. int i, j; /* Loop counters */
  86144. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  86145. Vdbe *v; /* The virtual machine under construction */
  86146. int isAgg; /* True for select lists like "count(*)" */
  86147. ExprList *pEList; /* List of columns to extract. */
  86148. SrcList *pTabList; /* List of tables to select from */
  86149. Expr *pWhere; /* The WHERE clause. May be NULL */
  86150. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  86151. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  86152. Expr *pHaving; /* The HAVING clause. May be NULL */
  86153. int rc = 1; /* Value to return from this function */
  86154. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  86155. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  86156. AggInfo sAggInfo; /* Information used by aggregate queries */
  86157. int iEnd; /* Address of the end of the query */
  86158. sqlite3 *db; /* The database connection */
  86159. #ifndef SQLITE_OMIT_EXPLAIN
  86160. int iRestoreSelectId = pParse->iSelectId;
  86161. pParse->iSelectId = pParse->iNextSelectId++;
  86162. #endif
  86163. db = pParse->db;
  86164. if( p==0 || db->mallocFailed || pParse->nErr ){
  86165. return 1;
  86166. }
  86167. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  86168. memset(&sAggInfo, 0, sizeof(sAggInfo));
  86169. if( IgnorableOrderby(pDest) ){
  86170. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  86171. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  86172. /* If ORDER BY makes no difference in the output then neither does
  86173. ** DISTINCT so it can be removed too. */
  86174. sqlite3ExprListDelete(db, p->pOrderBy);
  86175. p->pOrderBy = 0;
  86176. p->selFlags &= ~SF_Distinct;
  86177. }
  86178. sqlite3SelectPrep(pParse, p, 0);
  86179. pOrderBy = p->pOrderBy;
  86180. pTabList = p->pSrc;
  86181. pEList = p->pEList;
  86182. if( pParse->nErr || db->mallocFailed ){
  86183. goto select_end;
  86184. }
  86185. isAgg = (p->selFlags & SF_Aggregate)!=0;
  86186. assert( pEList!=0 );
  86187. /* Begin generating code.
  86188. */
  86189. v = sqlite3GetVdbe(pParse);
  86190. if( v==0 ) goto select_end;
  86191. /* If writing to memory or generating a set
  86192. ** only a single column may be output.
  86193. */
  86194. #ifndef SQLITE_OMIT_SUBQUERY
  86195. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  86196. goto select_end;
  86197. }
  86198. #endif
  86199. /* Generate code for all sub-queries in the FROM clause
  86200. */
  86201. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  86202. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  86203. struct SrcList_item *pItem = &pTabList->a[i];
  86204. SelectDest dest;
  86205. Select *pSub = pItem->pSelect;
  86206. int isAggSub;
  86207. if( pSub==0 ) continue;
  86208. /* Sometimes the code for a subquery will be generated more than
  86209. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  86210. ** for example. In that case, do not regenerate the code to manifest
  86211. ** a view or the co-routine to implement a view. The first instance
  86212. ** is sufficient, though the subroutine to manifest the view does need
  86213. ** to be invoked again. */
  86214. if( pItem->addrFillSub ){
  86215. if( pItem->viaCoroutine==0 ){
  86216. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  86217. }
  86218. continue;
  86219. }
  86220. /* Increment Parse.nHeight by the height of the largest expression
  86221. ** tree referred to by this, the parent select. The child select
  86222. ** may contain expression trees of at most
  86223. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  86224. ** more conservative than necessary, but much easier than enforcing
  86225. ** an exact limit.
  86226. */
  86227. pParse->nHeight += sqlite3SelectExprHeight(p);
  86228. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  86229. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  86230. /* This subquery can be absorbed into its parent. */
  86231. if( isAggSub ){
  86232. isAgg = 1;
  86233. p->selFlags |= SF_Aggregate;
  86234. }
  86235. i = -1;
  86236. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  86237. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  86238. ){
  86239. /* Implement a co-routine that will return a single row of the result
  86240. ** set on each invocation.
  86241. */
  86242. int addrTop;
  86243. int addrEof;
  86244. pItem->regReturn = ++pParse->nMem;
  86245. addrEof = ++pParse->nMem;
  86246. /* Before coding the OP_Goto to jump to the start of the main routine,
  86247. ** ensure that the jump to the verify-schema routine has already
  86248. ** been coded. Otherwise, the verify-schema would likely be coded as
  86249. ** part of the co-routine. If the main routine then accessed the
  86250. ** database before invoking the co-routine for the first time (for
  86251. ** example to initialize a LIMIT register from a sub-select), it would
  86252. ** be doing so without having verified the schema version and obtained
  86253. ** the required db locks. See ticket d6b36be38. */
  86254. sqlite3CodeVerifySchema(pParse, -1);
  86255. sqlite3VdbeAddOp0(v, OP_Goto);
  86256. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  86257. sqlite3VdbeChangeP5(v, 1);
  86258. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  86259. pItem->addrFillSub = addrTop;
  86260. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  86261. sqlite3VdbeChangeP5(v, 1);
  86262. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  86263. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  86264. sqlite3Select(pParse, pSub, &dest);
  86265. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  86266. pItem->viaCoroutine = 1;
  86267. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  86268. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  86269. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  86270. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  86271. VdbeComment((v, "end %s", pItem->pTab->zName));
  86272. sqlite3VdbeJumpHere(v, addrTop-1);
  86273. sqlite3ClearTempRegCache(pParse);
  86274. }else{
  86275. /* Generate a subroutine that will fill an ephemeral table with
  86276. ** the content of this subquery. pItem->addrFillSub will point
  86277. ** to the address of the generated subroutine. pItem->regReturn
  86278. ** is a register allocated to hold the subroutine return address
  86279. */
  86280. int topAddr;
  86281. int onceAddr = 0;
  86282. int retAddr;
  86283. assert( pItem->addrFillSub==0 );
  86284. pItem->regReturn = ++pParse->nMem;
  86285. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  86286. pItem->addrFillSub = topAddr+1;
  86287. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  86288. if( pItem->isCorrelated==0 ){
  86289. /* If the subquery is not correlated and if we are not inside of
  86290. ** a trigger, then we only need to compute the value of the subquery
  86291. ** once. */
  86292. onceAddr = sqlite3CodeOnce(pParse);
  86293. }
  86294. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  86295. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  86296. sqlite3Select(pParse, pSub, &dest);
  86297. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  86298. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  86299. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  86300. VdbeComment((v, "end %s", pItem->pTab->zName));
  86301. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  86302. sqlite3ClearTempRegCache(pParse);
  86303. }
  86304. if( /*pParse->nErr ||*/ db->mallocFailed ){
  86305. goto select_end;
  86306. }
  86307. pParse->nHeight -= sqlite3SelectExprHeight(p);
  86308. pTabList = p->pSrc;
  86309. if( !IgnorableOrderby(pDest) ){
  86310. pOrderBy = p->pOrderBy;
  86311. }
  86312. }
  86313. pEList = p->pEList;
  86314. #endif
  86315. pWhere = p->pWhere;
  86316. pGroupBy = p->pGroupBy;
  86317. pHaving = p->pHaving;
  86318. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  86319. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  86320. /* If there is are a sequence of queries, do the earlier ones first.
  86321. */
  86322. if( p->pPrior ){
  86323. if( p->pRightmost==0 ){
  86324. Select *pLoop, *pRight = 0;
  86325. int cnt = 0;
  86326. int mxSelect;
  86327. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  86328. pLoop->pRightmost = p;
  86329. pLoop->pNext = pRight;
  86330. pRight = pLoop;
  86331. }
  86332. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  86333. if( mxSelect && cnt>mxSelect ){
  86334. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  86335. goto select_end;
  86336. }
  86337. }
  86338. rc = multiSelect(pParse, p, pDest);
  86339. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  86340. return rc;
  86341. }
  86342. #endif
  86343. /* If there is both a GROUP BY and an ORDER BY clause and they are
  86344. ** identical, then disable the ORDER BY clause since the GROUP BY
  86345. ** will cause elements to come out in the correct order. This is
  86346. ** an optimization - the correct answer should result regardless.
  86347. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  86348. ** to disable this optimization for testing purposes.
  86349. */
  86350. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  86351. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  86352. pOrderBy = 0;
  86353. }
  86354. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  86355. ** if the select-list is the same as the ORDER BY list, then this query
  86356. ** can be rewritten as a GROUP BY. In other words, this:
  86357. **
  86358. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  86359. **
  86360. ** is transformed to:
  86361. **
  86362. ** SELECT xyz FROM ... GROUP BY xyz
  86363. **
  86364. ** The second form is preferred as a single index (or temp-table) may be
  86365. ** used for both the ORDER BY and DISTINCT processing. As originally
  86366. ** written the query must use a temp-table for at least one of the ORDER
  86367. ** BY and DISTINCT, and an index or separate temp-table for the other.
  86368. */
  86369. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  86370. && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  86371. ){
  86372. p->selFlags &= ~SF_Distinct;
  86373. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  86374. pGroupBy = p->pGroupBy;
  86375. pOrderBy = 0;
  86376. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  86377. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  86378. ** original setting of the SF_Distinct flag, not the current setting */
  86379. assert( sDistinct.isTnct );
  86380. }
  86381. /* If there is an ORDER BY clause, then this sorting
  86382. ** index might end up being unused if the data can be
  86383. ** extracted in pre-sorted order. If that is the case, then the
  86384. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  86385. ** we figure out that the sorting index is not needed. The addrSortIndex
  86386. ** variable is used to facilitate that change.
  86387. */
  86388. if( pOrderBy ){
  86389. KeyInfo *pKeyInfo;
  86390. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  86391. pOrderBy->iECursor = pParse->nTab++;
  86392. p->addrOpenEphm[2] = addrSortIndex =
  86393. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  86394. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  86395. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  86396. }else{
  86397. addrSortIndex = -1;
  86398. }
  86399. /* If the output is destined for a temporary table, open that table.
  86400. */
  86401. if( pDest->eDest==SRT_EphemTab ){
  86402. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  86403. }
  86404. /* Set the limiter.
  86405. */
  86406. iEnd = sqlite3VdbeMakeLabel(v);
  86407. p->nSelectRow = LARGEST_INT64;
  86408. computeLimitRegisters(pParse, p, iEnd);
  86409. if( p->iLimit==0 && addrSortIndex>=0 ){
  86410. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  86411. p->selFlags |= SF_UseSorter;
  86412. }
  86413. /* Open a virtual index to use for the distinct set.
  86414. */
  86415. if( p->selFlags & SF_Distinct ){
  86416. sDistinct.tabTnct = pParse->nTab++;
  86417. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  86418. sDistinct.tabTnct, 0, 0,
  86419. (char*)keyInfoFromExprList(pParse, p->pEList),
  86420. P4_KEYINFO_HANDOFF);
  86421. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  86422. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  86423. }else{
  86424. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  86425. }
  86426. if( !isAgg && pGroupBy==0 ){
  86427. /* No aggregate functions and no GROUP BY clause */
  86428. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  86429. /* Begin the database scan. */
  86430. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
  86431. wctrlFlags, 0);
  86432. if( pWInfo==0 ) goto select_end;
  86433. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  86434. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  86435. }
  86436. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  86437. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  86438. }
  86439. if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
  86440. /* If sorting index that was created by a prior OP_OpenEphemeral
  86441. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  86442. ** into an OP_Noop.
  86443. */
  86444. if( addrSortIndex>=0 && pOrderBy==0 ){
  86445. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  86446. p->addrOpenEphm[2] = -1;
  86447. }
  86448. /* Use the standard inner loop. */
  86449. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  86450. sqlite3WhereContinueLabel(pWInfo),
  86451. sqlite3WhereBreakLabel(pWInfo));
  86452. /* End the database scan loop.
  86453. */
  86454. sqlite3WhereEnd(pWInfo);
  86455. }else{
  86456. /* This case when there exist aggregate functions or a GROUP BY clause
  86457. ** or both */
  86458. NameContext sNC; /* Name context for processing aggregate information */
  86459. int iAMem; /* First Mem address for storing current GROUP BY */
  86460. int iBMem; /* First Mem address for previous GROUP BY */
  86461. int iUseFlag; /* Mem address holding flag indicating that at least
  86462. ** one row of the input to the aggregator has been
  86463. ** processed */
  86464. int iAbortFlag; /* Mem address which causes query abort if positive */
  86465. int groupBySort; /* Rows come from source in GROUP BY order */
  86466. int addrEnd; /* End of processing for this SELECT */
  86467. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  86468. int sortOut = 0; /* Output register from the sorter */
  86469. /* Remove any and all aliases between the result set and the
  86470. ** GROUP BY clause.
  86471. */
  86472. if( pGroupBy ){
  86473. int k; /* Loop counter */
  86474. struct ExprList_item *pItem; /* For looping over expression in a list */
  86475. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  86476. pItem->iAlias = 0;
  86477. }
  86478. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  86479. pItem->iAlias = 0;
  86480. }
  86481. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  86482. }else{
  86483. p->nSelectRow = 1;
  86484. }
  86485. /* Create a label to jump to when we want to abort the query */
  86486. addrEnd = sqlite3VdbeMakeLabel(v);
  86487. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  86488. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  86489. ** SELECT statement.
  86490. */
  86491. memset(&sNC, 0, sizeof(sNC));
  86492. sNC.pParse = pParse;
  86493. sNC.pSrcList = pTabList;
  86494. sNC.pAggInfo = &sAggInfo;
  86495. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  86496. sAggInfo.pGroupBy = pGroupBy;
  86497. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  86498. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  86499. if( pHaving ){
  86500. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  86501. }
  86502. sAggInfo.nAccumulator = sAggInfo.nColumn;
  86503. for(i=0; i<sAggInfo.nFunc; i++){
  86504. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  86505. sNC.ncFlags |= NC_InAggFunc;
  86506. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  86507. sNC.ncFlags &= ~NC_InAggFunc;
  86508. }
  86509. if( db->mallocFailed ) goto select_end;
  86510. /* Processing for aggregates with GROUP BY is very different and
  86511. ** much more complex than aggregates without a GROUP BY.
  86512. */
  86513. if( pGroupBy ){
  86514. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  86515. int j1; /* A-vs-B comparision jump */
  86516. int addrOutputRow; /* Start of subroutine that outputs a result row */
  86517. int regOutputRow; /* Return address register for output subroutine */
  86518. int addrSetAbort; /* Set the abort flag and return */
  86519. int addrTopOfLoop; /* Top of the input loop */
  86520. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  86521. int addrReset; /* Subroutine for resetting the accumulator */
  86522. int regReset; /* Return address register for reset subroutine */
  86523. /* If there is a GROUP BY clause we might need a sorting index to
  86524. ** implement it. Allocate that sorting index now. If it turns out
  86525. ** that we do not need it after all, the OP_SorterOpen instruction
  86526. ** will be converted into a Noop.
  86527. */
  86528. sAggInfo.sortingIdx = pParse->nTab++;
  86529. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  86530. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  86531. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  86532. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  86533. /* Initialize memory locations used by GROUP BY aggregate processing
  86534. */
  86535. iUseFlag = ++pParse->nMem;
  86536. iAbortFlag = ++pParse->nMem;
  86537. regOutputRow = ++pParse->nMem;
  86538. addrOutputRow = sqlite3VdbeMakeLabel(v);
  86539. regReset = ++pParse->nMem;
  86540. addrReset = sqlite3VdbeMakeLabel(v);
  86541. iAMem = pParse->nMem + 1;
  86542. pParse->nMem += pGroupBy->nExpr;
  86543. iBMem = pParse->nMem + 1;
  86544. pParse->nMem += pGroupBy->nExpr;
  86545. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  86546. VdbeComment((v, "clear abort flag"));
  86547. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  86548. VdbeComment((v, "indicate accumulator empty"));
  86549. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  86550. /* Begin a loop that will extract all source rows in GROUP BY order.
  86551. ** This might involve two separate loops with an OP_Sort in between, or
  86552. ** it might be a single loop that uses an index to extract information
  86553. ** in the right order to begin with.
  86554. */
  86555. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  86556. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  86557. WHERE_GROUPBY, 0);
  86558. if( pWInfo==0 ) goto select_end;
  86559. if( sqlite3WhereIsOrdered(pWInfo) ){
  86560. /* The optimizer is able to deliver rows in group by order so
  86561. ** we do not have to sort. The OP_OpenEphemeral table will be
  86562. ** cancelled later because we still need to use the pKeyInfo
  86563. */
  86564. groupBySort = 0;
  86565. }else{
  86566. /* Rows are coming out in undetermined order. We have to push
  86567. ** each row into a sorting index, terminate the first loop,
  86568. ** then loop over the sorting index in order to get the output
  86569. ** in sorted order
  86570. */
  86571. int regBase;
  86572. int regRecord;
  86573. int nCol;
  86574. int nGroupBy;
  86575. explainTempTable(pParse,
  86576. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  86577. "DISTINCT" : "GROUP BY");
  86578. groupBySort = 1;
  86579. nGroupBy = pGroupBy->nExpr;
  86580. nCol = nGroupBy + 1;
  86581. j = nGroupBy+1;
  86582. for(i=0; i<sAggInfo.nColumn; i++){
  86583. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  86584. nCol++;
  86585. j++;
  86586. }
  86587. }
  86588. regBase = sqlite3GetTempRange(pParse, nCol);
  86589. sqlite3ExprCacheClear(pParse);
  86590. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  86591. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  86592. j = nGroupBy+1;
  86593. for(i=0; i<sAggInfo.nColumn; i++){
  86594. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  86595. if( pCol->iSorterColumn>=j ){
  86596. int r1 = j + regBase;
  86597. int r2;
  86598. r2 = sqlite3ExprCodeGetColumn(pParse,
  86599. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  86600. if( r1!=r2 ){
  86601. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  86602. }
  86603. j++;
  86604. }
  86605. }
  86606. regRecord = sqlite3GetTempReg(pParse);
  86607. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  86608. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  86609. sqlite3ReleaseTempReg(pParse, regRecord);
  86610. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  86611. sqlite3WhereEnd(pWInfo);
  86612. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  86613. sortOut = sqlite3GetTempReg(pParse);
  86614. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  86615. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  86616. VdbeComment((v, "GROUP BY sort"));
  86617. sAggInfo.useSortingIdx = 1;
  86618. sqlite3ExprCacheClear(pParse);
  86619. }
  86620. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  86621. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  86622. ** Then compare the current GROUP BY terms against the GROUP BY terms
  86623. ** from the previous row currently stored in a0, a1, a2...
  86624. */
  86625. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  86626. sqlite3ExprCacheClear(pParse);
  86627. if( groupBySort ){
  86628. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  86629. }
  86630. for(j=0; j<pGroupBy->nExpr; j++){
  86631. if( groupBySort ){
  86632. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  86633. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  86634. }else{
  86635. sAggInfo.directMode = 1;
  86636. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  86637. }
  86638. }
  86639. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  86640. (char*)pKeyInfo, P4_KEYINFO);
  86641. j1 = sqlite3VdbeCurrentAddr(v);
  86642. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  86643. /* Generate code that runs whenever the GROUP BY changes.
  86644. ** Changes in the GROUP BY are detected by the previous code
  86645. ** block. If there were no changes, this block is skipped.
  86646. **
  86647. ** This code copies current group by terms in b0,b1,b2,...
  86648. ** over to a0,a1,a2. It then calls the output subroutine
  86649. ** and resets the aggregate accumulator registers in preparation
  86650. ** for the next GROUP BY batch.
  86651. */
  86652. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  86653. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  86654. VdbeComment((v, "output one row"));
  86655. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  86656. VdbeComment((v, "check abort flag"));
  86657. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  86658. VdbeComment((v, "reset accumulator"));
  86659. /* Update the aggregate accumulators based on the content of
  86660. ** the current row
  86661. */
  86662. sqlite3VdbeJumpHere(v, j1);
  86663. updateAccumulator(pParse, &sAggInfo);
  86664. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  86665. VdbeComment((v, "indicate data in accumulator"));
  86666. /* End of the loop
  86667. */
  86668. if( groupBySort ){
  86669. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  86670. }else{
  86671. sqlite3WhereEnd(pWInfo);
  86672. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  86673. }
  86674. /* Output the final row of result
  86675. */
  86676. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  86677. VdbeComment((v, "output final row"));
  86678. /* Jump over the subroutines
  86679. */
  86680. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  86681. /* Generate a subroutine that outputs a single row of the result
  86682. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  86683. ** is less than or equal to zero, the subroutine is a no-op. If
  86684. ** the processing calls for the query to abort, this subroutine
  86685. ** increments the iAbortFlag memory location before returning in
  86686. ** order to signal the caller to abort.
  86687. */
  86688. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  86689. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  86690. VdbeComment((v, "set abort flag"));
  86691. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86692. sqlite3VdbeResolveLabel(v, addrOutputRow);
  86693. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  86694. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  86695. VdbeComment((v, "Groupby result generator entry point"));
  86696. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86697. finalizeAggFunctions(pParse, &sAggInfo);
  86698. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  86699. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  86700. &sDistinct, pDest,
  86701. addrOutputRow+1, addrSetAbort);
  86702. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  86703. VdbeComment((v, "end groupby result generator"));
  86704. /* Generate a subroutine that will reset the group-by accumulator
  86705. */
  86706. sqlite3VdbeResolveLabel(v, addrReset);
  86707. resetAccumulator(pParse, &sAggInfo);
  86708. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  86709. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  86710. else {
  86711. ExprList *pDel = 0;
  86712. #ifndef SQLITE_OMIT_BTREECOUNT
  86713. Table *pTab;
  86714. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  86715. /* If isSimpleCount() returns a pointer to a Table structure, then
  86716. ** the SQL statement is of the form:
  86717. **
  86718. ** SELECT count(*) FROM <tbl>
  86719. **
  86720. ** where the Table structure returned represents table <tbl>.
  86721. **
  86722. ** This statement is so common that it is optimized specially. The
  86723. ** OP_Count instruction is executed either on the intkey table that
  86724. ** contains the data for table <tbl> or on one of its indexes. It
  86725. ** is better to execute the op on an index, as indexes are almost
  86726. ** always spread across less pages than their corresponding tables.
  86727. */
  86728. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  86729. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  86730. Index *pIdx; /* Iterator variable */
  86731. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  86732. Index *pBest = 0; /* Best index found so far */
  86733. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  86734. sqlite3CodeVerifySchema(pParse, iDb);
  86735. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  86736. /* Search for the index that has the lowest scan cost.
  86737. **
  86738. ** (2011-04-15) Do not do a full scan of an unordered index.
  86739. **
  86740. ** (2013-10-03) Do not count the entires in a partial index.
  86741. **
  86742. ** In practice the KeyInfo structure will not be used. It is only
  86743. ** passed to keep OP_OpenRead happy.
  86744. */
  86745. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86746. if( pIdx->bUnordered==0
  86747. && pIdx->szIdxRow<pTab->szTabRow
  86748. && pIdx->pPartIdxWhere==0
  86749. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  86750. ){
  86751. pBest = pIdx;
  86752. }
  86753. }
  86754. if( pBest ){
  86755. iRoot = pBest->tnum;
  86756. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  86757. }
  86758. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  86759. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  86760. if( pKeyInfo ){
  86761. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  86762. }
  86763. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  86764. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  86765. explainSimpleCount(pParse, pTab, pBest);
  86766. }else
  86767. #endif /* SQLITE_OMIT_BTREECOUNT */
  86768. {
  86769. /* Check if the query is of one of the following forms:
  86770. **
  86771. ** SELECT min(x) FROM ...
  86772. ** SELECT max(x) FROM ...
  86773. **
  86774. ** If it is, then ask the code in where.c to attempt to sort results
  86775. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  86776. ** If where.c is able to produce results sorted in this order, then
  86777. ** add vdbe code to break out of the processing loop after the
  86778. ** first iteration (since the first iteration of the loop is
  86779. ** guaranteed to operate on the row with the minimum or maximum
  86780. ** value of x, the only row required).
  86781. **
  86782. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  86783. ** modify behavior as follows:
  86784. **
  86785. ** + If the query is a "SELECT min(x)", then the loop coded by
  86786. ** where.c should not iterate over any values with a NULL value
  86787. ** for x.
  86788. **
  86789. ** + The optimizer code in where.c (the thing that decides which
  86790. ** index or indices to use) should place a different priority on
  86791. ** satisfying the 'ORDER BY' clause than it does in other cases.
  86792. ** Refer to code and comments in where.c for details.
  86793. */
  86794. ExprList *pMinMax = 0;
  86795. u8 flag = WHERE_ORDERBY_NORMAL;
  86796. assert( p->pGroupBy==0 );
  86797. assert( flag==0 );
  86798. if( p->pHaving==0 ){
  86799. flag = minMaxQuery(&sAggInfo, &pMinMax);
  86800. }
  86801. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  86802. if( flag ){
  86803. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  86804. pDel = pMinMax;
  86805. if( pMinMax && !db->mallocFailed ){
  86806. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  86807. pMinMax->a[0].pExpr->op = TK_COLUMN;
  86808. }
  86809. }
  86810. /* This case runs if the aggregate has no GROUP BY clause. The
  86811. ** processing is much simpler since there is only a single row
  86812. ** of output.
  86813. */
  86814. resetAccumulator(pParse, &sAggInfo);
  86815. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  86816. if( pWInfo==0 ){
  86817. sqlite3ExprListDelete(db, pDel);
  86818. goto select_end;
  86819. }
  86820. updateAccumulator(pParse, &sAggInfo);
  86821. assert( pMinMax==0 || pMinMax->nExpr==1 );
  86822. if( sqlite3WhereIsOrdered(pWInfo) ){
  86823. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  86824. VdbeComment((v, "%s() by index",
  86825. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  86826. }
  86827. sqlite3WhereEnd(pWInfo);
  86828. finalizeAggFunctions(pParse, &sAggInfo);
  86829. }
  86830. pOrderBy = 0;
  86831. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  86832. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  86833. pDest, addrEnd, addrEnd);
  86834. sqlite3ExprListDelete(db, pDel);
  86835. }
  86836. sqlite3VdbeResolveLabel(v, addrEnd);
  86837. } /* endif aggregate query */
  86838. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  86839. explainTempTable(pParse, "DISTINCT");
  86840. }
  86841. /* If there is an ORDER BY clause, then we need to sort the results
  86842. ** and send them to the callback one by one.
  86843. */
  86844. if( pOrderBy ){
  86845. explainTempTable(pParse, "ORDER BY");
  86846. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  86847. }
  86848. /* Jump here to skip this query
  86849. */
  86850. sqlite3VdbeResolveLabel(v, iEnd);
  86851. /* The SELECT was successfully coded. Set the return code to 0
  86852. ** to indicate no errors.
  86853. */
  86854. rc = 0;
  86855. /* Control jumps to here if an error is encountered above, or upon
  86856. ** successful coding of the SELECT.
  86857. */
  86858. select_end:
  86859. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  86860. /* Identify column names if results of the SELECT are to be output.
  86861. */
  86862. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  86863. generateColumnNames(pParse, pTabList, pEList);
  86864. }
  86865. sqlite3DbFree(db, sAggInfo.aCol);
  86866. sqlite3DbFree(db, sAggInfo.aFunc);
  86867. return rc;
  86868. }
  86869. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  86870. /*
  86871. ** Generate a human-readable description of a the Select object.
  86872. */
  86873. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  86874. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  86875. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  86876. if( p->selFlags & SF_Distinct ){
  86877. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  86878. }
  86879. if( p->selFlags & SF_Aggregate ){
  86880. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  86881. }
  86882. sqlite3ExplainNL(pVdbe);
  86883. sqlite3ExplainPrintf(pVdbe, " ");
  86884. }
  86885. sqlite3ExplainExprList(pVdbe, p->pEList);
  86886. sqlite3ExplainNL(pVdbe);
  86887. if( p->pSrc && p->pSrc->nSrc ){
  86888. int i;
  86889. sqlite3ExplainPrintf(pVdbe, "FROM ");
  86890. sqlite3ExplainPush(pVdbe);
  86891. for(i=0; i<p->pSrc->nSrc; i++){
  86892. struct SrcList_item *pItem = &p->pSrc->a[i];
  86893. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  86894. if( pItem->pSelect ){
  86895. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  86896. if( pItem->pTab ){
  86897. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  86898. }
  86899. }else if( pItem->zName ){
  86900. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  86901. }
  86902. if( pItem->zAlias ){
  86903. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  86904. }
  86905. if( pItem->jointype & JT_LEFT ){
  86906. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  86907. }
  86908. sqlite3ExplainNL(pVdbe);
  86909. }
  86910. sqlite3ExplainPop(pVdbe);
  86911. }
  86912. if( p->pWhere ){
  86913. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  86914. sqlite3ExplainExpr(pVdbe, p->pWhere);
  86915. sqlite3ExplainNL(pVdbe);
  86916. }
  86917. if( p->pGroupBy ){
  86918. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  86919. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  86920. sqlite3ExplainNL(pVdbe);
  86921. }
  86922. if( p->pHaving ){
  86923. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  86924. sqlite3ExplainExpr(pVdbe, p->pHaving);
  86925. sqlite3ExplainNL(pVdbe);
  86926. }
  86927. if( p->pOrderBy ){
  86928. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  86929. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  86930. sqlite3ExplainNL(pVdbe);
  86931. }
  86932. if( p->pLimit ){
  86933. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  86934. sqlite3ExplainExpr(pVdbe, p->pLimit);
  86935. sqlite3ExplainNL(pVdbe);
  86936. }
  86937. if( p->pOffset ){
  86938. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  86939. sqlite3ExplainExpr(pVdbe, p->pOffset);
  86940. sqlite3ExplainNL(pVdbe);
  86941. }
  86942. }
  86943. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  86944. if( p==0 ){
  86945. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  86946. return;
  86947. }
  86948. while( p->pPrior ){
  86949. p->pPrior->pNext = p;
  86950. p = p->pPrior;
  86951. }
  86952. sqlite3ExplainPush(pVdbe);
  86953. while( p ){
  86954. explainOneSelect(pVdbe, p);
  86955. p = p->pNext;
  86956. if( p==0 ) break;
  86957. sqlite3ExplainNL(pVdbe);
  86958. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  86959. }
  86960. sqlite3ExplainPrintf(pVdbe, "END");
  86961. sqlite3ExplainPop(pVdbe);
  86962. }
  86963. /* End of the structure debug printing code
  86964. *****************************************************************************/
  86965. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  86966. /************** End of select.c **********************************************/
  86967. /************** Begin file table.c *******************************************/
  86968. /*
  86969. ** 2001 September 15
  86970. **
  86971. ** The author disclaims copyright to this source code. In place of
  86972. ** a legal notice, here is a blessing:
  86973. **
  86974. ** May you do good and not evil.
  86975. ** May you find forgiveness for yourself and forgive others.
  86976. ** May you share freely, never taking more than you give.
  86977. **
  86978. *************************************************************************
  86979. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  86980. ** interface routines. These are just wrappers around the main
  86981. ** interface routine of sqlite3_exec().
  86982. **
  86983. ** These routines are in a separate files so that they will not be linked
  86984. ** if they are not used.
  86985. */
  86986. /* #include <stdlib.h> */
  86987. /* #include <string.h> */
  86988. #ifndef SQLITE_OMIT_GET_TABLE
  86989. /*
  86990. ** This structure is used to pass data from sqlite3_get_table() through
  86991. ** to the callback function is uses to build the result.
  86992. */
  86993. typedef struct TabResult {
  86994. char **azResult; /* Accumulated output */
  86995. char *zErrMsg; /* Error message text, if an error occurs */
  86996. int nAlloc; /* Slots allocated for azResult[] */
  86997. int nRow; /* Number of rows in the result */
  86998. int nColumn; /* Number of columns in the result */
  86999. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  87000. int rc; /* Return code from sqlite3_exec() */
  87001. } TabResult;
  87002. /*
  87003. ** This routine is called once for each row in the result table. Its job
  87004. ** is to fill in the TabResult structure appropriately, allocating new
  87005. ** memory as necessary.
  87006. */
  87007. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  87008. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  87009. int need; /* Slots needed in p->azResult[] */
  87010. int i; /* Loop counter */
  87011. char *z; /* A single column of result */
  87012. /* Make sure there is enough space in p->azResult to hold everything
  87013. ** we need to remember from this invocation of the callback.
  87014. */
  87015. if( p->nRow==0 && argv!=0 ){
  87016. need = nCol*2;
  87017. }else{
  87018. need = nCol;
  87019. }
  87020. if( p->nData + need > p->nAlloc ){
  87021. char **azNew;
  87022. p->nAlloc = p->nAlloc*2 + need;
  87023. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  87024. if( azNew==0 ) goto malloc_failed;
  87025. p->azResult = azNew;
  87026. }
  87027. /* If this is the first row, then generate an extra row containing
  87028. ** the names of all columns.
  87029. */
  87030. if( p->nRow==0 ){
  87031. p->nColumn = nCol;
  87032. for(i=0; i<nCol; i++){
  87033. z = sqlite3_mprintf("%s", colv[i]);
  87034. if( z==0 ) goto malloc_failed;
  87035. p->azResult[p->nData++] = z;
  87036. }
  87037. }else if( p->nColumn!=nCol ){
  87038. sqlite3_free(p->zErrMsg);
  87039. p->zErrMsg = sqlite3_mprintf(
  87040. "sqlite3_get_table() called with two or more incompatible queries"
  87041. );
  87042. p->rc = SQLITE_ERROR;
  87043. return 1;
  87044. }
  87045. /* Copy over the row data
  87046. */
  87047. if( argv!=0 ){
  87048. for(i=0; i<nCol; i++){
  87049. if( argv[i]==0 ){
  87050. z = 0;
  87051. }else{
  87052. int n = sqlite3Strlen30(argv[i])+1;
  87053. z = sqlite3_malloc( n );
  87054. if( z==0 ) goto malloc_failed;
  87055. memcpy(z, argv[i], n);
  87056. }
  87057. p->azResult[p->nData++] = z;
  87058. }
  87059. p->nRow++;
  87060. }
  87061. return 0;
  87062. malloc_failed:
  87063. p->rc = SQLITE_NOMEM;
  87064. return 1;
  87065. }
  87066. /*
  87067. ** Query the database. But instead of invoking a callback for each row,
  87068. ** malloc() for space to hold the result and return the entire results
  87069. ** at the conclusion of the call.
  87070. **
  87071. ** The result that is written to ***pazResult is held in memory obtained
  87072. ** from malloc(). But the caller cannot free this memory directly.
  87073. ** Instead, the entire table should be passed to sqlite3_free_table() when
  87074. ** the calling procedure is finished using it.
  87075. */
  87076. SQLITE_API int sqlite3_get_table(
  87077. sqlite3 *db, /* The database on which the SQL executes */
  87078. const char *zSql, /* The SQL to be executed */
  87079. char ***pazResult, /* Write the result table here */
  87080. int *pnRow, /* Write the number of rows in the result here */
  87081. int *pnColumn, /* Write the number of columns of result here */
  87082. char **pzErrMsg /* Write error messages here */
  87083. ){
  87084. int rc;
  87085. TabResult res;
  87086. *pazResult = 0;
  87087. if( pnColumn ) *pnColumn = 0;
  87088. if( pnRow ) *pnRow = 0;
  87089. if( pzErrMsg ) *pzErrMsg = 0;
  87090. res.zErrMsg = 0;
  87091. res.nRow = 0;
  87092. res.nColumn = 0;
  87093. res.nData = 1;
  87094. res.nAlloc = 20;
  87095. res.rc = SQLITE_OK;
  87096. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  87097. if( res.azResult==0 ){
  87098. db->errCode = SQLITE_NOMEM;
  87099. return SQLITE_NOMEM;
  87100. }
  87101. res.azResult[0] = 0;
  87102. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  87103. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  87104. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  87105. if( (rc&0xff)==SQLITE_ABORT ){
  87106. sqlite3_free_table(&res.azResult[1]);
  87107. if( res.zErrMsg ){
  87108. if( pzErrMsg ){
  87109. sqlite3_free(*pzErrMsg);
  87110. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  87111. }
  87112. sqlite3_free(res.zErrMsg);
  87113. }
  87114. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  87115. return res.rc;
  87116. }
  87117. sqlite3_free(res.zErrMsg);
  87118. if( rc!=SQLITE_OK ){
  87119. sqlite3_free_table(&res.azResult[1]);
  87120. return rc;
  87121. }
  87122. if( res.nAlloc>res.nData ){
  87123. char **azNew;
  87124. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  87125. if( azNew==0 ){
  87126. sqlite3_free_table(&res.azResult[1]);
  87127. db->errCode = SQLITE_NOMEM;
  87128. return SQLITE_NOMEM;
  87129. }
  87130. res.azResult = azNew;
  87131. }
  87132. *pazResult = &res.azResult[1];
  87133. if( pnColumn ) *pnColumn = res.nColumn;
  87134. if( pnRow ) *pnRow = res.nRow;
  87135. return rc;
  87136. }
  87137. /*
  87138. ** This routine frees the space the sqlite3_get_table() malloced.
  87139. */
  87140. SQLITE_API void sqlite3_free_table(
  87141. char **azResult /* Result returned from from sqlite3_get_table() */
  87142. ){
  87143. if( azResult ){
  87144. int i, n;
  87145. azResult--;
  87146. assert( azResult!=0 );
  87147. n = SQLITE_PTR_TO_INT(azResult[0]);
  87148. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  87149. sqlite3_free(azResult);
  87150. }
  87151. }
  87152. #endif /* SQLITE_OMIT_GET_TABLE */
  87153. /************** End of table.c ***********************************************/
  87154. /************** Begin file trigger.c *****************************************/
  87155. /*
  87156. **
  87157. ** The author disclaims copyright to this source code. In place of
  87158. ** a legal notice, here is a blessing:
  87159. **
  87160. ** May you do good and not evil.
  87161. ** May you find forgiveness for yourself and forgive others.
  87162. ** May you share freely, never taking more than you give.
  87163. **
  87164. *************************************************************************
  87165. ** This file contains the implementation for TRIGGERs
  87166. */
  87167. #ifndef SQLITE_OMIT_TRIGGER
  87168. /*
  87169. ** Delete a linked list of TriggerStep structures.
  87170. */
  87171. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  87172. while( pTriggerStep ){
  87173. TriggerStep * pTmp = pTriggerStep;
  87174. pTriggerStep = pTriggerStep->pNext;
  87175. sqlite3ExprDelete(db, pTmp->pWhere);
  87176. sqlite3ExprListDelete(db, pTmp->pExprList);
  87177. sqlite3SelectDelete(db, pTmp->pSelect);
  87178. sqlite3IdListDelete(db, pTmp->pIdList);
  87179. sqlite3DbFree(db, pTmp);
  87180. }
  87181. }
  87182. /*
  87183. ** Given table pTab, return a list of all the triggers attached to
  87184. ** the table. The list is connected by Trigger.pNext pointers.
  87185. **
  87186. ** All of the triggers on pTab that are in the same database as pTab
  87187. ** are already attached to pTab->pTrigger. But there might be additional
  87188. ** triggers on pTab in the TEMP schema. This routine prepends all
  87189. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  87190. ** and returns the combined list.
  87191. **
  87192. ** To state it another way: This routine returns a list of all triggers
  87193. ** that fire off of pTab. The list will include any TEMP triggers on
  87194. ** pTab as well as the triggers lised in pTab->pTrigger.
  87195. */
  87196. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  87197. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  87198. Trigger *pList = 0; /* List of triggers to return */
  87199. if( pParse->disableTriggers ){
  87200. return 0;
  87201. }
  87202. if( pTmpSchema!=pTab->pSchema ){
  87203. HashElem *p;
  87204. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  87205. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  87206. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  87207. if( pTrig->pTabSchema==pTab->pSchema
  87208. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  87209. ){
  87210. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  87211. pList = pTrig;
  87212. }
  87213. }
  87214. }
  87215. return (pList ? pList : pTab->pTrigger);
  87216. }
  87217. /*
  87218. ** This is called by the parser when it sees a CREATE TRIGGER statement
  87219. ** up to the point of the BEGIN before the trigger actions. A Trigger
  87220. ** structure is generated based on the information available and stored
  87221. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  87222. ** sqlite3FinishTrigger() function is called to complete the trigger
  87223. ** construction process.
  87224. */
  87225. SQLITE_PRIVATE void sqlite3BeginTrigger(
  87226. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  87227. Token *pName1, /* The name of the trigger */
  87228. Token *pName2, /* The name of the trigger */
  87229. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  87230. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  87231. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  87232. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  87233. Expr *pWhen, /* WHEN clause */
  87234. int isTemp, /* True if the TEMPORARY keyword is present */
  87235. int noErr /* Suppress errors if the trigger already exists */
  87236. ){
  87237. Trigger *pTrigger = 0; /* The new trigger */
  87238. Table *pTab; /* Table that the trigger fires off of */
  87239. char *zName = 0; /* Name of the trigger */
  87240. sqlite3 *db = pParse->db; /* The database connection */
  87241. int iDb; /* The database to store the trigger in */
  87242. Token *pName; /* The unqualified db name */
  87243. DbFixer sFix; /* State vector for the DB fixer */
  87244. int iTabDb; /* Index of the database holding pTab */
  87245. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  87246. assert( pName2!=0 );
  87247. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  87248. assert( op>0 && op<0xff );
  87249. if( isTemp ){
  87250. /* If TEMP was specified, then the trigger name may not be qualified. */
  87251. if( pName2->n>0 ){
  87252. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  87253. goto trigger_cleanup;
  87254. }
  87255. iDb = 1;
  87256. pName = pName1;
  87257. }else{
  87258. /* Figure out the db that the trigger will be created in */
  87259. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  87260. if( iDb<0 ){
  87261. goto trigger_cleanup;
  87262. }
  87263. }
  87264. if( !pTableName || db->mallocFailed ){
  87265. goto trigger_cleanup;
  87266. }
  87267. /* A long-standing parser bug is that this syntax was allowed:
  87268. **
  87269. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  87270. ** ^^^^^^^^
  87271. **
  87272. ** To maintain backwards compatibility, ignore the database
  87273. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  87274. */
  87275. if( db->init.busy && iDb!=1 ){
  87276. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  87277. pTableName->a[0].zDatabase = 0;
  87278. }
  87279. /* If the trigger name was unqualified, and the table is a temp table,
  87280. ** then set iDb to 1 to create the trigger in the temporary database.
  87281. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  87282. ** exist, the error is caught by the block below.
  87283. */
  87284. pTab = sqlite3SrcListLookup(pParse, pTableName);
  87285. if( db->init.busy==0 && pName2->n==0 && pTab
  87286. && pTab->pSchema==db->aDb[1].pSchema ){
  87287. iDb = 1;
  87288. }
  87289. /* Ensure the table name matches database name and that the table exists */
  87290. if( db->mallocFailed ) goto trigger_cleanup;
  87291. assert( pTableName->nSrc==1 );
  87292. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  87293. if( sqlite3FixSrcList(&sFix, pTableName) ){
  87294. goto trigger_cleanup;
  87295. }
  87296. pTab = sqlite3SrcListLookup(pParse, pTableName);
  87297. if( !pTab ){
  87298. /* The table does not exist. */
  87299. if( db->init.iDb==1 ){
  87300. /* Ticket #3810.
  87301. ** Normally, whenever a table is dropped, all associated triggers are
  87302. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  87303. ** and the table is dropped by a different database connection, the
  87304. ** trigger is not visible to the database connection that does the
  87305. ** drop so the trigger cannot be dropped. This results in an
  87306. ** "orphaned trigger" - a trigger whose associated table is missing.
  87307. */
  87308. db->init.orphanTrigger = 1;
  87309. }
  87310. goto trigger_cleanup;
  87311. }
  87312. if( IsVirtual(pTab) ){
  87313. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  87314. goto trigger_cleanup;
  87315. }
  87316. /* Check that the trigger name is not reserved and that no trigger of the
  87317. ** specified name exists */
  87318. zName = sqlite3NameFromToken(db, pName);
  87319. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  87320. goto trigger_cleanup;
  87321. }
  87322. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87323. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  87324. zName, sqlite3Strlen30(zName)) ){
  87325. if( !noErr ){
  87326. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  87327. }else{
  87328. assert( !db->init.busy );
  87329. sqlite3CodeVerifySchema(pParse, iDb);
  87330. }
  87331. goto trigger_cleanup;
  87332. }
  87333. /* Do not create a trigger on a system table */
  87334. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  87335. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  87336. pParse->nErr++;
  87337. goto trigger_cleanup;
  87338. }
  87339. /* INSTEAD of triggers are only for views and views only support INSTEAD
  87340. ** of triggers.
  87341. */
  87342. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  87343. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  87344. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  87345. goto trigger_cleanup;
  87346. }
  87347. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  87348. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  87349. " trigger on table: %S", pTableName, 0);
  87350. goto trigger_cleanup;
  87351. }
  87352. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87353. #ifndef SQLITE_OMIT_AUTHORIZATION
  87354. {
  87355. int code = SQLITE_CREATE_TRIGGER;
  87356. const char *zDb = db->aDb[iTabDb].zName;
  87357. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  87358. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  87359. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  87360. goto trigger_cleanup;
  87361. }
  87362. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  87363. goto trigger_cleanup;
  87364. }
  87365. }
  87366. #endif
  87367. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  87368. ** cannot appear on views. So we might as well translate every
  87369. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  87370. ** elsewhere.
  87371. */
  87372. if (tr_tm == TK_INSTEAD){
  87373. tr_tm = TK_BEFORE;
  87374. }
  87375. /* Build the Trigger object */
  87376. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  87377. if( pTrigger==0 ) goto trigger_cleanup;
  87378. pTrigger->zName = zName;
  87379. zName = 0;
  87380. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  87381. pTrigger->pSchema = db->aDb[iDb].pSchema;
  87382. pTrigger->pTabSchema = pTab->pSchema;
  87383. pTrigger->op = (u8)op;
  87384. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  87385. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  87386. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  87387. assert( pParse->pNewTrigger==0 );
  87388. pParse->pNewTrigger = pTrigger;
  87389. trigger_cleanup:
  87390. sqlite3DbFree(db, zName);
  87391. sqlite3SrcListDelete(db, pTableName);
  87392. sqlite3IdListDelete(db, pColumns);
  87393. sqlite3ExprDelete(db, pWhen);
  87394. if( !pParse->pNewTrigger ){
  87395. sqlite3DeleteTrigger(db, pTrigger);
  87396. }else{
  87397. assert( pParse->pNewTrigger==pTrigger );
  87398. }
  87399. }
  87400. /*
  87401. ** This routine is called after all of the trigger actions have been parsed
  87402. ** in order to complete the process of building the trigger.
  87403. */
  87404. SQLITE_PRIVATE void sqlite3FinishTrigger(
  87405. Parse *pParse, /* Parser context */
  87406. TriggerStep *pStepList, /* The triggered program */
  87407. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  87408. ){
  87409. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  87410. char *zName; /* Name of trigger */
  87411. sqlite3 *db = pParse->db; /* The database */
  87412. DbFixer sFix; /* Fixer object */
  87413. int iDb; /* Database containing the trigger */
  87414. Token nameToken; /* Trigger name for error reporting */
  87415. pParse->pNewTrigger = 0;
  87416. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  87417. zName = pTrig->zName;
  87418. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  87419. pTrig->step_list = pStepList;
  87420. while( pStepList ){
  87421. pStepList->pTrig = pTrig;
  87422. pStepList = pStepList->pNext;
  87423. }
  87424. nameToken.z = pTrig->zName;
  87425. nameToken.n = sqlite3Strlen30(nameToken.z);
  87426. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  87427. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  87428. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  87429. ){
  87430. goto triggerfinish_cleanup;
  87431. }
  87432. /* if we are not initializing,
  87433. ** build the sqlite_master entry
  87434. */
  87435. if( !db->init.busy ){
  87436. Vdbe *v;
  87437. char *z;
  87438. /* Make an entry in the sqlite_master table */
  87439. v = sqlite3GetVdbe(pParse);
  87440. if( v==0 ) goto triggerfinish_cleanup;
  87441. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87442. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  87443. sqlite3NestedParse(pParse,
  87444. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  87445. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  87446. pTrig->table, z);
  87447. sqlite3DbFree(db, z);
  87448. sqlite3ChangeCookie(pParse, iDb);
  87449. sqlite3VdbeAddParseSchemaOp(v, iDb,
  87450. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  87451. }
  87452. if( db->init.busy ){
  87453. Trigger *pLink = pTrig;
  87454. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  87455. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87456. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  87457. if( pTrig ){
  87458. db->mallocFailed = 1;
  87459. }else if( pLink->pSchema==pLink->pTabSchema ){
  87460. Table *pTab;
  87461. int n = sqlite3Strlen30(pLink->table);
  87462. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  87463. assert( pTab!=0 );
  87464. pLink->pNext = pTab->pTrigger;
  87465. pTab->pTrigger = pLink;
  87466. }
  87467. }
  87468. triggerfinish_cleanup:
  87469. sqlite3DeleteTrigger(db, pTrig);
  87470. assert( !pParse->pNewTrigger );
  87471. sqlite3DeleteTriggerStep(db, pStepList);
  87472. }
  87473. /*
  87474. ** Turn a SELECT statement (that the pSelect parameter points to) into
  87475. ** a trigger step. Return a pointer to a TriggerStep structure.
  87476. **
  87477. ** The parser calls this routine when it finds a SELECT statement in
  87478. ** body of a TRIGGER.
  87479. */
  87480. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  87481. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  87482. if( pTriggerStep==0 ) {
  87483. sqlite3SelectDelete(db, pSelect);
  87484. return 0;
  87485. }
  87486. pTriggerStep->op = TK_SELECT;
  87487. pTriggerStep->pSelect = pSelect;
  87488. pTriggerStep->orconf = OE_Default;
  87489. return pTriggerStep;
  87490. }
  87491. /*
  87492. ** Allocate space to hold a new trigger step. The allocated space
  87493. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  87494. **
  87495. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  87496. */
  87497. static TriggerStep *triggerStepAllocate(
  87498. sqlite3 *db, /* Database connection */
  87499. u8 op, /* Trigger opcode */
  87500. Token *pName /* The target name */
  87501. ){
  87502. TriggerStep *pTriggerStep;
  87503. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  87504. if( pTriggerStep ){
  87505. char *z = (char*)&pTriggerStep[1];
  87506. memcpy(z, pName->z, pName->n);
  87507. pTriggerStep->target.z = z;
  87508. pTriggerStep->target.n = pName->n;
  87509. pTriggerStep->op = op;
  87510. }
  87511. return pTriggerStep;
  87512. }
  87513. /*
  87514. ** Build a trigger step out of an INSERT statement. Return a pointer
  87515. ** to the new trigger step.
  87516. **
  87517. ** The parser calls this routine when it sees an INSERT inside the
  87518. ** body of a trigger.
  87519. */
  87520. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  87521. sqlite3 *db, /* The database connection */
  87522. Token *pTableName, /* Name of the table into which we insert */
  87523. IdList *pColumn, /* List of columns in pTableName to insert into */
  87524. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  87525. Select *pSelect, /* A SELECT statement that supplies values */
  87526. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  87527. ){
  87528. TriggerStep *pTriggerStep;
  87529. assert(pEList == 0 || pSelect == 0);
  87530. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  87531. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  87532. if( pTriggerStep ){
  87533. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  87534. pTriggerStep->pIdList = pColumn;
  87535. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  87536. pTriggerStep->orconf = orconf;
  87537. }else{
  87538. sqlite3IdListDelete(db, pColumn);
  87539. }
  87540. sqlite3ExprListDelete(db, pEList);
  87541. sqlite3SelectDelete(db, pSelect);
  87542. return pTriggerStep;
  87543. }
  87544. /*
  87545. ** Construct a trigger step that implements an UPDATE statement and return
  87546. ** a pointer to that trigger step. The parser calls this routine when it
  87547. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  87548. */
  87549. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  87550. sqlite3 *db, /* The database connection */
  87551. Token *pTableName, /* Name of the table to be updated */
  87552. ExprList *pEList, /* The SET clause: list of column and new values */
  87553. Expr *pWhere, /* The WHERE clause */
  87554. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  87555. ){
  87556. TriggerStep *pTriggerStep;
  87557. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  87558. if( pTriggerStep ){
  87559. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  87560. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  87561. pTriggerStep->orconf = orconf;
  87562. }
  87563. sqlite3ExprListDelete(db, pEList);
  87564. sqlite3ExprDelete(db, pWhere);
  87565. return pTriggerStep;
  87566. }
  87567. /*
  87568. ** Construct a trigger step that implements a DELETE statement and return
  87569. ** a pointer to that trigger step. The parser calls this routine when it
  87570. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  87571. */
  87572. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  87573. sqlite3 *db, /* Database connection */
  87574. Token *pTableName, /* The table from which rows are deleted */
  87575. Expr *pWhere /* The WHERE clause */
  87576. ){
  87577. TriggerStep *pTriggerStep;
  87578. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  87579. if( pTriggerStep ){
  87580. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  87581. pTriggerStep->orconf = OE_Default;
  87582. }
  87583. sqlite3ExprDelete(db, pWhere);
  87584. return pTriggerStep;
  87585. }
  87586. /*
  87587. ** Recursively delete a Trigger structure
  87588. */
  87589. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  87590. if( pTrigger==0 ) return;
  87591. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  87592. sqlite3DbFree(db, pTrigger->zName);
  87593. sqlite3DbFree(db, pTrigger->table);
  87594. sqlite3ExprDelete(db, pTrigger->pWhen);
  87595. sqlite3IdListDelete(db, pTrigger->pColumns);
  87596. sqlite3DbFree(db, pTrigger);
  87597. }
  87598. /*
  87599. ** This function is called to drop a trigger from the database schema.
  87600. **
  87601. ** This may be called directly from the parser and therefore identifies
  87602. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  87603. ** same job as this routine except it takes a pointer to the trigger
  87604. ** instead of the trigger name.
  87605. **/
  87606. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  87607. Trigger *pTrigger = 0;
  87608. int i;
  87609. const char *zDb;
  87610. const char *zName;
  87611. int nName;
  87612. sqlite3 *db = pParse->db;
  87613. if( db->mallocFailed ) goto drop_trigger_cleanup;
  87614. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87615. goto drop_trigger_cleanup;
  87616. }
  87617. assert( pName->nSrc==1 );
  87618. zDb = pName->a[0].zDatabase;
  87619. zName = pName->a[0].zName;
  87620. nName = sqlite3Strlen30(zName);
  87621. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  87622. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  87623. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  87624. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  87625. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  87626. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  87627. if( pTrigger ) break;
  87628. }
  87629. if( !pTrigger ){
  87630. if( !noErr ){
  87631. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  87632. }else{
  87633. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  87634. }
  87635. pParse->checkSchema = 1;
  87636. goto drop_trigger_cleanup;
  87637. }
  87638. sqlite3DropTriggerPtr(pParse, pTrigger);
  87639. drop_trigger_cleanup:
  87640. sqlite3SrcListDelete(db, pName);
  87641. }
  87642. /*
  87643. ** Return a pointer to the Table structure for the table that a trigger
  87644. ** is set on.
  87645. */
  87646. static Table *tableOfTrigger(Trigger *pTrigger){
  87647. int n = sqlite3Strlen30(pTrigger->table);
  87648. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  87649. }
  87650. /*
  87651. ** Drop a trigger given a pointer to that trigger.
  87652. */
  87653. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  87654. Table *pTable;
  87655. Vdbe *v;
  87656. sqlite3 *db = pParse->db;
  87657. int iDb;
  87658. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  87659. assert( iDb>=0 && iDb<db->nDb );
  87660. pTable = tableOfTrigger(pTrigger);
  87661. assert( pTable );
  87662. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  87663. #ifndef SQLITE_OMIT_AUTHORIZATION
  87664. {
  87665. int code = SQLITE_DROP_TRIGGER;
  87666. const char *zDb = db->aDb[iDb].zName;
  87667. const char *zTab = SCHEMA_TABLE(iDb);
  87668. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  87669. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  87670. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  87671. return;
  87672. }
  87673. }
  87674. #endif
  87675. /* Generate code to destroy the database record of the trigger.
  87676. */
  87677. assert( pTable!=0 );
  87678. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  87679. int base;
  87680. static const VdbeOpList dropTrigger[] = {
  87681. { OP_Rewind, 0, ADDR(9), 0},
  87682. { OP_String8, 0, 1, 0}, /* 1 */
  87683. { OP_Column, 0, 1, 2},
  87684. { OP_Ne, 2, ADDR(8), 1},
  87685. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  87686. { OP_Column, 0, 0, 2},
  87687. { OP_Ne, 2, ADDR(8), 1},
  87688. { OP_Delete, 0, 0, 0},
  87689. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  87690. };
  87691. sqlite3BeginWriteOperation(pParse, 0, iDb);
  87692. sqlite3OpenMasterTable(pParse, iDb);
  87693. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  87694. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  87695. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  87696. sqlite3ChangeCookie(pParse, iDb);
  87697. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  87698. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  87699. if( pParse->nMem<3 ){
  87700. pParse->nMem = 3;
  87701. }
  87702. }
  87703. }
  87704. /*
  87705. ** Remove a trigger from the hash tables of the sqlite* pointer.
  87706. */
  87707. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  87708. Trigger *pTrigger;
  87709. Hash *pHash;
  87710. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87711. pHash = &(db->aDb[iDb].pSchema->trigHash);
  87712. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  87713. if( ALWAYS(pTrigger) ){
  87714. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  87715. Table *pTab = tableOfTrigger(pTrigger);
  87716. Trigger **pp;
  87717. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  87718. *pp = (*pp)->pNext;
  87719. }
  87720. sqlite3DeleteTrigger(db, pTrigger);
  87721. db->flags |= SQLITE_InternChanges;
  87722. }
  87723. }
  87724. /*
  87725. ** pEList is the SET clause of an UPDATE statement. Each entry
  87726. ** in pEList is of the format <id>=<expr>. If any of the entries
  87727. ** in pEList have an <id> which matches an identifier in pIdList,
  87728. ** then return TRUE. If pIdList==NULL, then it is considered a
  87729. ** wildcard that matches anything. Likewise if pEList==NULL then
  87730. ** it matches anything so always return true. Return false only
  87731. ** if there is no match.
  87732. */
  87733. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  87734. int e;
  87735. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  87736. for(e=0; e<pEList->nExpr; e++){
  87737. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  87738. }
  87739. return 0;
  87740. }
  87741. /*
  87742. ** Return a list of all triggers on table pTab if there exists at least
  87743. ** one trigger that must be fired when an operation of type 'op' is
  87744. ** performed on the table, and, if that operation is an UPDATE, if at
  87745. ** least one of the columns in pChanges is being modified.
  87746. */
  87747. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  87748. Parse *pParse, /* Parse context */
  87749. Table *pTab, /* The table the contains the triggers */
  87750. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  87751. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  87752. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  87753. ){
  87754. int mask = 0;
  87755. Trigger *pList = 0;
  87756. Trigger *p;
  87757. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  87758. pList = sqlite3TriggerList(pParse, pTab);
  87759. }
  87760. assert( pList==0 || IsVirtual(pTab)==0 );
  87761. for(p=pList; p; p=p->pNext){
  87762. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  87763. mask |= p->tr_tm;
  87764. }
  87765. }
  87766. if( pMask ){
  87767. *pMask = mask;
  87768. }
  87769. return (mask ? pList : 0);
  87770. }
  87771. /*
  87772. ** Convert the pStep->target token into a SrcList and return a pointer
  87773. ** to that SrcList.
  87774. **
  87775. ** This routine adds a specific database name, if needed, to the target when
  87776. ** forming the SrcList. This prevents a trigger in one database from
  87777. ** referring to a target in another database. An exception is when the
  87778. ** trigger is in TEMP in which case it can refer to any other database it
  87779. ** wants.
  87780. */
  87781. static SrcList *targetSrcList(
  87782. Parse *pParse, /* The parsing context */
  87783. TriggerStep *pStep /* The trigger containing the target token */
  87784. ){
  87785. int iDb; /* Index of the database to use */
  87786. SrcList *pSrc; /* SrcList to be returned */
  87787. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  87788. if( pSrc ){
  87789. assert( pSrc->nSrc>0 );
  87790. assert( pSrc->a!=0 );
  87791. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  87792. if( iDb==0 || iDb>=2 ){
  87793. sqlite3 *db = pParse->db;
  87794. assert( iDb<pParse->db->nDb );
  87795. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  87796. }
  87797. }
  87798. return pSrc;
  87799. }
  87800. /*
  87801. ** Generate VDBE code for the statements inside the body of a single
  87802. ** trigger.
  87803. */
  87804. static int codeTriggerProgram(
  87805. Parse *pParse, /* The parser context */
  87806. TriggerStep *pStepList, /* List of statements inside the trigger body */
  87807. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  87808. ){
  87809. TriggerStep *pStep;
  87810. Vdbe *v = pParse->pVdbe;
  87811. sqlite3 *db = pParse->db;
  87812. assert( pParse->pTriggerTab && pParse->pToplevel );
  87813. assert( pStepList );
  87814. assert( v!=0 );
  87815. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  87816. /* Figure out the ON CONFLICT policy that will be used for this step
  87817. ** of the trigger program. If the statement that caused this trigger
  87818. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  87819. ** the ON CONFLICT policy that was specified as part of the trigger
  87820. ** step statement. Example:
  87821. **
  87822. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  87823. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  87824. ** END;
  87825. **
  87826. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  87827. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  87828. */
  87829. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  87830. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  87831. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  87832. ** that it is not safe to refactor constants (this happens after the
  87833. ** start of the first loop in the SQL statement is coded - at that
  87834. ** point code may be conditionally executed, so it is no longer safe to
  87835. ** initialize constant register values). */
  87836. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  87837. pParse->cookieGoto = 0;
  87838. switch( pStep->op ){
  87839. case TK_UPDATE: {
  87840. sqlite3Update(pParse,
  87841. targetSrcList(pParse, pStep),
  87842. sqlite3ExprListDup(db, pStep->pExprList, 0),
  87843. sqlite3ExprDup(db, pStep->pWhere, 0),
  87844. pParse->eOrconf
  87845. );
  87846. break;
  87847. }
  87848. case TK_INSERT: {
  87849. sqlite3Insert(pParse,
  87850. targetSrcList(pParse, pStep),
  87851. sqlite3ExprListDup(db, pStep->pExprList, 0),
  87852. sqlite3SelectDup(db, pStep->pSelect, 0),
  87853. sqlite3IdListDup(db, pStep->pIdList),
  87854. pParse->eOrconf
  87855. );
  87856. break;
  87857. }
  87858. case TK_DELETE: {
  87859. sqlite3DeleteFrom(pParse,
  87860. targetSrcList(pParse, pStep),
  87861. sqlite3ExprDup(db, pStep->pWhere, 0)
  87862. );
  87863. break;
  87864. }
  87865. default: assert( pStep->op==TK_SELECT ); {
  87866. SelectDest sDest;
  87867. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  87868. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  87869. sqlite3Select(pParse, pSelect, &sDest);
  87870. sqlite3SelectDelete(db, pSelect);
  87871. break;
  87872. }
  87873. }
  87874. if( pStep->op!=TK_SELECT ){
  87875. sqlite3VdbeAddOp0(v, OP_ResetCount);
  87876. }
  87877. }
  87878. return 0;
  87879. }
  87880. #ifdef SQLITE_DEBUG
  87881. /*
  87882. ** This function is used to add VdbeComment() annotations to a VDBE
  87883. ** program. It is not used in production code, only for debugging.
  87884. */
  87885. static const char *onErrorText(int onError){
  87886. switch( onError ){
  87887. case OE_Abort: return "abort";
  87888. case OE_Rollback: return "rollback";
  87889. case OE_Fail: return "fail";
  87890. case OE_Replace: return "replace";
  87891. case OE_Ignore: return "ignore";
  87892. case OE_Default: return "default";
  87893. }
  87894. return "n/a";
  87895. }
  87896. #endif
  87897. /*
  87898. ** Parse context structure pFrom has just been used to create a sub-vdbe
  87899. ** (trigger program). If an error has occurred, transfer error information
  87900. ** from pFrom to pTo.
  87901. */
  87902. static void transferParseError(Parse *pTo, Parse *pFrom){
  87903. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  87904. assert( pTo->zErrMsg==0 || pTo->nErr );
  87905. if( pTo->nErr==0 ){
  87906. pTo->zErrMsg = pFrom->zErrMsg;
  87907. pTo->nErr = pFrom->nErr;
  87908. }else{
  87909. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  87910. }
  87911. }
  87912. /*
  87913. ** Create and populate a new TriggerPrg object with a sub-program
  87914. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  87915. */
  87916. static TriggerPrg *codeRowTrigger(
  87917. Parse *pParse, /* Current parse context */
  87918. Trigger *pTrigger, /* Trigger to code */
  87919. Table *pTab, /* The table pTrigger is attached to */
  87920. int orconf /* ON CONFLICT policy to code trigger program with */
  87921. ){
  87922. Parse *pTop = sqlite3ParseToplevel(pParse);
  87923. sqlite3 *db = pParse->db; /* Database handle */
  87924. TriggerPrg *pPrg; /* Value to return */
  87925. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  87926. Vdbe *v; /* Temporary VM */
  87927. NameContext sNC; /* Name context for sub-vdbe */
  87928. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  87929. Parse *pSubParse; /* Parse context for sub-vdbe */
  87930. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  87931. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  87932. assert( pTop->pVdbe );
  87933. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  87934. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  87935. ** list of the top-level Parse object sooner rather than later. */
  87936. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  87937. if( !pPrg ) return 0;
  87938. pPrg->pNext = pTop->pTriggerPrg;
  87939. pTop->pTriggerPrg = pPrg;
  87940. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  87941. if( !pProgram ) return 0;
  87942. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  87943. pPrg->pTrigger = pTrigger;
  87944. pPrg->orconf = orconf;
  87945. pPrg->aColmask[0] = 0xffffffff;
  87946. pPrg->aColmask[1] = 0xffffffff;
  87947. /* Allocate and populate a new Parse context to use for coding the
  87948. ** trigger sub-program. */
  87949. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  87950. if( !pSubParse ) return 0;
  87951. memset(&sNC, 0, sizeof(sNC));
  87952. sNC.pParse = pSubParse;
  87953. pSubParse->db = db;
  87954. pSubParse->pTriggerTab = pTab;
  87955. pSubParse->pToplevel = pTop;
  87956. pSubParse->zAuthContext = pTrigger->zName;
  87957. pSubParse->eTriggerOp = pTrigger->op;
  87958. pSubParse->nQueryLoop = pParse->nQueryLoop;
  87959. v = sqlite3GetVdbe(pSubParse);
  87960. if( v ){
  87961. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  87962. pTrigger->zName, onErrorText(orconf),
  87963. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  87964. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  87965. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  87966. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  87967. pTab->zName
  87968. ));
  87969. #ifndef SQLITE_OMIT_TRACE
  87970. sqlite3VdbeChangeP4(v, -1,
  87971. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  87972. );
  87973. #endif
  87974. /* If one was specified, code the WHEN clause. If it evaluates to false
  87975. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  87976. ** OP_Halt inserted at the end of the program. */
  87977. if( pTrigger->pWhen ){
  87978. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  87979. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  87980. && db->mallocFailed==0
  87981. ){
  87982. iEndTrigger = sqlite3VdbeMakeLabel(v);
  87983. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  87984. }
  87985. sqlite3ExprDelete(db, pWhen);
  87986. }
  87987. /* Code the trigger program into the sub-vdbe. */
  87988. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  87989. /* Insert an OP_Halt at the end of the sub-program. */
  87990. if( iEndTrigger ){
  87991. sqlite3VdbeResolveLabel(v, iEndTrigger);
  87992. }
  87993. sqlite3VdbeAddOp0(v, OP_Halt);
  87994. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  87995. transferParseError(pParse, pSubParse);
  87996. if( db->mallocFailed==0 ){
  87997. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  87998. }
  87999. pProgram->nMem = pSubParse->nMem;
  88000. pProgram->nCsr = pSubParse->nTab;
  88001. pProgram->nOnce = pSubParse->nOnce;
  88002. pProgram->token = (void *)pTrigger;
  88003. pPrg->aColmask[0] = pSubParse->oldmask;
  88004. pPrg->aColmask[1] = pSubParse->newmask;
  88005. sqlite3VdbeDelete(v);
  88006. }
  88007. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  88008. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  88009. sqlite3StackFree(db, pSubParse);
  88010. return pPrg;
  88011. }
  88012. /*
  88013. ** Return a pointer to a TriggerPrg object containing the sub-program for
  88014. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  88015. ** TriggerPrg object exists, a new object is allocated and populated before
  88016. ** being returned.
  88017. */
  88018. static TriggerPrg *getRowTrigger(
  88019. Parse *pParse, /* Current parse context */
  88020. Trigger *pTrigger, /* Trigger to code */
  88021. Table *pTab, /* The table trigger pTrigger is attached to */
  88022. int orconf /* ON CONFLICT algorithm. */
  88023. ){
  88024. Parse *pRoot = sqlite3ParseToplevel(pParse);
  88025. TriggerPrg *pPrg;
  88026. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  88027. /* It may be that this trigger has already been coded (or is in the
  88028. ** process of being coded). If this is the case, then an entry with
  88029. ** a matching TriggerPrg.pTrigger field will be present somewhere
  88030. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  88031. for(pPrg=pRoot->pTriggerPrg;
  88032. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  88033. pPrg=pPrg->pNext
  88034. );
  88035. /* If an existing TriggerPrg could not be located, create a new one. */
  88036. if( !pPrg ){
  88037. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  88038. }
  88039. return pPrg;
  88040. }
  88041. /*
  88042. ** Generate code for the trigger program associated with trigger p on
  88043. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  88044. ** function are the same as those described in the header function for
  88045. ** sqlite3CodeRowTrigger()
  88046. */
  88047. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  88048. Parse *pParse, /* Parse context */
  88049. Trigger *p, /* Trigger to code */
  88050. Table *pTab, /* The table to code triggers from */
  88051. int reg, /* Reg array containing OLD.* and NEW.* values */
  88052. int orconf, /* ON CONFLICT policy */
  88053. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  88054. ){
  88055. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  88056. TriggerPrg *pPrg;
  88057. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  88058. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  88059. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  88060. ** is a pointer to the sub-vdbe containing the trigger program. */
  88061. if( pPrg ){
  88062. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  88063. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  88064. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  88065. VdbeComment(
  88066. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  88067. /* Set the P5 operand of the OP_Program instruction to non-zero if
  88068. ** recursive invocation of this trigger program is disallowed. Recursive
  88069. ** invocation is disallowed if (a) the sub-program is really a trigger,
  88070. ** not a foreign key action, and (b) the flag to enable recursive triggers
  88071. ** is clear. */
  88072. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  88073. }
  88074. }
  88075. /*
  88076. ** This is called to code the required FOR EACH ROW triggers for an operation
  88077. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  88078. ** is given by the op parameter. The tr_tm parameter determines whether the
  88079. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  88080. ** parameter pChanges is passed the list of columns being modified.
  88081. **
  88082. ** If there are no triggers that fire at the specified time for the specified
  88083. ** operation on pTab, this function is a no-op.
  88084. **
  88085. ** The reg argument is the address of the first in an array of registers
  88086. ** that contain the values substituted for the new.* and old.* references
  88087. ** in the trigger program. If N is the number of columns in table pTab
  88088. ** (a copy of pTab->nCol), then registers are populated as follows:
  88089. **
  88090. ** Register Contains
  88091. ** ------------------------------------------------------
  88092. ** reg+0 OLD.rowid
  88093. ** reg+1 OLD.* value of left-most column of pTab
  88094. ** ... ...
  88095. ** reg+N OLD.* value of right-most column of pTab
  88096. ** reg+N+1 NEW.rowid
  88097. ** reg+N+2 OLD.* value of left-most column of pTab
  88098. ** ... ...
  88099. ** reg+N+N+1 NEW.* value of right-most column of pTab
  88100. **
  88101. ** For ON DELETE triggers, the registers containing the NEW.* values will
  88102. ** never be accessed by the trigger program, so they are not allocated or
  88103. ** populated by the caller (there is no data to populate them with anyway).
  88104. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  88105. ** are never accessed, and so are not allocated by the caller. So, for an
  88106. ** ON INSERT trigger, the value passed to this function as parameter reg
  88107. ** is not a readable register, although registers (reg+N) through
  88108. ** (reg+N+N+1) are.
  88109. **
  88110. ** Parameter orconf is the default conflict resolution algorithm for the
  88111. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  88112. ** is the instruction that control should jump to if a trigger program
  88113. ** raises an IGNORE exception.
  88114. */
  88115. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  88116. Parse *pParse, /* Parse context */
  88117. Trigger *pTrigger, /* List of triggers on table pTab */
  88118. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  88119. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  88120. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  88121. Table *pTab, /* The table to code triggers from */
  88122. int reg, /* The first in an array of registers (see above) */
  88123. int orconf, /* ON CONFLICT policy */
  88124. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  88125. ){
  88126. Trigger *p; /* Used to iterate through pTrigger list */
  88127. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  88128. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  88129. assert( (op==TK_UPDATE)==(pChanges!=0) );
  88130. for(p=pTrigger; p; p=p->pNext){
  88131. /* Sanity checking: The schema for the trigger and for the table are
  88132. ** always defined. The trigger must be in the same schema as the table
  88133. ** or else it must be a TEMP trigger. */
  88134. assert( p->pSchema!=0 );
  88135. assert( p->pTabSchema!=0 );
  88136. assert( p->pSchema==p->pTabSchema
  88137. || p->pSchema==pParse->db->aDb[1].pSchema );
  88138. /* Determine whether we should code this trigger */
  88139. if( p->op==op
  88140. && p->tr_tm==tr_tm
  88141. && checkColumnOverlap(p->pColumns, pChanges)
  88142. ){
  88143. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  88144. }
  88145. }
  88146. }
  88147. /*
  88148. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  88149. ** This function returns a 32-bit bitmask indicating which columns of the
  88150. ** old.* or new.* tables actually are used by triggers. This information
  88151. ** may be used by the caller, for example, to avoid having to load the entire
  88152. ** old.* record into memory when executing an UPDATE or DELETE command.
  88153. **
  88154. ** Bit 0 of the returned mask is set if the left-most column of the
  88155. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  88156. ** the second leftmost column value is required, and so on. If there
  88157. ** are more than 32 columns in the table, and at least one of the columns
  88158. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  88159. **
  88160. ** It is not possible to determine if the old.rowid or new.rowid column is
  88161. ** accessed by triggers. The caller must always assume that it is.
  88162. **
  88163. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  88164. ** applies to the old.* table. If 1, the new.* table.
  88165. **
  88166. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  88167. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  88168. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  88169. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  88170. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  88171. */
  88172. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  88173. Parse *pParse, /* Parse context */
  88174. Trigger *pTrigger, /* List of triggers on table pTab */
  88175. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  88176. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  88177. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  88178. Table *pTab, /* The table to code triggers from */
  88179. int orconf /* Default ON CONFLICT policy for trigger steps */
  88180. ){
  88181. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  88182. u32 mask = 0;
  88183. Trigger *p;
  88184. assert( isNew==1 || isNew==0 );
  88185. for(p=pTrigger; p; p=p->pNext){
  88186. if( p->op==op && (tr_tm&p->tr_tm)
  88187. && checkColumnOverlap(p->pColumns,pChanges)
  88188. ){
  88189. TriggerPrg *pPrg;
  88190. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  88191. if( pPrg ){
  88192. mask |= pPrg->aColmask[isNew];
  88193. }
  88194. }
  88195. }
  88196. return mask;
  88197. }
  88198. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  88199. /************** End of trigger.c *********************************************/
  88200. /************** Begin file update.c ******************************************/
  88201. /*
  88202. ** 2001 September 15
  88203. **
  88204. ** The author disclaims copyright to this source code. In place of
  88205. ** a legal notice, here is a blessing:
  88206. **
  88207. ** May you do good and not evil.
  88208. ** May you find forgiveness for yourself and forgive others.
  88209. ** May you share freely, never taking more than you give.
  88210. **
  88211. *************************************************************************
  88212. ** This file contains C code routines that are called by the parser
  88213. ** to handle UPDATE statements.
  88214. */
  88215. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88216. /* Forward declaration */
  88217. static void updateVirtualTable(
  88218. Parse *pParse, /* The parsing context */
  88219. SrcList *pSrc, /* The virtual table to be modified */
  88220. Table *pTab, /* The virtual table */
  88221. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  88222. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  88223. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  88224. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  88225. int onError /* ON CONFLICT strategy */
  88226. );
  88227. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  88228. /*
  88229. ** The most recently coded instruction was an OP_Column to retrieve the
  88230. ** i-th column of table pTab. This routine sets the P4 parameter of the
  88231. ** OP_Column to the default value, if any.
  88232. **
  88233. ** The default value of a column is specified by a DEFAULT clause in the
  88234. ** column definition. This was either supplied by the user when the table
  88235. ** was created, or added later to the table definition by an ALTER TABLE
  88236. ** command. If the latter, then the row-records in the table btree on disk
  88237. ** may not contain a value for the column and the default value, taken
  88238. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  88239. ** If the former, then all row-records are guaranteed to include a value
  88240. ** for the column and the P4 value is not required.
  88241. **
  88242. ** Column definitions created by an ALTER TABLE command may only have
  88243. ** literal default values specified: a number, null or a string. (If a more
  88244. ** complicated default expression value was provided, it is evaluated
  88245. ** when the ALTER TABLE is executed and one of the literal values written
  88246. ** into the sqlite_master table.)
  88247. **
  88248. ** Therefore, the P4 parameter is only required if the default value for
  88249. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  88250. ** function is capable of transforming these types of expressions into
  88251. ** sqlite3_value objects.
  88252. **
  88253. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  88254. ** on register iReg. This is used when an equivalent integer value is
  88255. ** stored in place of an 8-byte floating point value in order to save
  88256. ** space.
  88257. */
  88258. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  88259. assert( pTab!=0 );
  88260. if( !pTab->pSelect ){
  88261. sqlite3_value *pValue = 0;
  88262. u8 enc = ENC(sqlite3VdbeDb(v));
  88263. Column *pCol = &pTab->aCol[i];
  88264. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  88265. assert( i<pTab->nCol );
  88266. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  88267. pCol->affinity, &pValue);
  88268. if( pValue ){
  88269. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  88270. }
  88271. #ifndef SQLITE_OMIT_FLOATING_POINT
  88272. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  88273. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  88274. }
  88275. #endif
  88276. }
  88277. }
  88278. /*
  88279. ** Process an UPDATE statement.
  88280. **
  88281. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  88282. ** \_______/ \________/ \______/ \________________/
  88283. * onError pTabList pChanges pWhere
  88284. */
  88285. SQLITE_PRIVATE void sqlite3Update(
  88286. Parse *pParse, /* The parser context */
  88287. SrcList *pTabList, /* The table in which we should change things */
  88288. ExprList *pChanges, /* Things to be changed */
  88289. Expr *pWhere, /* The WHERE clause. May be null */
  88290. int onError /* How to handle constraint errors */
  88291. ){
  88292. int i, j; /* Loop counters */
  88293. Table *pTab; /* The table to be updated */
  88294. int addr = 0; /* VDBE instruction address of the start of the loop */
  88295. WhereInfo *pWInfo; /* Information about the WHERE clause */
  88296. Vdbe *v; /* The virtual database engine */
  88297. Index *pIdx; /* For looping over indices */
  88298. int nIdx; /* Number of indices that need updating */
  88299. int iCur; /* VDBE Cursor number of pTab */
  88300. sqlite3 *db; /* The database structure */
  88301. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  88302. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  88303. ** an expression for the i-th column of the table.
  88304. ** aXRef[i]==-1 if the i-th column is not changed. */
  88305. int chngRowid; /* True if the record number is being changed */
  88306. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  88307. int openAll = 0; /* True if all indices need to be opened */
  88308. AuthContext sContext; /* The authorization context */
  88309. NameContext sNC; /* The name-context to resolve expressions in */
  88310. int iDb; /* Database containing the table being updated */
  88311. int okOnePass; /* True for one-pass algorithm without the FIFO */
  88312. int hasFK; /* True if foreign key processing is required */
  88313. #ifndef SQLITE_OMIT_TRIGGER
  88314. int isView; /* True when updating a view (INSTEAD OF trigger) */
  88315. Trigger *pTrigger; /* List of triggers on pTab, if required */
  88316. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  88317. #endif
  88318. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  88319. /* Register Allocations */
  88320. int regRowCount = 0; /* A count of rows changed */
  88321. int regOldRowid; /* The old rowid */
  88322. int regNewRowid; /* The new rowid */
  88323. int regNew; /* Content of the NEW.* table in triggers */
  88324. int regOld = 0; /* Content of OLD.* table in triggers */
  88325. int regRowSet = 0; /* Rowset of rows to be updated */
  88326. memset(&sContext, 0, sizeof(sContext));
  88327. db = pParse->db;
  88328. if( pParse->nErr || db->mallocFailed ){
  88329. goto update_cleanup;
  88330. }
  88331. assert( pTabList->nSrc==1 );
  88332. /* Locate the table which we want to update.
  88333. */
  88334. pTab = sqlite3SrcListLookup(pParse, pTabList);
  88335. if( pTab==0 ) goto update_cleanup;
  88336. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88337. /* Figure out if we have any triggers and if the table being
  88338. ** updated is a view.
  88339. */
  88340. #ifndef SQLITE_OMIT_TRIGGER
  88341. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  88342. isView = pTab->pSelect!=0;
  88343. assert( pTrigger || tmask==0 );
  88344. #else
  88345. # define pTrigger 0
  88346. # define isView 0
  88347. # define tmask 0
  88348. #endif
  88349. #ifdef SQLITE_OMIT_VIEW
  88350. # undef isView
  88351. # define isView 0
  88352. #endif
  88353. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  88354. goto update_cleanup;
  88355. }
  88356. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  88357. goto update_cleanup;
  88358. }
  88359. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  88360. if( aXRef==0 ) goto update_cleanup;
  88361. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  88362. /* Allocate a cursors for the main database table and for all indices.
  88363. ** The index cursors might not be used, but if they are used they
  88364. ** need to occur right after the database cursor. So go ahead and
  88365. ** allocate enough space, just in case.
  88366. */
  88367. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  88368. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88369. pParse->nTab++;
  88370. }
  88371. /* Initialize the name-context */
  88372. memset(&sNC, 0, sizeof(sNC));
  88373. sNC.pParse = pParse;
  88374. sNC.pSrcList = pTabList;
  88375. /* Resolve the column names in all the expressions of the
  88376. ** of the UPDATE statement. Also find the column index
  88377. ** for each column to be updated in the pChanges array. For each
  88378. ** column to be updated, make sure we have authorization to change
  88379. ** that column.
  88380. */
  88381. chngRowid = 0;
  88382. for(i=0; i<pChanges->nExpr; i++){
  88383. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  88384. goto update_cleanup;
  88385. }
  88386. for(j=0; j<pTab->nCol; j++){
  88387. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  88388. if( j==pTab->iPKey ){
  88389. chngRowid = 1;
  88390. pRowidExpr = pChanges->a[i].pExpr;
  88391. }
  88392. aXRef[j] = i;
  88393. break;
  88394. }
  88395. }
  88396. if( j>=pTab->nCol ){
  88397. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  88398. j = -1;
  88399. chngRowid = 1;
  88400. pRowidExpr = pChanges->a[i].pExpr;
  88401. }else{
  88402. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  88403. pParse->checkSchema = 1;
  88404. goto update_cleanup;
  88405. }
  88406. }
  88407. #ifndef SQLITE_OMIT_AUTHORIZATION
  88408. {
  88409. int rc;
  88410. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  88411. j<0 ? "ROWID" : pTab->aCol[j].zName,
  88412. db->aDb[iDb].zName);
  88413. if( rc==SQLITE_DENY ){
  88414. goto update_cleanup;
  88415. }else if( rc==SQLITE_IGNORE ){
  88416. aXRef[j] = -1;
  88417. }
  88418. }
  88419. #endif
  88420. }
  88421. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  88422. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  88423. ** array for each index associated with table being updated. Fill in
  88424. ** the value with a register number for indices that are to be used
  88425. ** and with zero for unused indices.
  88426. */
  88427. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  88428. if( nIdx>0 ){
  88429. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  88430. if( aRegIdx==0 ) goto update_cleanup;
  88431. }
  88432. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  88433. int reg;
  88434. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  88435. reg = ++pParse->nMem;
  88436. }else{
  88437. reg = 0;
  88438. for(i=0; i<pIdx->nColumn; i++){
  88439. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  88440. reg = ++pParse->nMem;
  88441. break;
  88442. }
  88443. }
  88444. }
  88445. aRegIdx[j] = reg;
  88446. }
  88447. /* Begin generating code. */
  88448. v = sqlite3GetVdbe(pParse);
  88449. if( v==0 ) goto update_cleanup;
  88450. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  88451. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88452. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88453. /* Virtual tables must be handled separately */
  88454. if( IsVirtual(pTab) ){
  88455. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  88456. pWhere, onError);
  88457. pWhere = 0;
  88458. pTabList = 0;
  88459. goto update_cleanup;
  88460. }
  88461. #endif
  88462. /* Allocate required registers. */
  88463. regRowSet = ++pParse->nMem;
  88464. regOldRowid = regNewRowid = ++pParse->nMem;
  88465. if( pTrigger || hasFK ){
  88466. regOld = pParse->nMem + 1;
  88467. pParse->nMem += pTab->nCol;
  88468. }
  88469. if( chngRowid || pTrigger || hasFK ){
  88470. regNewRowid = ++pParse->nMem;
  88471. }
  88472. regNew = pParse->nMem + 1;
  88473. pParse->nMem += pTab->nCol;
  88474. /* Start the view context. */
  88475. if( isView ){
  88476. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  88477. }
  88478. /* If we are trying to update a view, realize that view into
  88479. ** a ephemeral table.
  88480. */
  88481. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  88482. if( isView ){
  88483. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  88484. }
  88485. #endif
  88486. /* Resolve the column names in all the expressions in the
  88487. ** WHERE clause.
  88488. */
  88489. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  88490. goto update_cleanup;
  88491. }
  88492. /* Begin the database scan
  88493. */
  88494. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  88495. pWInfo = sqlite3WhereBegin(
  88496. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  88497. );
  88498. if( pWInfo==0 ) goto update_cleanup;
  88499. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  88500. /* Remember the rowid of every item to be updated.
  88501. */
  88502. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  88503. if( !okOnePass ){
  88504. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  88505. }
  88506. /* End the database scan loop.
  88507. */
  88508. sqlite3WhereEnd(pWInfo);
  88509. /* Initialize the count of updated rows
  88510. */
  88511. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  88512. regRowCount = ++pParse->nMem;
  88513. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  88514. }
  88515. if( !isView ){
  88516. /*
  88517. ** Open every index that needs updating. Note that if any
  88518. ** index could potentially invoke a REPLACE conflict resolution
  88519. ** action, then we need to open all indices because we might need
  88520. ** to be deleting some records.
  88521. */
  88522. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  88523. if( onError==OE_Replace ){
  88524. openAll = 1;
  88525. }else{
  88526. openAll = 0;
  88527. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88528. if( pIdx->onError==OE_Replace ){
  88529. openAll = 1;
  88530. break;
  88531. }
  88532. }
  88533. }
  88534. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  88535. assert( aRegIdx );
  88536. if( openAll || aRegIdx[i]>0 ){
  88537. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  88538. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  88539. (char*)pKey, P4_KEYINFO_HANDOFF);
  88540. assert( pParse->nTab>iCur+i+1 );
  88541. }
  88542. }
  88543. }
  88544. /* Top of the update loop */
  88545. if( okOnePass ){
  88546. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  88547. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  88548. sqlite3VdbeJumpHere(v, a1);
  88549. }else{
  88550. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  88551. }
  88552. /* Make cursor iCur point to the record that is being updated. If
  88553. ** this record does not exist for some reason (deleted by a trigger,
  88554. ** for example, then jump to the next iteration of the RowSet loop. */
  88555. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  88556. /* If the record number will change, set register regNewRowid to
  88557. ** contain the new value. If the record number is not being modified,
  88558. ** then regNewRowid is the same register as regOldRowid, which is
  88559. ** already populated. */
  88560. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  88561. if( chngRowid ){
  88562. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  88563. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  88564. }
  88565. /* If there are triggers on this table, populate an array of registers
  88566. ** with the required old.* column data. */
  88567. if( hasFK || pTrigger ){
  88568. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  88569. oldmask |= sqlite3TriggerColmask(pParse,
  88570. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  88571. );
  88572. for(i=0; i<pTab->nCol; i++){
  88573. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  88574. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  88575. }else{
  88576. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  88577. }
  88578. }
  88579. if( chngRowid==0 ){
  88580. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  88581. }
  88582. }
  88583. /* Populate the array of registers beginning at regNew with the new
  88584. ** row data. This array is used to check constaints, create the new
  88585. ** table and index records, and as the values for any new.* references
  88586. ** made by triggers.
  88587. **
  88588. ** If there are one or more BEFORE triggers, then do not populate the
  88589. ** registers associated with columns that are (a) not modified by
  88590. ** this UPDATE statement and (b) not accessed by new.* references. The
  88591. ** values for registers not modified by the UPDATE must be reloaded from
  88592. ** the database after the BEFORE triggers are fired anyway (as the trigger
  88593. ** may have modified them). So not loading those that are not going to
  88594. ** be used eliminates some redundant opcodes.
  88595. */
  88596. newmask = sqlite3TriggerColmask(
  88597. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  88598. );
  88599. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  88600. for(i=0; i<pTab->nCol; i++){
  88601. if( i==pTab->iPKey ){
  88602. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  88603. }else{
  88604. j = aXRef[i];
  88605. if( j>=0 ){
  88606. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  88607. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  88608. /* This branch loads the value of a column that will not be changed
  88609. ** into a register. This is done if there are no BEFORE triggers, or
  88610. ** if there are one or more BEFORE triggers that use this value via
  88611. ** a new.* reference in a trigger program.
  88612. */
  88613. testcase( i==31 );
  88614. testcase( i==32 );
  88615. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  88616. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  88617. }
  88618. }
  88619. }
  88620. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  88621. ** verified. One could argue that this is wrong.
  88622. */
  88623. if( tmask&TRIGGER_BEFORE ){
  88624. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  88625. sqlite3TableAffinityStr(v, pTab);
  88626. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  88627. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  88628. /* The row-trigger may have deleted the row being updated. In this
  88629. ** case, jump to the next row. No updates or AFTER triggers are
  88630. ** required. This behavior - what happens when the row being updated
  88631. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  88632. ** documentation.
  88633. */
  88634. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  88635. /* If it did not delete it, the row-trigger may still have modified
  88636. ** some of the columns of the row being updated. Load the values for
  88637. ** all columns not modified by the update statement into their
  88638. ** registers in case this has happened.
  88639. */
  88640. for(i=0; i<pTab->nCol; i++){
  88641. if( aXRef[i]<0 && i!=pTab->iPKey ){
  88642. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  88643. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  88644. }
  88645. }
  88646. }
  88647. if( !isView ){
  88648. int j1; /* Address of jump instruction */
  88649. /* Do constraint checks. */
  88650. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  88651. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  88652. /* Do FK constraint checks. */
  88653. if( hasFK ){
  88654. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  88655. }
  88656. /* Delete the index entries associated with the current record. */
  88657. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  88658. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  88659. /* If changing the record number, delete the old record. */
  88660. if( hasFK || chngRowid ){
  88661. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  88662. }
  88663. sqlite3VdbeJumpHere(v, j1);
  88664. if( hasFK ){
  88665. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  88666. }
  88667. /* Insert the new index entries and the new record. */
  88668. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  88669. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  88670. ** handle rows (possibly in other tables) that refer via a foreign key
  88671. ** to the row just updated. */
  88672. if( hasFK ){
  88673. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  88674. }
  88675. }
  88676. /* Increment the row counter
  88677. */
  88678. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  88679. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  88680. }
  88681. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  88682. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  88683. /* Repeat the above with the next record to be updated, until
  88684. ** all record selected by the WHERE clause have been updated.
  88685. */
  88686. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  88687. sqlite3VdbeJumpHere(v, addr);
  88688. /* Close all tables */
  88689. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  88690. assert( aRegIdx );
  88691. if( openAll || aRegIdx[i]>0 ){
  88692. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  88693. }
  88694. }
  88695. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  88696. /* Update the sqlite_sequence table by storing the content of the
  88697. ** maximum rowid counter values recorded while inserting into
  88698. ** autoincrement tables.
  88699. */
  88700. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  88701. sqlite3AutoincrementEnd(pParse);
  88702. }
  88703. /*
  88704. ** Return the number of rows that were changed. If this routine is
  88705. ** generating code because of a call to sqlite3NestedParse(), do not
  88706. ** invoke the callback function.
  88707. */
  88708. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  88709. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  88710. sqlite3VdbeSetNumCols(v, 1);
  88711. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  88712. }
  88713. update_cleanup:
  88714. sqlite3AuthContextPop(&sContext);
  88715. sqlite3DbFree(db, aRegIdx);
  88716. sqlite3DbFree(db, aXRef);
  88717. sqlite3SrcListDelete(db, pTabList);
  88718. sqlite3ExprListDelete(db, pChanges);
  88719. sqlite3ExprDelete(db, pWhere);
  88720. return;
  88721. }
  88722. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  88723. ** thely may interfere with compilation of other functions in this file
  88724. ** (or in another file, if this file becomes part of the amalgamation). */
  88725. #ifdef isView
  88726. #undef isView
  88727. #endif
  88728. #ifdef pTrigger
  88729. #undef pTrigger
  88730. #endif
  88731. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88732. /*
  88733. ** Generate code for an UPDATE of a virtual table.
  88734. **
  88735. ** The strategy is that we create an ephemerial table that contains
  88736. ** for each row to be changed:
  88737. **
  88738. ** (A) The original rowid of that row.
  88739. ** (B) The revised rowid for the row. (note1)
  88740. ** (C) The content of every column in the row.
  88741. **
  88742. ** Then we loop over this ephemeral table and for each row in
  88743. ** the ephermeral table call VUpdate.
  88744. **
  88745. ** When finished, drop the ephemeral table.
  88746. **
  88747. ** (note1) Actually, if we know in advance that (A) is always the same
  88748. ** as (B) we only store (A), then duplicate (A) when pulling
  88749. ** it out of the ephemeral table before calling VUpdate.
  88750. */
  88751. static void updateVirtualTable(
  88752. Parse *pParse, /* The parsing context */
  88753. SrcList *pSrc, /* The virtual table to be modified */
  88754. Table *pTab, /* The virtual table */
  88755. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  88756. Expr *pRowid, /* Expression used to recompute the rowid */
  88757. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  88758. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  88759. int onError /* ON CONFLICT strategy */
  88760. ){
  88761. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  88762. ExprList *pEList = 0; /* The result set of the SELECT statement */
  88763. Select *pSelect = 0; /* The SELECT statement */
  88764. Expr *pExpr; /* Temporary expression */
  88765. int ephemTab; /* Table holding the result of the SELECT */
  88766. int i; /* Loop counter */
  88767. int addr; /* Address of top of loop */
  88768. int iReg; /* First register in set passed to OP_VUpdate */
  88769. sqlite3 *db = pParse->db; /* Database connection */
  88770. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  88771. SelectDest dest;
  88772. /* Construct the SELECT statement that will find the new values for
  88773. ** all updated rows.
  88774. */
  88775. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  88776. if( pRowid ){
  88777. pEList = sqlite3ExprListAppend(pParse, pEList,
  88778. sqlite3ExprDup(db, pRowid, 0));
  88779. }
  88780. assert( pTab->iPKey<0 );
  88781. for(i=0; i<pTab->nCol; i++){
  88782. if( aXRef[i]>=0 ){
  88783. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  88784. }else{
  88785. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  88786. }
  88787. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  88788. }
  88789. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  88790. /* Create the ephemeral table into which the update results will
  88791. ** be stored.
  88792. */
  88793. assert( v );
  88794. ephemTab = pParse->nTab++;
  88795. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  88796. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  88797. /* fill the ephemeral table
  88798. */
  88799. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  88800. sqlite3Select(pParse, pSelect, &dest);
  88801. /* Generate code to scan the ephemeral table and call VUpdate. */
  88802. iReg = ++pParse->nMem;
  88803. pParse->nMem += pTab->nCol+1;
  88804. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  88805. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  88806. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  88807. for(i=0; i<pTab->nCol; i++){
  88808. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  88809. }
  88810. sqlite3VtabMakeWritable(pParse, pTab);
  88811. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  88812. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  88813. sqlite3MayAbort(pParse);
  88814. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  88815. sqlite3VdbeJumpHere(v, addr);
  88816. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  88817. /* Cleanup */
  88818. sqlite3SelectDelete(db, pSelect);
  88819. }
  88820. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  88821. /************** End of update.c **********************************************/
  88822. /************** Begin file vacuum.c ******************************************/
  88823. /*
  88824. ** 2003 April 6
  88825. **
  88826. ** The author disclaims copyright to this source code. In place of
  88827. ** a legal notice, here is a blessing:
  88828. **
  88829. ** May you do good and not evil.
  88830. ** May you find forgiveness for yourself and forgive others.
  88831. ** May you share freely, never taking more than you give.
  88832. **
  88833. *************************************************************************
  88834. ** This file contains code used to implement the VACUUM command.
  88835. **
  88836. ** Most of the code in this file may be omitted by defining the
  88837. ** SQLITE_OMIT_VACUUM macro.
  88838. */
  88839. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  88840. /*
  88841. ** Finalize a prepared statement. If there was an error, store the
  88842. ** text of the error message in *pzErrMsg. Return the result code.
  88843. */
  88844. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  88845. int rc;
  88846. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  88847. if( rc ){
  88848. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  88849. }
  88850. return rc;
  88851. }
  88852. /*
  88853. ** Execute zSql on database db. Return an error code.
  88854. */
  88855. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  88856. sqlite3_stmt *pStmt;
  88857. VVA_ONLY( int rc; )
  88858. if( !zSql ){
  88859. return SQLITE_NOMEM;
  88860. }
  88861. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  88862. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  88863. return sqlite3_errcode(db);
  88864. }
  88865. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  88866. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  88867. return vacuumFinalize(db, pStmt, pzErrMsg);
  88868. }
  88869. /*
  88870. ** Execute zSql on database db. The statement returns exactly
  88871. ** one column. Execute this as SQL on the same database.
  88872. */
  88873. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  88874. sqlite3_stmt *pStmt;
  88875. int rc;
  88876. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  88877. if( rc!=SQLITE_OK ) return rc;
  88878. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  88879. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  88880. if( rc!=SQLITE_OK ){
  88881. vacuumFinalize(db, pStmt, pzErrMsg);
  88882. return rc;
  88883. }
  88884. }
  88885. return vacuumFinalize(db, pStmt, pzErrMsg);
  88886. }
  88887. /*
  88888. ** The VACUUM command is used to clean up the database,
  88889. ** collapse free space, etc. It is modelled after the VACUUM command
  88890. ** in PostgreSQL. The VACUUM command works as follows:
  88891. **
  88892. ** (1) Create a new transient database file
  88893. ** (2) Copy all content from the database being vacuumed into
  88894. ** the new transient database file
  88895. ** (3) Copy content from the transient database back into the
  88896. ** original database.
  88897. **
  88898. ** The transient database requires temporary disk space approximately
  88899. ** equal to the size of the original database. The copy operation of
  88900. ** step (3) requires additional temporary disk space approximately equal
  88901. ** to the size of the original database for the rollback journal.
  88902. ** Hence, temporary disk space that is approximately 2x the size of the
  88903. ** orginal database is required. Every page of the database is written
  88904. ** approximately 3 times: Once for step (2) and twice for step (3).
  88905. ** Two writes per page are required in step (3) because the original
  88906. ** database content must be written into the rollback journal prior to
  88907. ** overwriting the database with the vacuumed content.
  88908. **
  88909. ** Only 1x temporary space and only 1x writes would be required if
  88910. ** the copy of step (3) were replace by deleting the original database
  88911. ** and renaming the transient database as the original. But that will
  88912. ** not work if other processes are attached to the original database.
  88913. ** And a power loss in between deleting the original and renaming the
  88914. ** transient would cause the database file to appear to be deleted
  88915. ** following reboot.
  88916. */
  88917. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  88918. Vdbe *v = sqlite3GetVdbe(pParse);
  88919. if( v ){
  88920. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  88921. sqlite3VdbeUsesBtree(v, 0);
  88922. }
  88923. return;
  88924. }
  88925. /*
  88926. ** This routine implements the OP_Vacuum opcode of the VDBE.
  88927. */
  88928. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  88929. int rc = SQLITE_OK; /* Return code from service routines */
  88930. Btree *pMain; /* The database being vacuumed */
  88931. Btree *pTemp; /* The temporary database we vacuum into */
  88932. char *zSql = 0; /* SQL statements */
  88933. int saved_flags; /* Saved value of the db->flags */
  88934. int saved_nChange; /* Saved value of db->nChange */
  88935. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  88936. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  88937. Db *pDb = 0; /* Database to detach at end of vacuum */
  88938. int isMemDb; /* True if vacuuming a :memory: database */
  88939. int nRes; /* Bytes of reserved space at the end of each page */
  88940. int nDb; /* Number of attached databases */
  88941. if( !db->autoCommit ){
  88942. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  88943. return SQLITE_ERROR;
  88944. }
  88945. if( db->nVdbeActive>1 ){
  88946. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  88947. return SQLITE_ERROR;
  88948. }
  88949. /* Save the current value of the database flags so that it can be
  88950. ** restored before returning. Then set the writable-schema flag, and
  88951. ** disable CHECK and foreign key constraints. */
  88952. saved_flags = db->flags;
  88953. saved_nChange = db->nChange;
  88954. saved_nTotalChange = db->nTotalChange;
  88955. saved_xTrace = db->xTrace;
  88956. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  88957. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  88958. db->xTrace = 0;
  88959. pMain = db->aDb[0].pBt;
  88960. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  88961. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  88962. ** can be set to 'off' for this file, as it is not recovered if a crash
  88963. ** occurs anyway. The integrity of the database is maintained by a
  88964. ** (possibly synchronous) transaction opened on the main database before
  88965. ** sqlite3BtreeCopyFile() is called.
  88966. **
  88967. ** An optimisation would be to use a non-journaled pager.
  88968. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  88969. ** that actually made the VACUUM run slower. Very little journalling
  88970. ** actually occurs when doing a vacuum since the vacuum_db is initially
  88971. ** empty. Only the journal header is written. Apparently it takes more
  88972. ** time to parse and run the PRAGMA to turn journalling off than it does
  88973. ** to write the journal header file.
  88974. */
  88975. nDb = db->nDb;
  88976. if( sqlite3TempInMemory(db) ){
  88977. zSql = "ATTACH ':memory:' AS vacuum_db;";
  88978. }else{
  88979. zSql = "ATTACH '' AS vacuum_db;";
  88980. }
  88981. rc = execSql(db, pzErrMsg, zSql);
  88982. if( db->nDb>nDb ){
  88983. pDb = &db->aDb[db->nDb-1];
  88984. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  88985. }
  88986. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  88987. pTemp = db->aDb[db->nDb-1].pBt;
  88988. /* The call to execSql() to attach the temp database has left the file
  88989. ** locked (as there was more than one active statement when the transaction
  88990. ** to read the schema was concluded. Unlock it here so that this doesn't
  88991. ** cause problems for the call to BtreeSetPageSize() below. */
  88992. sqlite3BtreeCommit(pTemp);
  88993. nRes = sqlite3BtreeGetReserve(pMain);
  88994. /* A VACUUM cannot change the pagesize of an encrypted database. */
  88995. #ifdef SQLITE_HAS_CODEC
  88996. if( db->nextPagesize ){
  88997. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  88998. int nKey;
  88999. char *zKey;
  89000. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  89001. if( nKey ) db->nextPagesize = 0;
  89002. }
  89003. #endif
  89004. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  89005. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89006. /* Begin a transaction and take an exclusive lock on the main database
  89007. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  89008. ** to ensure that we do not try to change the page-size on a WAL database.
  89009. */
  89010. rc = execSql(db, pzErrMsg, "BEGIN;");
  89011. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89012. rc = sqlite3BtreeBeginTrans(pMain, 2);
  89013. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89014. /* Do not attempt to change the page size for a WAL database */
  89015. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  89016. ==PAGER_JOURNALMODE_WAL ){
  89017. db->nextPagesize = 0;
  89018. }
  89019. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  89020. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  89021. || NEVER(db->mallocFailed)
  89022. ){
  89023. rc = SQLITE_NOMEM;
  89024. goto end_of_vacuum;
  89025. }
  89026. #ifndef SQLITE_OMIT_AUTOVACUUM
  89027. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  89028. sqlite3BtreeGetAutoVacuum(pMain));
  89029. #endif
  89030. /* Query the schema of the main database. Create a mirror schema
  89031. ** in the temporary database.
  89032. */
  89033. rc = execExecSql(db, pzErrMsg,
  89034. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  89035. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  89036. " AND rootpage>0"
  89037. );
  89038. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89039. rc = execExecSql(db, pzErrMsg,
  89040. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  89041. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  89042. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89043. rc = execExecSql(db, pzErrMsg,
  89044. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  89045. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  89046. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89047. /* Loop through the tables in the main database. For each, do
  89048. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  89049. ** the contents to the temporary database.
  89050. */
  89051. rc = execExecSql(db, pzErrMsg,
  89052. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  89053. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  89054. "FROM main.sqlite_master "
  89055. "WHERE type = 'table' AND name!='sqlite_sequence' "
  89056. " AND rootpage>0"
  89057. );
  89058. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89059. /* Copy over the sequence table
  89060. */
  89061. rc = execExecSql(db, pzErrMsg,
  89062. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  89063. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  89064. );
  89065. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89066. rc = execExecSql(db, pzErrMsg,
  89067. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  89068. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  89069. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  89070. );
  89071. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89072. /* Copy the triggers, views, and virtual tables from the main database
  89073. ** over to the temporary database. None of these objects has any
  89074. ** associated storage, so all we have to do is copy their entries
  89075. ** from the SQLITE_MASTER table.
  89076. */
  89077. rc = execSql(db, pzErrMsg,
  89078. "INSERT INTO vacuum_db.sqlite_master "
  89079. " SELECT type, name, tbl_name, rootpage, sql"
  89080. " FROM main.sqlite_master"
  89081. " WHERE type='view' OR type='trigger'"
  89082. " OR (type='table' AND rootpage=0)"
  89083. );
  89084. if( rc ) goto end_of_vacuum;
  89085. /* At this point, there is a write transaction open on both the
  89086. ** vacuum database and the main database. Assuming no error occurs,
  89087. ** both transactions are closed by this block - the main database
  89088. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  89089. ** call to sqlite3BtreeCommit().
  89090. */
  89091. {
  89092. u32 meta;
  89093. int i;
  89094. /* This array determines which meta meta values are preserved in the
  89095. ** vacuum. Even entries are the meta value number and odd entries
  89096. ** are an increment to apply to the meta value after the vacuum.
  89097. ** The increment is used to increase the schema cookie so that other
  89098. ** connections to the same database will know to reread the schema.
  89099. */
  89100. static const unsigned char aCopy[] = {
  89101. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  89102. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  89103. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  89104. BTREE_USER_VERSION, 0, /* Preserve the user version */
  89105. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  89106. };
  89107. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  89108. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  89109. /* Copy Btree meta values */
  89110. for(i=0; i<ArraySize(aCopy); i+=2){
  89111. /* GetMeta() and UpdateMeta() cannot fail in this context because
  89112. ** we already have page 1 loaded into cache and marked dirty. */
  89113. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  89114. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  89115. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  89116. }
  89117. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  89118. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89119. rc = sqlite3BtreeCommit(pTemp);
  89120. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  89121. #ifndef SQLITE_OMIT_AUTOVACUUM
  89122. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  89123. #endif
  89124. }
  89125. assert( rc==SQLITE_OK );
  89126. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  89127. end_of_vacuum:
  89128. /* Restore the original value of db->flags */
  89129. db->flags = saved_flags;
  89130. db->nChange = saved_nChange;
  89131. db->nTotalChange = saved_nTotalChange;
  89132. db->xTrace = saved_xTrace;
  89133. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  89134. /* Currently there is an SQL level transaction open on the vacuum
  89135. ** database. No locks are held on any other files (since the main file
  89136. ** was committed at the btree level). So it safe to end the transaction
  89137. ** by manually setting the autoCommit flag to true and detaching the
  89138. ** vacuum database. The vacuum_db journal file is deleted when the pager
  89139. ** is closed by the DETACH.
  89140. */
  89141. db->autoCommit = 1;
  89142. if( pDb ){
  89143. sqlite3BtreeClose(pDb->pBt);
  89144. pDb->pBt = 0;
  89145. pDb->pSchema = 0;
  89146. }
  89147. /* This both clears the schemas and reduces the size of the db->aDb[]
  89148. ** array. */
  89149. sqlite3ResetAllSchemasOfConnection(db);
  89150. return rc;
  89151. }
  89152. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  89153. /************** End of vacuum.c **********************************************/
  89154. /************** Begin file vtab.c ********************************************/
  89155. /*
  89156. ** 2006 June 10
  89157. **
  89158. ** The author disclaims copyright to this source code. In place of
  89159. ** a legal notice, here is a blessing:
  89160. **
  89161. ** May you do good and not evil.
  89162. ** May you find forgiveness for yourself and forgive others.
  89163. ** May you share freely, never taking more than you give.
  89164. **
  89165. *************************************************************************
  89166. ** This file contains code used to help implement virtual tables.
  89167. */
  89168. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89169. /*
  89170. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  89171. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  89172. ** this struct allocated on the stack. It is used by the implementation of
  89173. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  89174. ** are invoked only from within xCreate and xConnect methods.
  89175. */
  89176. struct VtabCtx {
  89177. VTable *pVTable; /* The virtual table being constructed */
  89178. Table *pTab; /* The Table object to which the virtual table belongs */
  89179. };
  89180. /*
  89181. ** The actual function that does the work of creating a new module.
  89182. ** This function implements the sqlite3_create_module() and
  89183. ** sqlite3_create_module_v2() interfaces.
  89184. */
  89185. static int createModule(
  89186. sqlite3 *db, /* Database in which module is registered */
  89187. const char *zName, /* Name assigned to this module */
  89188. const sqlite3_module *pModule, /* The definition of the module */
  89189. void *pAux, /* Context pointer for xCreate/xConnect */
  89190. void (*xDestroy)(void *) /* Module destructor function */
  89191. ){
  89192. int rc = SQLITE_OK;
  89193. int nName;
  89194. sqlite3_mutex_enter(db->mutex);
  89195. nName = sqlite3Strlen30(zName);
  89196. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  89197. rc = SQLITE_MISUSE_BKPT;
  89198. }else{
  89199. Module *pMod;
  89200. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  89201. if( pMod ){
  89202. Module *pDel;
  89203. char *zCopy = (char *)(&pMod[1]);
  89204. memcpy(zCopy, zName, nName+1);
  89205. pMod->zName = zCopy;
  89206. pMod->pModule = pModule;
  89207. pMod->pAux = pAux;
  89208. pMod->xDestroy = xDestroy;
  89209. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  89210. assert( pDel==0 || pDel==pMod );
  89211. if( pDel ){
  89212. db->mallocFailed = 1;
  89213. sqlite3DbFree(db, pDel);
  89214. }
  89215. }
  89216. }
  89217. rc = sqlite3ApiExit(db, rc);
  89218. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  89219. sqlite3_mutex_leave(db->mutex);
  89220. return rc;
  89221. }
  89222. /*
  89223. ** External API function used to create a new virtual-table module.
  89224. */
  89225. SQLITE_API int sqlite3_create_module(
  89226. sqlite3 *db, /* Database in which module is registered */
  89227. const char *zName, /* Name assigned to this module */
  89228. const sqlite3_module *pModule, /* The definition of the module */
  89229. void *pAux /* Context pointer for xCreate/xConnect */
  89230. ){
  89231. return createModule(db, zName, pModule, pAux, 0);
  89232. }
  89233. /*
  89234. ** External API function used to create a new virtual-table module.
  89235. */
  89236. SQLITE_API int sqlite3_create_module_v2(
  89237. sqlite3 *db, /* Database in which module is registered */
  89238. const char *zName, /* Name assigned to this module */
  89239. const sqlite3_module *pModule, /* The definition of the module */
  89240. void *pAux, /* Context pointer for xCreate/xConnect */
  89241. void (*xDestroy)(void *) /* Module destructor function */
  89242. ){
  89243. return createModule(db, zName, pModule, pAux, xDestroy);
  89244. }
  89245. /*
  89246. ** Lock the virtual table so that it cannot be disconnected.
  89247. ** Locks nest. Every lock should have a corresponding unlock.
  89248. ** If an unlock is omitted, resources leaks will occur.
  89249. **
  89250. ** If a disconnect is attempted while a virtual table is locked,
  89251. ** the disconnect is deferred until all locks have been removed.
  89252. */
  89253. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  89254. pVTab->nRef++;
  89255. }
  89256. /*
  89257. ** pTab is a pointer to a Table structure representing a virtual-table.
  89258. ** Return a pointer to the VTable object used by connection db to access
  89259. ** this virtual-table, if one has been created, or NULL otherwise.
  89260. */
  89261. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  89262. VTable *pVtab;
  89263. assert( IsVirtual(pTab) );
  89264. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  89265. return pVtab;
  89266. }
  89267. /*
  89268. ** Decrement the ref-count on a virtual table object. When the ref-count
  89269. ** reaches zero, call the xDisconnect() method to delete the object.
  89270. */
  89271. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  89272. sqlite3 *db = pVTab->db;
  89273. assert( db );
  89274. assert( pVTab->nRef>0 );
  89275. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  89276. pVTab->nRef--;
  89277. if( pVTab->nRef==0 ){
  89278. sqlite3_vtab *p = pVTab->pVtab;
  89279. if( p ){
  89280. p->pModule->xDisconnect(p);
  89281. }
  89282. sqlite3DbFree(db, pVTab);
  89283. }
  89284. }
  89285. /*
  89286. ** Table p is a virtual table. This function moves all elements in the
  89287. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  89288. ** database connections to be disconnected at the next opportunity.
  89289. ** Except, if argument db is not NULL, then the entry associated with
  89290. ** connection db is left in the p->pVTable list.
  89291. */
  89292. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  89293. VTable *pRet = 0;
  89294. VTable *pVTable = p->pVTable;
  89295. p->pVTable = 0;
  89296. /* Assert that the mutex (if any) associated with the BtShared database
  89297. ** that contains table p is held by the caller. See header comments
  89298. ** above function sqlite3VtabUnlockList() for an explanation of why
  89299. ** this makes it safe to access the sqlite3.pDisconnect list of any
  89300. ** database connection that may have an entry in the p->pVTable list.
  89301. */
  89302. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  89303. while( pVTable ){
  89304. sqlite3 *db2 = pVTable->db;
  89305. VTable *pNext = pVTable->pNext;
  89306. assert( db2 );
  89307. if( db2==db ){
  89308. pRet = pVTable;
  89309. p->pVTable = pRet;
  89310. pRet->pNext = 0;
  89311. }else{
  89312. pVTable->pNext = db2->pDisconnect;
  89313. db2->pDisconnect = pVTable;
  89314. }
  89315. pVTable = pNext;
  89316. }
  89317. assert( !db || pRet );
  89318. return pRet;
  89319. }
  89320. /*
  89321. ** Table *p is a virtual table. This function removes the VTable object
  89322. ** for table *p associated with database connection db from the linked
  89323. ** list in p->pVTab. It also decrements the VTable ref count. This is
  89324. ** used when closing database connection db to free all of its VTable
  89325. ** objects without disturbing the rest of the Schema object (which may
  89326. ** be being used by other shared-cache connections).
  89327. */
  89328. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  89329. VTable **ppVTab;
  89330. assert( IsVirtual(p) );
  89331. assert( sqlite3BtreeHoldsAllMutexes(db) );
  89332. assert( sqlite3_mutex_held(db->mutex) );
  89333. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  89334. if( (*ppVTab)->db==db ){
  89335. VTable *pVTab = *ppVTab;
  89336. *ppVTab = pVTab->pNext;
  89337. sqlite3VtabUnlock(pVTab);
  89338. break;
  89339. }
  89340. }
  89341. }
  89342. /*
  89343. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  89344. **
  89345. ** This function may only be called when the mutexes associated with all
  89346. ** shared b-tree databases opened using connection db are held by the
  89347. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  89348. ** sqlite3.pDisconnect list is accessed only as follows:
  89349. **
  89350. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  89351. ** associated with the database handle itself must be held.
  89352. **
  89353. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  89354. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  89355. ** associated with the database the virtual table is stored in is held
  89356. ** or, if the virtual table is stored in a non-sharable database, then
  89357. ** the database handle mutex is held.
  89358. **
  89359. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  89360. ** by multiple threads. It is thread-safe.
  89361. */
  89362. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  89363. VTable *p = db->pDisconnect;
  89364. db->pDisconnect = 0;
  89365. assert( sqlite3BtreeHoldsAllMutexes(db) );
  89366. assert( sqlite3_mutex_held(db->mutex) );
  89367. if( p ){
  89368. sqlite3ExpirePreparedStatements(db);
  89369. do {
  89370. VTable *pNext = p->pNext;
  89371. sqlite3VtabUnlock(p);
  89372. p = pNext;
  89373. }while( p );
  89374. }
  89375. }
  89376. /*
  89377. ** Clear any and all virtual-table information from the Table record.
  89378. ** This routine is called, for example, just before deleting the Table
  89379. ** record.
  89380. **
  89381. ** Since it is a virtual-table, the Table structure contains a pointer
  89382. ** to the head of a linked list of VTable structures. Each VTable
  89383. ** structure is associated with a single sqlite3* user of the schema.
  89384. ** The reference count of the VTable structure associated with database
  89385. ** connection db is decremented immediately (which may lead to the
  89386. ** structure being xDisconnected and free). Any other VTable structures
  89387. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  89388. ** database connection.
  89389. */
  89390. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  89391. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  89392. if( p->azModuleArg ){
  89393. int i;
  89394. for(i=0; i<p->nModuleArg; i++){
  89395. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  89396. }
  89397. sqlite3DbFree(db, p->azModuleArg);
  89398. }
  89399. }
  89400. /*
  89401. ** Add a new module argument to pTable->azModuleArg[].
  89402. ** The string is not copied - the pointer is stored. The
  89403. ** string will be freed automatically when the table is
  89404. ** deleted.
  89405. */
  89406. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  89407. int i = pTable->nModuleArg++;
  89408. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  89409. char **azModuleArg;
  89410. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  89411. if( azModuleArg==0 ){
  89412. int j;
  89413. for(j=0; j<i; j++){
  89414. sqlite3DbFree(db, pTable->azModuleArg[j]);
  89415. }
  89416. sqlite3DbFree(db, zArg);
  89417. sqlite3DbFree(db, pTable->azModuleArg);
  89418. pTable->nModuleArg = 0;
  89419. }else{
  89420. azModuleArg[i] = zArg;
  89421. azModuleArg[i+1] = 0;
  89422. }
  89423. pTable->azModuleArg = azModuleArg;
  89424. }
  89425. /*
  89426. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  89427. ** statement. The module name has been parsed, but the optional list
  89428. ** of parameters that follow the module name are still pending.
  89429. */
  89430. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  89431. Parse *pParse, /* Parsing context */
  89432. Token *pName1, /* Name of new table, or database name */
  89433. Token *pName2, /* Name of new table or NULL */
  89434. Token *pModuleName, /* Name of the module for the virtual table */
  89435. int ifNotExists /* No error if the table already exists */
  89436. ){
  89437. int iDb; /* The database the table is being created in */
  89438. Table *pTable; /* The new virtual table */
  89439. sqlite3 *db; /* Database connection */
  89440. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  89441. pTable = pParse->pNewTable;
  89442. if( pTable==0 ) return;
  89443. assert( 0==pTable->pIndex );
  89444. db = pParse->db;
  89445. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  89446. assert( iDb>=0 );
  89447. pTable->tabFlags |= TF_Virtual;
  89448. pTable->nModuleArg = 0;
  89449. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  89450. addModuleArgument(db, pTable, 0);
  89451. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  89452. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  89453. #ifndef SQLITE_OMIT_AUTHORIZATION
  89454. /* Creating a virtual table invokes the authorization callback twice.
  89455. ** The first invocation, to obtain permission to INSERT a row into the
  89456. ** sqlite_master table, has already been made by sqlite3StartTable().
  89457. ** The second call, to obtain permission to create the table, is made now.
  89458. */
  89459. if( pTable->azModuleArg ){
  89460. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  89461. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  89462. }
  89463. #endif
  89464. }
  89465. /*
  89466. ** This routine takes the module argument that has been accumulating
  89467. ** in pParse->zArg[] and appends it to the list of arguments on the
  89468. ** virtual table currently under construction in pParse->pTable.
  89469. */
  89470. static void addArgumentToVtab(Parse *pParse){
  89471. if( pParse->sArg.z && pParse->pNewTable ){
  89472. const char *z = (const char*)pParse->sArg.z;
  89473. int n = pParse->sArg.n;
  89474. sqlite3 *db = pParse->db;
  89475. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  89476. }
  89477. }
  89478. /*
  89479. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  89480. ** has been completely parsed.
  89481. */
  89482. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  89483. Table *pTab = pParse->pNewTable; /* The table being constructed */
  89484. sqlite3 *db = pParse->db; /* The database connection */
  89485. if( pTab==0 ) return;
  89486. addArgumentToVtab(pParse);
  89487. pParse->sArg.z = 0;
  89488. if( pTab->nModuleArg<1 ) return;
  89489. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  89490. ** first time (in other words if the virtual table is actually being
  89491. ** created now instead of just being read out of sqlite_master) then
  89492. ** do additional initialization work and store the statement text
  89493. ** in the sqlite_master table.
  89494. */
  89495. if( !db->init.busy ){
  89496. char *zStmt;
  89497. char *zWhere;
  89498. int iDb;
  89499. Vdbe *v;
  89500. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  89501. if( pEnd ){
  89502. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  89503. }
  89504. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  89505. /* A slot for the record has already been allocated in the
  89506. ** SQLITE_MASTER table. We just need to update that slot with all
  89507. ** the information we've collected.
  89508. **
  89509. ** The VM register number pParse->regRowid holds the rowid of an
  89510. ** entry in the sqlite_master table tht was created for this vtab
  89511. ** by sqlite3StartTable().
  89512. */
  89513. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89514. sqlite3NestedParse(pParse,
  89515. "UPDATE %Q.%s "
  89516. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  89517. "WHERE rowid=#%d",
  89518. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  89519. pTab->zName,
  89520. pTab->zName,
  89521. zStmt,
  89522. pParse->regRowid
  89523. );
  89524. sqlite3DbFree(db, zStmt);
  89525. v = sqlite3GetVdbe(pParse);
  89526. sqlite3ChangeCookie(pParse, iDb);
  89527. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  89528. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  89529. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  89530. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  89531. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  89532. }
  89533. /* If we are rereading the sqlite_master table create the in-memory
  89534. ** record of the table. The xConnect() method is not called until
  89535. ** the first time the virtual table is used in an SQL statement. This
  89536. ** allows a schema that contains virtual tables to be loaded before
  89537. ** the required virtual table implementations are registered. */
  89538. else {
  89539. Table *pOld;
  89540. Schema *pSchema = pTab->pSchema;
  89541. const char *zName = pTab->zName;
  89542. int nName = sqlite3Strlen30(zName);
  89543. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  89544. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  89545. if( pOld ){
  89546. db->mallocFailed = 1;
  89547. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  89548. return;
  89549. }
  89550. pParse->pNewTable = 0;
  89551. }
  89552. }
  89553. /*
  89554. ** The parser calls this routine when it sees the first token
  89555. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  89556. */
  89557. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  89558. addArgumentToVtab(pParse);
  89559. pParse->sArg.z = 0;
  89560. pParse->sArg.n = 0;
  89561. }
  89562. /*
  89563. ** The parser calls this routine for each token after the first token
  89564. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  89565. */
  89566. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  89567. Token *pArg = &pParse->sArg;
  89568. if( pArg->z==0 ){
  89569. pArg->z = p->z;
  89570. pArg->n = p->n;
  89571. }else{
  89572. assert(pArg->z < p->z);
  89573. pArg->n = (int)(&p->z[p->n] - pArg->z);
  89574. }
  89575. }
  89576. /*
  89577. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  89578. ** pointer to the function to invoke is passed as the fourth parameter
  89579. ** to this procedure.
  89580. */
  89581. static int vtabCallConstructor(
  89582. sqlite3 *db,
  89583. Table *pTab,
  89584. Module *pMod,
  89585. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  89586. char **pzErr
  89587. ){
  89588. VtabCtx sCtx, *pPriorCtx;
  89589. VTable *pVTable;
  89590. int rc;
  89591. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  89592. int nArg = pTab->nModuleArg;
  89593. char *zErr = 0;
  89594. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  89595. int iDb;
  89596. if( !zModuleName ){
  89597. return SQLITE_NOMEM;
  89598. }
  89599. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  89600. if( !pVTable ){
  89601. sqlite3DbFree(db, zModuleName);
  89602. return SQLITE_NOMEM;
  89603. }
  89604. pVTable->db = db;
  89605. pVTable->pMod = pMod;
  89606. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89607. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  89608. /* Invoke the virtual table constructor */
  89609. assert( &db->pVtabCtx );
  89610. assert( xConstruct );
  89611. sCtx.pTab = pTab;
  89612. sCtx.pVTable = pVTable;
  89613. pPriorCtx = db->pVtabCtx;
  89614. db->pVtabCtx = &sCtx;
  89615. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  89616. db->pVtabCtx = pPriorCtx;
  89617. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  89618. if( SQLITE_OK!=rc ){
  89619. if( zErr==0 ){
  89620. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  89621. }else {
  89622. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  89623. sqlite3_free(zErr);
  89624. }
  89625. sqlite3DbFree(db, pVTable);
  89626. }else if( ALWAYS(pVTable->pVtab) ){
  89627. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  89628. ** the sqlite3_vtab object if successful. */
  89629. pVTable->pVtab->pModule = pMod->pModule;
  89630. pVTable->nRef = 1;
  89631. if( sCtx.pTab ){
  89632. const char *zFormat = "vtable constructor did not declare schema: %s";
  89633. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  89634. sqlite3VtabUnlock(pVTable);
  89635. rc = SQLITE_ERROR;
  89636. }else{
  89637. int iCol;
  89638. /* If everything went according to plan, link the new VTable structure
  89639. ** into the linked list headed by pTab->pVTable. Then loop through the
  89640. ** columns of the table to see if any of them contain the token "hidden".
  89641. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  89642. ** the type string. */
  89643. pVTable->pNext = pTab->pVTable;
  89644. pTab->pVTable = pVTable;
  89645. for(iCol=0; iCol<pTab->nCol; iCol++){
  89646. char *zType = pTab->aCol[iCol].zType;
  89647. int nType;
  89648. int i = 0;
  89649. if( !zType ) continue;
  89650. nType = sqlite3Strlen30(zType);
  89651. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  89652. for(i=0; i<nType; i++){
  89653. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  89654. && (zType[i+7]=='\0' || zType[i+7]==' ')
  89655. ){
  89656. i++;
  89657. break;
  89658. }
  89659. }
  89660. }
  89661. if( i<nType ){
  89662. int j;
  89663. int nDel = 6 + (zType[i+6] ? 1 : 0);
  89664. for(j=i; (j+nDel)<=nType; j++){
  89665. zType[j] = zType[j+nDel];
  89666. }
  89667. if( zType[i]=='\0' && i>0 ){
  89668. assert(zType[i-1]==' ');
  89669. zType[i-1] = '\0';
  89670. }
  89671. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  89672. }
  89673. }
  89674. }
  89675. }
  89676. sqlite3DbFree(db, zModuleName);
  89677. return rc;
  89678. }
  89679. /*
  89680. ** This function is invoked by the parser to call the xConnect() method
  89681. ** of the virtual table pTab. If an error occurs, an error code is returned
  89682. ** and an error left in pParse.
  89683. **
  89684. ** This call is a no-op if table pTab is not a virtual table.
  89685. */
  89686. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  89687. sqlite3 *db = pParse->db;
  89688. const char *zMod;
  89689. Module *pMod;
  89690. int rc;
  89691. assert( pTab );
  89692. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  89693. return SQLITE_OK;
  89694. }
  89695. /* Locate the required virtual table module */
  89696. zMod = pTab->azModuleArg[0];
  89697. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  89698. if( !pMod ){
  89699. const char *zModule = pTab->azModuleArg[0];
  89700. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  89701. rc = SQLITE_ERROR;
  89702. }else{
  89703. char *zErr = 0;
  89704. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  89705. if( rc!=SQLITE_OK ){
  89706. sqlite3ErrorMsg(pParse, "%s", zErr);
  89707. }
  89708. sqlite3DbFree(db, zErr);
  89709. }
  89710. return rc;
  89711. }
  89712. /*
  89713. ** Grow the db->aVTrans[] array so that there is room for at least one
  89714. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  89715. */
  89716. static int growVTrans(sqlite3 *db){
  89717. const int ARRAY_INCR = 5;
  89718. /* Grow the sqlite3.aVTrans array if required */
  89719. if( (db->nVTrans%ARRAY_INCR)==0 ){
  89720. VTable **aVTrans;
  89721. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  89722. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  89723. if( !aVTrans ){
  89724. return SQLITE_NOMEM;
  89725. }
  89726. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  89727. db->aVTrans = aVTrans;
  89728. }
  89729. return SQLITE_OK;
  89730. }
  89731. /*
  89732. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  89733. ** have already been reserved using growVTrans().
  89734. */
  89735. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  89736. /* Add pVtab to the end of sqlite3.aVTrans */
  89737. db->aVTrans[db->nVTrans++] = pVTab;
  89738. sqlite3VtabLock(pVTab);
  89739. }
  89740. /*
  89741. ** This function is invoked by the vdbe to call the xCreate method
  89742. ** of the virtual table named zTab in database iDb.
  89743. **
  89744. ** If an error occurs, *pzErr is set to point an an English language
  89745. ** description of the error and an SQLITE_XXX error code is returned.
  89746. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  89747. */
  89748. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  89749. int rc = SQLITE_OK;
  89750. Table *pTab;
  89751. Module *pMod;
  89752. const char *zMod;
  89753. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  89754. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  89755. /* Locate the required virtual table module */
  89756. zMod = pTab->azModuleArg[0];
  89757. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  89758. /* If the module has been registered and includes a Create method,
  89759. ** invoke it now. If the module has not been registered, return an
  89760. ** error. Otherwise, do nothing.
  89761. */
  89762. if( !pMod ){
  89763. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  89764. rc = SQLITE_ERROR;
  89765. }else{
  89766. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  89767. }
  89768. /* Justification of ALWAYS(): The xConstructor method is required to
  89769. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  89770. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  89771. rc = growVTrans(db);
  89772. if( rc==SQLITE_OK ){
  89773. addToVTrans(db, sqlite3GetVTable(db, pTab));
  89774. }
  89775. }
  89776. return rc;
  89777. }
  89778. /*
  89779. ** This function is used to set the schema of a virtual table. It is only
  89780. ** valid to call this function from within the xCreate() or xConnect() of a
  89781. ** virtual table module.
  89782. */
  89783. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  89784. Parse *pParse;
  89785. int rc = SQLITE_OK;
  89786. Table *pTab;
  89787. char *zErr = 0;
  89788. sqlite3_mutex_enter(db->mutex);
  89789. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  89790. sqlite3Error(db, SQLITE_MISUSE, 0);
  89791. sqlite3_mutex_leave(db->mutex);
  89792. return SQLITE_MISUSE_BKPT;
  89793. }
  89794. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  89795. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  89796. if( pParse==0 ){
  89797. rc = SQLITE_NOMEM;
  89798. }else{
  89799. pParse->declareVtab = 1;
  89800. pParse->db = db;
  89801. pParse->nQueryLoop = 1;
  89802. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  89803. && pParse->pNewTable
  89804. && !db->mallocFailed
  89805. && !pParse->pNewTable->pSelect
  89806. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  89807. ){
  89808. if( !pTab->aCol ){
  89809. pTab->aCol = pParse->pNewTable->aCol;
  89810. pTab->nCol = pParse->pNewTable->nCol;
  89811. pParse->pNewTable->nCol = 0;
  89812. pParse->pNewTable->aCol = 0;
  89813. }
  89814. db->pVtabCtx->pTab = 0;
  89815. }else{
  89816. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  89817. sqlite3DbFree(db, zErr);
  89818. rc = SQLITE_ERROR;
  89819. }
  89820. pParse->declareVtab = 0;
  89821. if( pParse->pVdbe ){
  89822. sqlite3VdbeFinalize(pParse->pVdbe);
  89823. }
  89824. sqlite3DeleteTable(db, pParse->pNewTable);
  89825. sqlite3StackFree(db, pParse);
  89826. }
  89827. assert( (rc&0xff)==rc );
  89828. rc = sqlite3ApiExit(db, rc);
  89829. sqlite3_mutex_leave(db->mutex);
  89830. return rc;
  89831. }
  89832. /*
  89833. ** This function is invoked by the vdbe to call the xDestroy method
  89834. ** of the virtual table named zTab in database iDb. This occurs
  89835. ** when a DROP TABLE is mentioned.
  89836. **
  89837. ** This call is a no-op if zTab is not a virtual table.
  89838. */
  89839. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  89840. int rc = SQLITE_OK;
  89841. Table *pTab;
  89842. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  89843. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  89844. VTable *p = vtabDisconnectAll(db, pTab);
  89845. assert( rc==SQLITE_OK );
  89846. rc = p->pMod->pModule->xDestroy(p->pVtab);
  89847. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  89848. if( rc==SQLITE_OK ){
  89849. assert( pTab->pVTable==p && p->pNext==0 );
  89850. p->pVtab = 0;
  89851. pTab->pVTable = 0;
  89852. sqlite3VtabUnlock(p);
  89853. }
  89854. }
  89855. return rc;
  89856. }
  89857. /*
  89858. ** This function invokes either the xRollback or xCommit method
  89859. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  89860. ** called is identified by the second argument, "offset", which is
  89861. ** the offset of the method to call in the sqlite3_module structure.
  89862. **
  89863. ** The array is cleared after invoking the callbacks.
  89864. */
  89865. static void callFinaliser(sqlite3 *db, int offset){
  89866. int i;
  89867. if( db->aVTrans ){
  89868. for(i=0; i<db->nVTrans; i++){
  89869. VTable *pVTab = db->aVTrans[i];
  89870. sqlite3_vtab *p = pVTab->pVtab;
  89871. if( p ){
  89872. int (*x)(sqlite3_vtab *);
  89873. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  89874. if( x ) x(p);
  89875. }
  89876. pVTab->iSavepoint = 0;
  89877. sqlite3VtabUnlock(pVTab);
  89878. }
  89879. sqlite3DbFree(db, db->aVTrans);
  89880. db->nVTrans = 0;
  89881. db->aVTrans = 0;
  89882. }
  89883. }
  89884. /*
  89885. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  89886. ** array. Return the error code for the first error that occurs, or
  89887. ** SQLITE_OK if all xSync operations are successful.
  89888. **
  89889. ** If an error message is available, leave it in p->zErrMsg.
  89890. */
  89891. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  89892. int i;
  89893. int rc = SQLITE_OK;
  89894. VTable **aVTrans = db->aVTrans;
  89895. db->aVTrans = 0;
  89896. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  89897. int (*x)(sqlite3_vtab *);
  89898. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  89899. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  89900. rc = x(pVtab);
  89901. sqlite3VtabImportErrmsg(p, pVtab);
  89902. }
  89903. }
  89904. db->aVTrans = aVTrans;
  89905. return rc;
  89906. }
  89907. /*
  89908. ** Invoke the xRollback method of all virtual tables in the
  89909. ** sqlite3.aVTrans array. Then clear the array itself.
  89910. */
  89911. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  89912. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  89913. return SQLITE_OK;
  89914. }
  89915. /*
  89916. ** Invoke the xCommit method of all virtual tables in the
  89917. ** sqlite3.aVTrans array. Then clear the array itself.
  89918. */
  89919. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  89920. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  89921. return SQLITE_OK;
  89922. }
  89923. /*
  89924. ** If the virtual table pVtab supports the transaction interface
  89925. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  89926. ** not currently open, invoke the xBegin method now.
  89927. **
  89928. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  89929. ** in the sqlite3.aVTrans array.
  89930. */
  89931. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  89932. int rc = SQLITE_OK;
  89933. const sqlite3_module *pModule;
  89934. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  89935. ** than zero, then this function is being called from within a
  89936. ** virtual module xSync() callback. It is illegal to write to
  89937. ** virtual module tables in this case, so return SQLITE_LOCKED.
  89938. */
  89939. if( sqlite3VtabInSync(db) ){
  89940. return SQLITE_LOCKED;
  89941. }
  89942. if( !pVTab ){
  89943. return SQLITE_OK;
  89944. }
  89945. pModule = pVTab->pVtab->pModule;
  89946. if( pModule->xBegin ){
  89947. int i;
  89948. /* If pVtab is already in the aVTrans array, return early */
  89949. for(i=0; i<db->nVTrans; i++){
  89950. if( db->aVTrans[i]==pVTab ){
  89951. return SQLITE_OK;
  89952. }
  89953. }
  89954. /* Invoke the xBegin method. If successful, add the vtab to the
  89955. ** sqlite3.aVTrans[] array. */
  89956. rc = growVTrans(db);
  89957. if( rc==SQLITE_OK ){
  89958. rc = pModule->xBegin(pVTab->pVtab);
  89959. if( rc==SQLITE_OK ){
  89960. addToVTrans(db, pVTab);
  89961. }
  89962. }
  89963. }
  89964. return rc;
  89965. }
  89966. /*
  89967. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  89968. ** virtual tables that currently have an open transaction. Pass iSavepoint
  89969. ** as the second argument to the virtual table method invoked.
  89970. **
  89971. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  89972. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  89973. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  89974. ** an open transaction is invoked.
  89975. **
  89976. ** If any virtual table method returns an error code other than SQLITE_OK,
  89977. ** processing is abandoned and the error returned to the caller of this
  89978. ** function immediately. If all calls to virtual table methods are successful,
  89979. ** SQLITE_OK is returned.
  89980. */
  89981. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  89982. int rc = SQLITE_OK;
  89983. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  89984. assert( iSavepoint>=0 );
  89985. if( db->aVTrans ){
  89986. int i;
  89987. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  89988. VTable *pVTab = db->aVTrans[i];
  89989. const sqlite3_module *pMod = pVTab->pMod->pModule;
  89990. if( pVTab->pVtab && pMod->iVersion>=2 ){
  89991. int (*xMethod)(sqlite3_vtab *, int);
  89992. switch( op ){
  89993. case SAVEPOINT_BEGIN:
  89994. xMethod = pMod->xSavepoint;
  89995. pVTab->iSavepoint = iSavepoint+1;
  89996. break;
  89997. case SAVEPOINT_ROLLBACK:
  89998. xMethod = pMod->xRollbackTo;
  89999. break;
  90000. default:
  90001. xMethod = pMod->xRelease;
  90002. break;
  90003. }
  90004. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  90005. rc = xMethod(pVTab->pVtab, iSavepoint);
  90006. }
  90007. }
  90008. }
  90009. }
  90010. return rc;
  90011. }
  90012. /*
  90013. ** The first parameter (pDef) is a function implementation. The
  90014. ** second parameter (pExpr) is the first argument to this function.
  90015. ** If pExpr is a column in a virtual table, then let the virtual
  90016. ** table implementation have an opportunity to overload the function.
  90017. **
  90018. ** This routine is used to allow virtual table implementations to
  90019. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  90020. **
  90021. ** Return either the pDef argument (indicating no change) or a
  90022. ** new FuncDef structure that is marked as ephemeral using the
  90023. ** SQLITE_FUNC_EPHEM flag.
  90024. */
  90025. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  90026. sqlite3 *db, /* Database connection for reporting malloc problems */
  90027. FuncDef *pDef, /* Function to possibly overload */
  90028. int nArg, /* Number of arguments to the function */
  90029. Expr *pExpr /* First argument to the function */
  90030. ){
  90031. Table *pTab;
  90032. sqlite3_vtab *pVtab;
  90033. sqlite3_module *pMod;
  90034. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  90035. void *pArg = 0;
  90036. FuncDef *pNew;
  90037. int rc = 0;
  90038. char *zLowerName;
  90039. unsigned char *z;
  90040. /* Check to see the left operand is a column in a virtual table */
  90041. if( NEVER(pExpr==0) ) return pDef;
  90042. if( pExpr->op!=TK_COLUMN ) return pDef;
  90043. pTab = pExpr->pTab;
  90044. if( NEVER(pTab==0) ) return pDef;
  90045. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  90046. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  90047. assert( pVtab!=0 );
  90048. assert( pVtab->pModule!=0 );
  90049. pMod = (sqlite3_module *)pVtab->pModule;
  90050. if( pMod->xFindFunction==0 ) return pDef;
  90051. /* Call the xFindFunction method on the virtual table implementation
  90052. ** to see if the implementation wants to overload this function
  90053. */
  90054. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  90055. if( zLowerName ){
  90056. for(z=(unsigned char*)zLowerName; *z; z++){
  90057. *z = sqlite3UpperToLower[*z];
  90058. }
  90059. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  90060. sqlite3DbFree(db, zLowerName);
  90061. }
  90062. if( rc==0 ){
  90063. return pDef;
  90064. }
  90065. /* Create a new ephemeral function definition for the overloaded
  90066. ** function */
  90067. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  90068. + sqlite3Strlen30(pDef->zName) + 1);
  90069. if( pNew==0 ){
  90070. return pDef;
  90071. }
  90072. *pNew = *pDef;
  90073. pNew->zName = (char *)&pNew[1];
  90074. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  90075. pNew->xFunc = xFunc;
  90076. pNew->pUserData = pArg;
  90077. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  90078. return pNew;
  90079. }
  90080. /*
  90081. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  90082. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  90083. ** array if it is missing. If pTab is already in the array, this routine
  90084. ** is a no-op.
  90085. */
  90086. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  90087. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  90088. int i, n;
  90089. Table **apVtabLock;
  90090. assert( IsVirtual(pTab) );
  90091. for(i=0; i<pToplevel->nVtabLock; i++){
  90092. if( pTab==pToplevel->apVtabLock[i] ) return;
  90093. }
  90094. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  90095. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  90096. if( apVtabLock ){
  90097. pToplevel->apVtabLock = apVtabLock;
  90098. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  90099. }else{
  90100. pToplevel->db->mallocFailed = 1;
  90101. }
  90102. }
  90103. /*
  90104. ** Return the ON CONFLICT resolution mode in effect for the virtual
  90105. ** table update operation currently in progress.
  90106. **
  90107. ** The results of this routine are undefined unless it is called from
  90108. ** within an xUpdate method.
  90109. */
  90110. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  90111. static const unsigned char aMap[] = {
  90112. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  90113. };
  90114. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  90115. assert( OE_Ignore==4 && OE_Replace==5 );
  90116. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  90117. return (int)aMap[db->vtabOnConflict-1];
  90118. }
  90119. /*
  90120. ** Call from within the xCreate() or xConnect() methods to provide
  90121. ** the SQLite core with additional information about the behavior
  90122. ** of the virtual table being implemented.
  90123. */
  90124. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  90125. va_list ap;
  90126. int rc = SQLITE_OK;
  90127. sqlite3_mutex_enter(db->mutex);
  90128. va_start(ap, op);
  90129. switch( op ){
  90130. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  90131. VtabCtx *p = db->pVtabCtx;
  90132. if( !p ){
  90133. rc = SQLITE_MISUSE_BKPT;
  90134. }else{
  90135. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  90136. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  90137. }
  90138. break;
  90139. }
  90140. default:
  90141. rc = SQLITE_MISUSE_BKPT;
  90142. break;
  90143. }
  90144. va_end(ap);
  90145. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  90146. sqlite3_mutex_leave(db->mutex);
  90147. return rc;
  90148. }
  90149. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  90150. /************** End of vtab.c ************************************************/
  90151. /************** Begin file where.c *******************************************/
  90152. /*
  90153. ** 2001 September 15
  90154. **
  90155. ** The author disclaims copyright to this source code. In place of
  90156. ** a legal notice, here is a blessing:
  90157. **
  90158. ** May you do good and not evil.
  90159. ** May you find forgiveness for yourself and forgive others.
  90160. ** May you share freely, never taking more than you give.
  90161. **
  90162. *************************************************************************
  90163. ** This module contains C code that generates VDBE code used to process
  90164. ** the WHERE clause of SQL statements. This module is responsible for
  90165. ** generating the code that loops through a table looking for applicable
  90166. ** rows. Indices are selected and used to speed the search when doing
  90167. ** so is applicable. Because this module is responsible for selecting
  90168. ** indices, you might also think of this module as the "query optimizer".
  90169. */
  90170. /*
  90171. ** Trace output macros
  90172. */
  90173. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  90174. /***/ int sqlite3WhereTrace = 0;
  90175. #endif
  90176. #if defined(SQLITE_DEBUG) \
  90177. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  90178. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  90179. # define WHERETRACE_ENABLED 1
  90180. #else
  90181. # define WHERETRACE(K,X)
  90182. #endif
  90183. /* Forward references
  90184. */
  90185. typedef struct WhereClause WhereClause;
  90186. typedef struct WhereMaskSet WhereMaskSet;
  90187. typedef struct WhereOrInfo WhereOrInfo;
  90188. typedef struct WhereAndInfo WhereAndInfo;
  90189. typedef struct WhereLevel WhereLevel;
  90190. typedef struct WhereLoop WhereLoop;
  90191. typedef struct WherePath WherePath;
  90192. typedef struct WhereTerm WhereTerm;
  90193. typedef struct WhereLoopBuilder WhereLoopBuilder;
  90194. typedef struct WhereScan WhereScan;
  90195. typedef struct WhereOrCost WhereOrCost;
  90196. typedef struct WhereOrSet WhereOrSet;
  90197. /*
  90198. ** This object contains information needed to implement a single nested
  90199. ** loop in WHERE clause.
  90200. **
  90201. ** Contrast this object with WhereLoop. This object describes the
  90202. ** implementation of the loop. WhereLoop describes the algorithm.
  90203. ** This object contains a pointer to the WhereLoop algorithm as one of
  90204. ** its elements.
  90205. **
  90206. ** The WhereInfo object contains a single instance of this object for
  90207. ** each term in the FROM clause (which is to say, for each of the
  90208. ** nested loops as implemented). The order of WhereLevel objects determines
  90209. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  90210. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  90211. */
  90212. struct WhereLevel {
  90213. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  90214. int iTabCur; /* The VDBE cursor used to access the table */
  90215. int iIdxCur; /* The VDBE cursor used to access pIdx */
  90216. int addrBrk; /* Jump here to break out of the loop */
  90217. int addrNxt; /* Jump here to start the next IN combination */
  90218. int addrCont; /* Jump here to continue with the next loop cycle */
  90219. int addrFirst; /* First instruction of interior of the loop */
  90220. int addrBody; /* Beginning of the body of this loop */
  90221. u8 iFrom; /* Which entry in the FROM clause */
  90222. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  90223. int p1, p2; /* Operands of the opcode used to ends the loop */
  90224. union { /* Information that depends on pWLoop->wsFlags */
  90225. struct {
  90226. int nIn; /* Number of entries in aInLoop[] */
  90227. struct InLoop {
  90228. int iCur; /* The VDBE cursor used by this IN operator */
  90229. int addrInTop; /* Top of the IN loop */
  90230. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  90231. } *aInLoop; /* Information about each nested IN operator */
  90232. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  90233. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  90234. } u;
  90235. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  90236. Bitmask notReady; /* FROM entries not usable at this level */
  90237. };
  90238. /*
  90239. ** Each instance of this object represents an algorithm for evaluating one
  90240. ** term of a join. Every term of the FROM clause will have at least
  90241. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  90242. ** prevent a query solution - which is an error) and many terms of the
  90243. ** FROM clause will have multiple WhereLoop objects, each describing a
  90244. ** potential way of implementing that FROM-clause term, together with
  90245. ** dependencies and cost estimates for using the chosen algorithm.
  90246. **
  90247. ** Query planning consists of building up a collection of these WhereLoop
  90248. ** objects, then computing a particular sequence of WhereLoop objects, with
  90249. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  90250. ** and that minimize the overall cost.
  90251. */
  90252. struct WhereLoop {
  90253. Bitmask prereq; /* Bitmask of other loops that must run first */
  90254. Bitmask maskSelf; /* Bitmask identifying table iTab */
  90255. #ifdef SQLITE_DEBUG
  90256. char cId; /* Symbolic ID of this loop for debugging use */
  90257. #endif
  90258. u8 iTab; /* Position in FROM clause of table for this loop */
  90259. u8 iSortIdx; /* Sorting index number. 0==None */
  90260. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  90261. LogEst rRun; /* Cost of running each loop */
  90262. LogEst nOut; /* Estimated number of output rows */
  90263. union {
  90264. struct { /* Information for internal btree tables */
  90265. int nEq; /* Number of equality constraints */
  90266. Index *pIndex; /* Index used, or NULL */
  90267. } btree;
  90268. struct { /* Information for virtual tables */
  90269. int idxNum; /* Index number */
  90270. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  90271. u8 isOrdered; /* True if satisfies ORDER BY */
  90272. u16 omitMask; /* Terms that may be omitted */
  90273. char *idxStr; /* Index identifier string */
  90274. } vtab;
  90275. } u;
  90276. u32 wsFlags; /* WHERE_* flags describing the plan */
  90277. u16 nLTerm; /* Number of entries in aLTerm[] */
  90278. /**** whereLoopXfer() copies fields above ***********************/
  90279. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  90280. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  90281. WhereTerm **aLTerm; /* WhereTerms used */
  90282. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  90283. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  90284. };
  90285. /* This object holds the prerequisites and the cost of running a
  90286. ** subquery on one operand of an OR operator in the WHERE clause.
  90287. ** See WhereOrSet for additional information
  90288. */
  90289. struct WhereOrCost {
  90290. Bitmask prereq; /* Prerequisites */
  90291. LogEst rRun; /* Cost of running this subquery */
  90292. LogEst nOut; /* Number of outputs for this subquery */
  90293. };
  90294. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  90295. ** correspond to the subquery(s) of OR-clause processing. Only the
  90296. ** best N_OR_COST elements are retained.
  90297. */
  90298. #define N_OR_COST 3
  90299. struct WhereOrSet {
  90300. u16 n; /* Number of valid a[] entries */
  90301. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  90302. };
  90303. /* Forward declaration of methods */
  90304. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  90305. /*
  90306. ** Each instance of this object holds a sequence of WhereLoop objects
  90307. ** that implement some or all of a query plan.
  90308. **
  90309. ** Think of each WhereLoop object as a node in a graph with arcs
  90310. ** showing dependencies and costs for travelling between nodes. (That is
  90311. ** not a completely accurate description because WhereLoop costs are a
  90312. ** vector, not a scalar, and because dependencies are many-to-one, not
  90313. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  90314. ** Then a WherePath object is a path through the graph that visits some
  90315. ** or all of the WhereLoop objects once.
  90316. **
  90317. ** The "solver" works by creating the N best WherePath objects of length
  90318. ** 1. Then using those as a basis to compute the N best WherePath objects
  90319. ** of length 2. And so forth until the length of WherePaths equals the
  90320. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  90321. ** at the end is the choosen query plan.
  90322. */
  90323. struct WherePath {
  90324. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  90325. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  90326. LogEst nRow; /* Estimated number of rows generated by this path */
  90327. LogEst rCost; /* Total cost of this path */
  90328. u8 isOrdered; /* True if this path satisfies ORDER BY */
  90329. u8 isOrderedValid; /* True if the isOrdered field is valid */
  90330. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  90331. };
  90332. /*
  90333. ** The query generator uses an array of instances of this structure to
  90334. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  90335. ** clause subexpression is separated from the others by AND operators,
  90336. ** usually, or sometimes subexpressions separated by OR.
  90337. **
  90338. ** All WhereTerms are collected into a single WhereClause structure.
  90339. ** The following identity holds:
  90340. **
  90341. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  90342. **
  90343. ** When a term is of the form:
  90344. **
  90345. ** X <op> <expr>
  90346. **
  90347. ** where X is a column name and <op> is one of certain operators,
  90348. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  90349. ** cursor number and column number for X. WhereTerm.eOperator records
  90350. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  90351. ** use of a bitmask encoding for the operator allows us to search
  90352. ** quickly for terms that match any of several different operators.
  90353. **
  90354. ** A WhereTerm might also be two or more subterms connected by OR:
  90355. **
  90356. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  90357. **
  90358. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  90359. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  90360. ** is collected about the OR clause.
  90361. **
  90362. ** If a term in the WHERE clause does not match either of the two previous
  90363. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  90364. ** to the original subexpression content and wtFlags is set up appropriately
  90365. ** but no other fields in the WhereTerm object are meaningful.
  90366. **
  90367. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  90368. ** but they do so indirectly. A single WhereMaskSet structure translates
  90369. ** cursor number into bits and the translated bit is stored in the prereq
  90370. ** fields. The translation is used in order to maximize the number of
  90371. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  90372. ** spread out over the non-negative integers. For example, the cursor
  90373. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  90374. ** translates these sparse cursor numbers into consecutive integers
  90375. ** beginning with 0 in order to make the best possible use of the available
  90376. ** bits in the Bitmask. So, in the example above, the cursor numbers
  90377. ** would be mapped into integers 0 through 7.
  90378. **
  90379. ** The number of terms in a join is limited by the number of bits
  90380. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  90381. ** is only able to process joins with 64 or fewer tables.
  90382. */
  90383. struct WhereTerm {
  90384. Expr *pExpr; /* Pointer to the subexpression that is this term */
  90385. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  90386. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  90387. union {
  90388. int leftColumn; /* Column number of X in "X <op> <expr>" */
  90389. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  90390. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  90391. } u;
  90392. LogEst truthProb; /* Probability of truth for this expression */
  90393. u16 eOperator; /* A WO_xx value describing <op> */
  90394. u8 wtFlags; /* TERM_xxx bit flags. See below */
  90395. u8 nChild; /* Number of children that must disable us */
  90396. WhereClause *pWC; /* The clause this term is part of */
  90397. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  90398. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  90399. };
  90400. /*
  90401. ** Allowed values of WhereTerm.wtFlags
  90402. */
  90403. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  90404. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  90405. #define TERM_CODED 0x04 /* This term is already coded */
  90406. #define TERM_COPIED 0x08 /* Has a child */
  90407. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  90408. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  90409. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  90410. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  90411. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  90412. #else
  90413. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  90414. #endif
  90415. /*
  90416. ** An instance of the WhereScan object is used as an iterator for locating
  90417. ** terms in the WHERE clause that are useful to the query planner.
  90418. */
  90419. struct WhereScan {
  90420. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  90421. WhereClause *pWC; /* WhereClause currently being scanned */
  90422. char *zCollName; /* Required collating sequence, if not NULL */
  90423. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  90424. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  90425. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  90426. u32 opMask; /* Acceptable operators */
  90427. int k; /* Resume scanning at this->pWC->a[this->k] */
  90428. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  90429. };
  90430. /*
  90431. ** An instance of the following structure holds all information about a
  90432. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  90433. **
  90434. ** Explanation of pOuter: For a WHERE clause of the form
  90435. **
  90436. ** a AND ((b AND c) OR (d AND e)) AND f
  90437. **
  90438. ** There are separate WhereClause objects for the whole clause and for
  90439. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  90440. ** subclauses points to the WhereClause object for the whole clause.
  90441. */
  90442. struct WhereClause {
  90443. WhereInfo *pWInfo; /* WHERE clause processing context */
  90444. WhereClause *pOuter; /* Outer conjunction */
  90445. u8 op; /* Split operator. TK_AND or TK_OR */
  90446. int nTerm; /* Number of terms */
  90447. int nSlot; /* Number of entries in a[] */
  90448. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  90449. #if defined(SQLITE_SMALL_STACK)
  90450. WhereTerm aStatic[1]; /* Initial static space for a[] */
  90451. #else
  90452. WhereTerm aStatic[8]; /* Initial static space for a[] */
  90453. #endif
  90454. };
  90455. /*
  90456. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  90457. ** a dynamically allocated instance of the following structure.
  90458. */
  90459. struct WhereOrInfo {
  90460. WhereClause wc; /* Decomposition into subterms */
  90461. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  90462. };
  90463. /*
  90464. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  90465. ** a dynamically allocated instance of the following structure.
  90466. */
  90467. struct WhereAndInfo {
  90468. WhereClause wc; /* The subexpression broken out */
  90469. };
  90470. /*
  90471. ** An instance of the following structure keeps track of a mapping
  90472. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  90473. **
  90474. ** The VDBE cursor numbers are small integers contained in
  90475. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  90476. ** clause, the cursor numbers might not begin with 0 and they might
  90477. ** contain gaps in the numbering sequence. But we want to make maximum
  90478. ** use of the bits in our bitmasks. This structure provides a mapping
  90479. ** from the sparse cursor numbers into consecutive integers beginning
  90480. ** with 0.
  90481. **
  90482. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  90483. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  90484. **
  90485. ** For example, if the WHERE clause expression used these VDBE
  90486. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  90487. ** would map those cursor numbers into bits 0 through 5.
  90488. **
  90489. ** Note that the mapping is not necessarily ordered. In the example
  90490. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  90491. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  90492. ** does not really matter. What is important is that sparse cursor
  90493. ** numbers all get mapped into bit numbers that begin with 0 and contain
  90494. ** no gaps.
  90495. */
  90496. struct WhereMaskSet {
  90497. int n; /* Number of assigned cursor values */
  90498. int ix[BMS]; /* Cursor assigned to each bit */
  90499. };
  90500. /*
  90501. ** This object is a convenience wrapper holding all information needed
  90502. ** to construct WhereLoop objects for a particular query.
  90503. */
  90504. struct WhereLoopBuilder {
  90505. WhereInfo *pWInfo; /* Information about this WHERE */
  90506. WhereClause *pWC; /* WHERE clause terms */
  90507. ExprList *pOrderBy; /* ORDER BY clause */
  90508. WhereLoop *pNew; /* Template WhereLoop */
  90509. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  90510. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  90511. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  90512. int nRecValid; /* Number of valid fields currently in pRec */
  90513. #endif
  90514. };
  90515. /*
  90516. ** The WHERE clause processing routine has two halves. The
  90517. ** first part does the start of the WHERE loop and the second
  90518. ** half does the tail of the WHERE loop. An instance of
  90519. ** this structure is returned by the first half and passed
  90520. ** into the second half to give some continuity.
  90521. **
  90522. ** An instance of this object holds the complete state of the query
  90523. ** planner.
  90524. */
  90525. struct WhereInfo {
  90526. Parse *pParse; /* Parsing and code generating context */
  90527. SrcList *pTabList; /* List of tables in the join */
  90528. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  90529. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  90530. WhereLoop *pLoops; /* List of all WhereLoop objects */
  90531. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  90532. LogEst nRowOut; /* Estimated number of output rows */
  90533. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  90534. u8 bOBSat; /* ORDER BY satisfied by indices */
  90535. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  90536. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  90537. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  90538. u8 nLevel; /* Number of nested loop */
  90539. int iTop; /* The very beginning of the WHERE loop */
  90540. int iContinue; /* Jump here to continue with next record */
  90541. int iBreak; /* Jump here to break out of the loop */
  90542. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  90543. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  90544. WhereClause sWC; /* Decomposition of the WHERE clause */
  90545. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  90546. };
  90547. /*
  90548. ** Bitmasks for the operators on WhereTerm objects. These are all
  90549. ** operators that are of interest to the query planner. An
  90550. ** OR-ed combination of these values can be used when searching for
  90551. ** particular WhereTerms within a WhereClause.
  90552. */
  90553. #define WO_IN 0x001
  90554. #define WO_EQ 0x002
  90555. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  90556. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  90557. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  90558. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  90559. #define WO_MATCH 0x040
  90560. #define WO_ISNULL 0x080
  90561. #define WO_OR 0x100 /* Two or more OR-connected terms */
  90562. #define WO_AND 0x200 /* Two or more AND-connected terms */
  90563. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  90564. #define WO_NOOP 0x800 /* This term does not restrict search space */
  90565. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  90566. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  90567. /*
  90568. ** These are definitions of bits in the WhereLoop.wsFlags field.
  90569. ** The particular combination of bits in each WhereLoop help to
  90570. ** determine the algorithm that WhereLoop represents.
  90571. */
  90572. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  90573. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  90574. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  90575. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  90576. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  90577. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  90578. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  90579. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  90580. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  90581. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  90582. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  90583. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  90584. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  90585. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  90586. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  90587. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  90588. /*
  90589. ** Return the estimated number of output rows from a WHERE clause
  90590. */
  90591. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  90592. return sqlite3LogEstToInt(pWInfo->nRowOut);
  90593. }
  90594. /*
  90595. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  90596. ** WHERE clause returns outputs for DISTINCT processing.
  90597. */
  90598. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  90599. return pWInfo->eDistinct;
  90600. }
  90601. /*
  90602. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  90603. ** Return FALSE if the output needs to be sorted.
  90604. */
  90605. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  90606. return pWInfo->bOBSat!=0;
  90607. }
  90608. /*
  90609. ** Return the VDBE address or label to jump to in order to continue
  90610. ** immediately with the next row of a WHERE clause.
  90611. */
  90612. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  90613. return pWInfo->iContinue;
  90614. }
  90615. /*
  90616. ** Return the VDBE address or label to jump to in order to break
  90617. ** out of a WHERE loop.
  90618. */
  90619. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  90620. return pWInfo->iBreak;
  90621. }
  90622. /*
  90623. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  90624. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  90625. ** UPDATE or DELETE might change subsequent WHERE clause results.
  90626. */
  90627. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  90628. return pWInfo->okOnePass;
  90629. }
  90630. /*
  90631. ** Move the content of pSrc into pDest
  90632. */
  90633. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  90634. pDest->n = pSrc->n;
  90635. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  90636. }
  90637. /*
  90638. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  90639. **
  90640. ** The new entry might overwrite an existing entry, or it might be
  90641. ** appended, or it might be discarded. Do whatever is the right thing
  90642. ** so that pSet keeps the N_OR_COST best entries seen so far.
  90643. */
  90644. static int whereOrInsert(
  90645. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  90646. Bitmask prereq, /* Prerequisites of the new entry */
  90647. LogEst rRun, /* Run-cost of the new entry */
  90648. LogEst nOut /* Number of outputs for the new entry */
  90649. ){
  90650. u16 i;
  90651. WhereOrCost *p;
  90652. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  90653. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  90654. goto whereOrInsert_done;
  90655. }
  90656. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  90657. return 0;
  90658. }
  90659. }
  90660. if( pSet->n<N_OR_COST ){
  90661. p = &pSet->a[pSet->n++];
  90662. p->nOut = nOut;
  90663. }else{
  90664. p = pSet->a;
  90665. for(i=1; i<pSet->n; i++){
  90666. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  90667. }
  90668. if( p->rRun<=rRun ) return 0;
  90669. }
  90670. whereOrInsert_done:
  90671. p->prereq = prereq;
  90672. p->rRun = rRun;
  90673. if( p->nOut>nOut ) p->nOut = nOut;
  90674. return 1;
  90675. }
  90676. /*
  90677. ** Initialize a preallocated WhereClause structure.
  90678. */
  90679. static void whereClauseInit(
  90680. WhereClause *pWC, /* The WhereClause to be initialized */
  90681. WhereInfo *pWInfo /* The WHERE processing context */
  90682. ){
  90683. pWC->pWInfo = pWInfo;
  90684. pWC->pOuter = 0;
  90685. pWC->nTerm = 0;
  90686. pWC->nSlot = ArraySize(pWC->aStatic);
  90687. pWC->a = pWC->aStatic;
  90688. }
  90689. /* Forward reference */
  90690. static void whereClauseClear(WhereClause*);
  90691. /*
  90692. ** Deallocate all memory associated with a WhereOrInfo object.
  90693. */
  90694. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  90695. whereClauseClear(&p->wc);
  90696. sqlite3DbFree(db, p);
  90697. }
  90698. /*
  90699. ** Deallocate all memory associated with a WhereAndInfo object.
  90700. */
  90701. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  90702. whereClauseClear(&p->wc);
  90703. sqlite3DbFree(db, p);
  90704. }
  90705. /*
  90706. ** Deallocate a WhereClause structure. The WhereClause structure
  90707. ** itself is not freed. This routine is the inverse of whereClauseInit().
  90708. */
  90709. static void whereClauseClear(WhereClause *pWC){
  90710. int i;
  90711. WhereTerm *a;
  90712. sqlite3 *db = pWC->pWInfo->pParse->db;
  90713. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  90714. if( a->wtFlags & TERM_DYNAMIC ){
  90715. sqlite3ExprDelete(db, a->pExpr);
  90716. }
  90717. if( a->wtFlags & TERM_ORINFO ){
  90718. whereOrInfoDelete(db, a->u.pOrInfo);
  90719. }else if( a->wtFlags & TERM_ANDINFO ){
  90720. whereAndInfoDelete(db, a->u.pAndInfo);
  90721. }
  90722. }
  90723. if( pWC->a!=pWC->aStatic ){
  90724. sqlite3DbFree(db, pWC->a);
  90725. }
  90726. }
  90727. /*
  90728. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  90729. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  90730. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  90731. ** 0 is returned if the new WhereTerm could not be added due to a memory
  90732. ** allocation error. The memory allocation failure will be recorded in
  90733. ** the db->mallocFailed flag so that higher-level functions can detect it.
  90734. **
  90735. ** This routine will increase the size of the pWC->a[] array as necessary.
  90736. **
  90737. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  90738. ** for freeing the expression p is assumed by the WhereClause object pWC.
  90739. ** This is true even if this routine fails to allocate a new WhereTerm.
  90740. **
  90741. ** WARNING: This routine might reallocate the space used to store
  90742. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  90743. ** calling this routine. Such pointers may be reinitialized by referencing
  90744. ** the pWC->a[] array.
  90745. */
  90746. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  90747. WhereTerm *pTerm;
  90748. int idx;
  90749. testcase( wtFlags & TERM_VIRTUAL );
  90750. if( pWC->nTerm>=pWC->nSlot ){
  90751. WhereTerm *pOld = pWC->a;
  90752. sqlite3 *db = pWC->pWInfo->pParse->db;
  90753. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  90754. if( pWC->a==0 ){
  90755. if( wtFlags & TERM_DYNAMIC ){
  90756. sqlite3ExprDelete(db, p);
  90757. }
  90758. pWC->a = pOld;
  90759. return 0;
  90760. }
  90761. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  90762. if( pOld!=pWC->aStatic ){
  90763. sqlite3DbFree(db, pOld);
  90764. }
  90765. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  90766. }
  90767. pTerm = &pWC->a[idx = pWC->nTerm++];
  90768. if( p && ExprHasProperty(p, EP_Unlikely) ){
  90769. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  90770. }else{
  90771. pTerm->truthProb = -1;
  90772. }
  90773. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  90774. pTerm->wtFlags = wtFlags;
  90775. pTerm->pWC = pWC;
  90776. pTerm->iParent = -1;
  90777. return idx;
  90778. }
  90779. /*
  90780. ** This routine identifies subexpressions in the WHERE clause where
  90781. ** each subexpression is separated by the AND operator or some other
  90782. ** operator specified in the op parameter. The WhereClause structure
  90783. ** is filled with pointers to subexpressions. For example:
  90784. **
  90785. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  90786. ** \________/ \_______________/ \________________/
  90787. ** slot[0] slot[1] slot[2]
  90788. **
  90789. ** The original WHERE clause in pExpr is unaltered. All this routine
  90790. ** does is make slot[] entries point to substructure within pExpr.
  90791. **
  90792. ** In the previous sentence and in the diagram, "slot[]" refers to
  90793. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  90794. ** all terms of the WHERE clause.
  90795. */
  90796. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  90797. pWC->op = op;
  90798. if( pExpr==0 ) return;
  90799. if( pExpr->op!=op ){
  90800. whereClauseInsert(pWC, pExpr, 0);
  90801. }else{
  90802. whereSplit(pWC, pExpr->pLeft, op);
  90803. whereSplit(pWC, pExpr->pRight, op);
  90804. }
  90805. }
  90806. /*
  90807. ** Initialize a WhereMaskSet object
  90808. */
  90809. #define initMaskSet(P) (P)->n=0
  90810. /*
  90811. ** Return the bitmask for the given cursor number. Return 0 if
  90812. ** iCursor is not in the set.
  90813. */
  90814. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  90815. int i;
  90816. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  90817. for(i=0; i<pMaskSet->n; i++){
  90818. if( pMaskSet->ix[i]==iCursor ){
  90819. return MASKBIT(i);
  90820. }
  90821. }
  90822. return 0;
  90823. }
  90824. /*
  90825. ** Create a new mask for cursor iCursor.
  90826. **
  90827. ** There is one cursor per table in the FROM clause. The number of
  90828. ** tables in the FROM clause is limited by a test early in the
  90829. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  90830. ** array will never overflow.
  90831. */
  90832. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  90833. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  90834. pMaskSet->ix[pMaskSet->n++] = iCursor;
  90835. }
  90836. /*
  90837. ** These routines walk (recursively) an expression tree and generate
  90838. ** a bitmask indicating which tables are used in that expression
  90839. ** tree.
  90840. */
  90841. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  90842. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  90843. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  90844. Bitmask mask = 0;
  90845. if( p==0 ) return 0;
  90846. if( p->op==TK_COLUMN ){
  90847. mask = getMask(pMaskSet, p->iTable);
  90848. return mask;
  90849. }
  90850. mask = exprTableUsage(pMaskSet, p->pRight);
  90851. mask |= exprTableUsage(pMaskSet, p->pLeft);
  90852. if( ExprHasProperty(p, EP_xIsSelect) ){
  90853. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  90854. }else{
  90855. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  90856. }
  90857. return mask;
  90858. }
  90859. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  90860. int i;
  90861. Bitmask mask = 0;
  90862. if( pList ){
  90863. for(i=0; i<pList->nExpr; i++){
  90864. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  90865. }
  90866. }
  90867. return mask;
  90868. }
  90869. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  90870. Bitmask mask = 0;
  90871. while( pS ){
  90872. SrcList *pSrc = pS->pSrc;
  90873. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  90874. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  90875. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  90876. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  90877. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  90878. if( ALWAYS(pSrc!=0) ){
  90879. int i;
  90880. for(i=0; i<pSrc->nSrc; i++){
  90881. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  90882. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  90883. }
  90884. }
  90885. pS = pS->pPrior;
  90886. }
  90887. return mask;
  90888. }
  90889. /*
  90890. ** Return TRUE if the given operator is one of the operators that is
  90891. ** allowed for an indexable WHERE clause term. The allowed operators are
  90892. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  90893. */
  90894. static int allowedOp(int op){
  90895. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  90896. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  90897. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  90898. assert( TK_GE==TK_EQ+4 );
  90899. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  90900. }
  90901. /*
  90902. ** Swap two objects of type TYPE.
  90903. */
  90904. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  90905. /*
  90906. ** Commute a comparison operator. Expressions of the form "X op Y"
  90907. ** are converted into "Y op X".
  90908. **
  90909. ** If left/right precedence rules come into play when determining the
  90910. ** collating sequence, then COLLATE operators are adjusted to ensure
  90911. ** that the collating sequence does not change. For example:
  90912. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  90913. ** the left hand side of a comparison overrides any collation sequence
  90914. ** attached to the right. For the same reason the EP_Collate flag
  90915. ** is not commuted.
  90916. */
  90917. static void exprCommute(Parse *pParse, Expr *pExpr){
  90918. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  90919. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  90920. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  90921. if( expRight==expLeft ){
  90922. /* Either X and Y both have COLLATE operator or neither do */
  90923. if( expRight ){
  90924. /* Both X and Y have COLLATE operators. Make sure X is always
  90925. ** used by clearing the EP_Collate flag from Y. */
  90926. pExpr->pRight->flags &= ~EP_Collate;
  90927. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  90928. /* Neither X nor Y have COLLATE operators, but X has a non-default
  90929. ** collating sequence. So add the EP_Collate marker on X to cause
  90930. ** it to be searched first. */
  90931. pExpr->pLeft->flags |= EP_Collate;
  90932. }
  90933. }
  90934. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  90935. if( pExpr->op>=TK_GT ){
  90936. assert( TK_LT==TK_GT+2 );
  90937. assert( TK_GE==TK_LE+2 );
  90938. assert( TK_GT>TK_EQ );
  90939. assert( TK_GT<TK_LE );
  90940. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  90941. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  90942. }
  90943. }
  90944. /*
  90945. ** Translate from TK_xx operator to WO_xx bitmask.
  90946. */
  90947. static u16 operatorMask(int op){
  90948. u16 c;
  90949. assert( allowedOp(op) );
  90950. if( op==TK_IN ){
  90951. c = WO_IN;
  90952. }else if( op==TK_ISNULL ){
  90953. c = WO_ISNULL;
  90954. }else{
  90955. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  90956. c = (u16)(WO_EQ<<(op-TK_EQ));
  90957. }
  90958. assert( op!=TK_ISNULL || c==WO_ISNULL );
  90959. assert( op!=TK_IN || c==WO_IN );
  90960. assert( op!=TK_EQ || c==WO_EQ );
  90961. assert( op!=TK_LT || c==WO_LT );
  90962. assert( op!=TK_LE || c==WO_LE );
  90963. assert( op!=TK_GT || c==WO_GT );
  90964. assert( op!=TK_GE || c==WO_GE );
  90965. return c;
  90966. }
  90967. /*
  90968. ** Advance to the next WhereTerm that matches according to the criteria
  90969. ** established when the pScan object was initialized by whereScanInit().
  90970. ** Return NULL if there are no more matching WhereTerms.
  90971. */
  90972. static WhereTerm *whereScanNext(WhereScan *pScan){
  90973. int iCur; /* The cursor on the LHS of the term */
  90974. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  90975. Expr *pX; /* An expression being tested */
  90976. WhereClause *pWC; /* Shorthand for pScan->pWC */
  90977. WhereTerm *pTerm; /* The term being tested */
  90978. int k = pScan->k; /* Where to start scanning */
  90979. while( pScan->iEquiv<=pScan->nEquiv ){
  90980. iCur = pScan->aEquiv[pScan->iEquiv-2];
  90981. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  90982. while( (pWC = pScan->pWC)!=0 ){
  90983. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  90984. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  90985. if( (pTerm->eOperator & WO_EQUIV)!=0
  90986. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  90987. ){
  90988. int j;
  90989. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  90990. assert( pX->op==TK_COLUMN );
  90991. for(j=0; j<pScan->nEquiv; j+=2){
  90992. if( pScan->aEquiv[j]==pX->iTable
  90993. && pScan->aEquiv[j+1]==pX->iColumn ){
  90994. break;
  90995. }
  90996. }
  90997. if( j==pScan->nEquiv ){
  90998. pScan->aEquiv[j] = pX->iTable;
  90999. pScan->aEquiv[j+1] = pX->iColumn;
  91000. pScan->nEquiv += 2;
  91001. }
  91002. }
  91003. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  91004. /* Verify the affinity and collating sequence match */
  91005. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  91006. CollSeq *pColl;
  91007. Parse *pParse = pWC->pWInfo->pParse;
  91008. pX = pTerm->pExpr;
  91009. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  91010. continue;
  91011. }
  91012. assert(pX->pLeft);
  91013. pColl = sqlite3BinaryCompareCollSeq(pParse,
  91014. pX->pLeft, pX->pRight);
  91015. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  91016. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  91017. continue;
  91018. }
  91019. }
  91020. if( (pTerm->eOperator & WO_EQ)!=0
  91021. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  91022. && pX->iTable==pScan->aEquiv[0]
  91023. && pX->iColumn==pScan->aEquiv[1]
  91024. ){
  91025. continue;
  91026. }
  91027. pScan->k = k+1;
  91028. return pTerm;
  91029. }
  91030. }
  91031. }
  91032. pScan->pWC = pScan->pWC->pOuter;
  91033. k = 0;
  91034. }
  91035. pScan->pWC = pScan->pOrigWC;
  91036. k = 0;
  91037. pScan->iEquiv += 2;
  91038. }
  91039. return 0;
  91040. }
  91041. /*
  91042. ** Initialize a WHERE clause scanner object. Return a pointer to the
  91043. ** first match. Return NULL if there are no matches.
  91044. **
  91045. ** The scanner will be searching the WHERE clause pWC. It will look
  91046. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  91047. ** iCur. The <op> must be one of the operators described by opMask.
  91048. **
  91049. ** If the search is for X and the WHERE clause contains terms of the
  91050. ** form X=Y then this routine might also return terms of the form
  91051. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  91052. ** but is enough to handle most commonly occurring SQL statements.
  91053. **
  91054. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  91055. ** index pIdx.
  91056. */
  91057. static WhereTerm *whereScanInit(
  91058. WhereScan *pScan, /* The WhereScan object being initialized */
  91059. WhereClause *pWC, /* The WHERE clause to be scanned */
  91060. int iCur, /* Cursor to scan for */
  91061. int iColumn, /* Column to scan for */
  91062. u32 opMask, /* Operator(s) to scan for */
  91063. Index *pIdx /* Must be compatible with this index */
  91064. ){
  91065. int j;
  91066. /* memset(pScan, 0, sizeof(*pScan)); */
  91067. pScan->pOrigWC = pWC;
  91068. pScan->pWC = pWC;
  91069. if( pIdx && iColumn>=0 ){
  91070. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  91071. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  91072. if( NEVER(j>=pIdx->nColumn) ) return 0;
  91073. }
  91074. pScan->zCollName = pIdx->azColl[j];
  91075. }else{
  91076. pScan->idxaff = 0;
  91077. pScan->zCollName = 0;
  91078. }
  91079. pScan->opMask = opMask;
  91080. pScan->k = 0;
  91081. pScan->aEquiv[0] = iCur;
  91082. pScan->aEquiv[1] = iColumn;
  91083. pScan->nEquiv = 2;
  91084. pScan->iEquiv = 2;
  91085. return whereScanNext(pScan);
  91086. }
  91087. /*
  91088. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  91089. ** where X is a reference to the iColumn of table iCur and <op> is one of
  91090. ** the WO_xx operator codes specified by the op parameter.
  91091. ** Return a pointer to the term. Return 0 if not found.
  91092. **
  91093. ** The term returned might by Y=<expr> if there is another constraint in
  91094. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  91095. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  91096. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  91097. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  91098. ** and the second is for the column number. There are 22 slots in aEquiv[]
  91099. ** so that means we can look for X plus up to 10 other equivalent values.
  91100. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  91101. ** and ... and A9=A10 and A10=<expr>.
  91102. **
  91103. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  91104. ** then try for the one with no dependencies on <expr> - in other words where
  91105. ** <expr> is a constant expression of some kind. Only return entries of
  91106. ** the form "X <op> Y" where Y is a column in another table if no terms of
  91107. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  91108. ** exist, try to return a term that does not use WO_EQUIV.
  91109. */
  91110. static WhereTerm *findTerm(
  91111. WhereClause *pWC, /* The WHERE clause to be searched */
  91112. int iCur, /* Cursor number of LHS */
  91113. int iColumn, /* Column number of LHS */
  91114. Bitmask notReady, /* RHS must not overlap with this mask */
  91115. u32 op, /* Mask of WO_xx values describing operator */
  91116. Index *pIdx /* Must be compatible with this index, if not NULL */
  91117. ){
  91118. WhereTerm *pResult = 0;
  91119. WhereTerm *p;
  91120. WhereScan scan;
  91121. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  91122. while( p ){
  91123. if( (p->prereqRight & notReady)==0 ){
  91124. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  91125. return p;
  91126. }
  91127. if( pResult==0 ) pResult = p;
  91128. }
  91129. p = whereScanNext(&scan);
  91130. }
  91131. return pResult;
  91132. }
  91133. /* Forward reference */
  91134. static void exprAnalyze(SrcList*, WhereClause*, int);
  91135. /*
  91136. ** Call exprAnalyze on all terms in a WHERE clause.
  91137. */
  91138. static void exprAnalyzeAll(
  91139. SrcList *pTabList, /* the FROM clause */
  91140. WhereClause *pWC /* the WHERE clause to be analyzed */
  91141. ){
  91142. int i;
  91143. for(i=pWC->nTerm-1; i>=0; i--){
  91144. exprAnalyze(pTabList, pWC, i);
  91145. }
  91146. }
  91147. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  91148. /*
  91149. ** Check to see if the given expression is a LIKE or GLOB operator that
  91150. ** can be optimized using inequality constraints. Return TRUE if it is
  91151. ** so and false if not.
  91152. **
  91153. ** In order for the operator to be optimizible, the RHS must be a string
  91154. ** literal that does not begin with a wildcard.
  91155. */
  91156. static int isLikeOrGlob(
  91157. Parse *pParse, /* Parsing and code generating context */
  91158. Expr *pExpr, /* Test this expression */
  91159. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  91160. int *pisComplete, /* True if the only wildcard is % in the last character */
  91161. int *pnoCase /* True if uppercase is equivalent to lowercase */
  91162. ){
  91163. const char *z = 0; /* String on RHS of LIKE operator */
  91164. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  91165. ExprList *pList; /* List of operands to the LIKE operator */
  91166. int c; /* One character in z[] */
  91167. int cnt; /* Number of non-wildcard prefix characters */
  91168. char wc[3]; /* Wildcard characters */
  91169. sqlite3 *db = pParse->db; /* Database connection */
  91170. sqlite3_value *pVal = 0;
  91171. int op; /* Opcode of pRight */
  91172. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  91173. return 0;
  91174. }
  91175. #ifdef SQLITE_EBCDIC
  91176. if( *pnoCase ) return 0;
  91177. #endif
  91178. pList = pExpr->x.pList;
  91179. pLeft = pList->a[1].pExpr;
  91180. if( pLeft->op!=TK_COLUMN
  91181. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  91182. || IsVirtual(pLeft->pTab)
  91183. ){
  91184. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  91185. ** be the name of an indexed column with TEXT affinity. */
  91186. return 0;
  91187. }
  91188. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  91189. pRight = pList->a[0].pExpr;
  91190. op = pRight->op;
  91191. if( op==TK_REGISTER ){
  91192. op = pRight->op2;
  91193. }
  91194. if( op==TK_VARIABLE ){
  91195. Vdbe *pReprepare = pParse->pReprepare;
  91196. int iCol = pRight->iColumn;
  91197. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  91198. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  91199. z = (char *)sqlite3_value_text(pVal);
  91200. }
  91201. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  91202. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  91203. }else if( op==TK_STRING ){
  91204. z = pRight->u.zToken;
  91205. }
  91206. if( z ){
  91207. cnt = 0;
  91208. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  91209. cnt++;
  91210. }
  91211. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  91212. Expr *pPrefix;
  91213. *pisComplete = c==wc[0] && z[cnt+1]==0;
  91214. pPrefix = sqlite3Expr(db, TK_STRING, z);
  91215. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  91216. *ppPrefix = pPrefix;
  91217. if( op==TK_VARIABLE ){
  91218. Vdbe *v = pParse->pVdbe;
  91219. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  91220. if( *pisComplete && pRight->u.zToken[1] ){
  91221. /* If the rhs of the LIKE expression is a variable, and the current
  91222. ** value of the variable means there is no need to invoke the LIKE
  91223. ** function, then no OP_Variable will be added to the program.
  91224. ** This causes problems for the sqlite3_bind_parameter_name()
  91225. ** API. To workaround them, add a dummy OP_Variable here.
  91226. */
  91227. int r1 = sqlite3GetTempReg(pParse);
  91228. sqlite3ExprCodeTarget(pParse, pRight, r1);
  91229. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  91230. sqlite3ReleaseTempReg(pParse, r1);
  91231. }
  91232. }
  91233. }else{
  91234. z = 0;
  91235. }
  91236. }
  91237. sqlite3ValueFree(pVal);
  91238. return (z!=0);
  91239. }
  91240. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  91241. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91242. /*
  91243. ** Check to see if the given expression is of the form
  91244. **
  91245. ** column MATCH expr
  91246. **
  91247. ** If it is then return TRUE. If not, return FALSE.
  91248. */
  91249. static int isMatchOfColumn(
  91250. Expr *pExpr /* Test this expression */
  91251. ){
  91252. ExprList *pList;
  91253. if( pExpr->op!=TK_FUNCTION ){
  91254. return 0;
  91255. }
  91256. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  91257. return 0;
  91258. }
  91259. pList = pExpr->x.pList;
  91260. if( pList->nExpr!=2 ){
  91261. return 0;
  91262. }
  91263. if( pList->a[1].pExpr->op != TK_COLUMN ){
  91264. return 0;
  91265. }
  91266. return 1;
  91267. }
  91268. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91269. /*
  91270. ** If the pBase expression originated in the ON or USING clause of
  91271. ** a join, then transfer the appropriate markings over to derived.
  91272. */
  91273. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  91274. if( pDerived ){
  91275. pDerived->flags |= pBase->flags & EP_FromJoin;
  91276. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  91277. }
  91278. }
  91279. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  91280. /*
  91281. ** Analyze a term that consists of two or more OR-connected
  91282. ** subterms. So in:
  91283. **
  91284. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  91285. ** ^^^^^^^^^^^^^^^^^^^^
  91286. **
  91287. ** This routine analyzes terms such as the middle term in the above example.
  91288. ** A WhereOrTerm object is computed and attached to the term under
  91289. ** analysis, regardless of the outcome of the analysis. Hence:
  91290. **
  91291. ** WhereTerm.wtFlags |= TERM_ORINFO
  91292. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  91293. **
  91294. ** The term being analyzed must have two or more of OR-connected subterms.
  91295. ** A single subterm might be a set of AND-connected sub-subterms.
  91296. ** Examples of terms under analysis:
  91297. **
  91298. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  91299. ** (B) x=expr1 OR expr2=x OR x=expr3
  91300. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  91301. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  91302. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  91303. **
  91304. ** CASE 1:
  91305. **
  91306. ** If all subterms are of the form T.C=expr for some single column of C and
  91307. ** a single table T (as shown in example B above) then create a new virtual
  91308. ** term that is an equivalent IN expression. In other words, if the term
  91309. ** being analyzed is:
  91310. **
  91311. ** x = expr1 OR expr2 = x OR x = expr3
  91312. **
  91313. ** then create a new virtual term like this:
  91314. **
  91315. ** x IN (expr1,expr2,expr3)
  91316. **
  91317. ** CASE 2:
  91318. **
  91319. ** If all subterms are indexable by a single table T, then set
  91320. **
  91321. ** WhereTerm.eOperator = WO_OR
  91322. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  91323. **
  91324. ** A subterm is "indexable" if it is of the form
  91325. ** "T.C <op> <expr>" where C is any column of table T and
  91326. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  91327. ** A subterm is also indexable if it is an AND of two or more
  91328. ** subsubterms at least one of which is indexable. Indexable AND
  91329. ** subterms have their eOperator set to WO_AND and they have
  91330. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  91331. **
  91332. ** From another point of view, "indexable" means that the subterm could
  91333. ** potentially be used with an index if an appropriate index exists.
  91334. ** This analysis does not consider whether or not the index exists; that
  91335. ** is decided elsewhere. This analysis only looks at whether subterms
  91336. ** appropriate for indexing exist.
  91337. **
  91338. ** All examples A through E above satisfy case 2. But if a term
  91339. ** also statisfies case 1 (such as B) we know that the optimizer will
  91340. ** always prefer case 1, so in that case we pretend that case 2 is not
  91341. ** satisfied.
  91342. **
  91343. ** It might be the case that multiple tables are indexable. For example,
  91344. ** (E) above is indexable on tables P, Q, and R.
  91345. **
  91346. ** Terms that satisfy case 2 are candidates for lookup by using
  91347. ** separate indices to find rowids for each subterm and composing
  91348. ** the union of all rowids using a RowSet object. This is similar
  91349. ** to "bitmap indices" in other database engines.
  91350. **
  91351. ** OTHERWISE:
  91352. **
  91353. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  91354. ** zero. This term is not useful for search.
  91355. */
  91356. static void exprAnalyzeOrTerm(
  91357. SrcList *pSrc, /* the FROM clause */
  91358. WhereClause *pWC, /* the complete WHERE clause */
  91359. int idxTerm /* Index of the OR-term to be analyzed */
  91360. ){
  91361. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  91362. Parse *pParse = pWInfo->pParse; /* Parser context */
  91363. sqlite3 *db = pParse->db; /* Database connection */
  91364. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  91365. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  91366. int i; /* Loop counters */
  91367. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  91368. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  91369. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  91370. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  91371. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  91372. /*
  91373. ** Break the OR clause into its separate subterms. The subterms are
  91374. ** stored in a WhereClause structure containing within the WhereOrInfo
  91375. ** object that is attached to the original OR clause term.
  91376. */
  91377. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  91378. assert( pExpr->op==TK_OR );
  91379. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  91380. if( pOrInfo==0 ) return;
  91381. pTerm->wtFlags |= TERM_ORINFO;
  91382. pOrWc = &pOrInfo->wc;
  91383. whereClauseInit(pOrWc, pWInfo);
  91384. whereSplit(pOrWc, pExpr, TK_OR);
  91385. exprAnalyzeAll(pSrc, pOrWc);
  91386. if( db->mallocFailed ) return;
  91387. assert( pOrWc->nTerm>=2 );
  91388. /*
  91389. ** Compute the set of tables that might satisfy cases 1 or 2.
  91390. */
  91391. indexable = ~(Bitmask)0;
  91392. chngToIN = ~(Bitmask)0;
  91393. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  91394. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  91395. WhereAndInfo *pAndInfo;
  91396. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  91397. chngToIN = 0;
  91398. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  91399. if( pAndInfo ){
  91400. WhereClause *pAndWC;
  91401. WhereTerm *pAndTerm;
  91402. int j;
  91403. Bitmask b = 0;
  91404. pOrTerm->u.pAndInfo = pAndInfo;
  91405. pOrTerm->wtFlags |= TERM_ANDINFO;
  91406. pOrTerm->eOperator = WO_AND;
  91407. pAndWC = &pAndInfo->wc;
  91408. whereClauseInit(pAndWC, pWC->pWInfo);
  91409. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  91410. exprAnalyzeAll(pSrc, pAndWC);
  91411. pAndWC->pOuter = pWC;
  91412. testcase( db->mallocFailed );
  91413. if( !db->mallocFailed ){
  91414. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  91415. assert( pAndTerm->pExpr );
  91416. if( allowedOp(pAndTerm->pExpr->op) ){
  91417. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  91418. }
  91419. }
  91420. }
  91421. indexable &= b;
  91422. }
  91423. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  91424. /* Skip this term for now. We revisit it when we process the
  91425. ** corresponding TERM_VIRTUAL term */
  91426. }else{
  91427. Bitmask b;
  91428. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  91429. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  91430. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  91431. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  91432. }
  91433. indexable &= b;
  91434. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  91435. chngToIN = 0;
  91436. }else{
  91437. chngToIN &= b;
  91438. }
  91439. }
  91440. }
  91441. /*
  91442. ** Record the set of tables that satisfy case 2. The set might be
  91443. ** empty.
  91444. */
  91445. pOrInfo->indexable = indexable;
  91446. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  91447. /*
  91448. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  91449. ** we have to do some additional checking to see if case 1 really
  91450. ** is satisfied.
  91451. **
  91452. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  91453. ** that there is no possibility of transforming the OR clause into an
  91454. ** IN operator because one or more terms in the OR clause contain
  91455. ** something other than == on a column in the single table. The 1-bit
  91456. ** case means that every term of the OR clause is of the form
  91457. ** "table.column=expr" for some single table. The one bit that is set
  91458. ** will correspond to the common table. We still need to check to make
  91459. ** sure the same column is used on all terms. The 2-bit case is when
  91460. ** the all terms are of the form "table1.column=table2.column". It
  91461. ** might be possible to form an IN operator with either table1.column
  91462. ** or table2.column as the LHS if either is common to every term of
  91463. ** the OR clause.
  91464. **
  91465. ** Note that terms of the form "table.column1=table.column2" (the
  91466. ** same table on both sizes of the ==) cannot be optimized.
  91467. */
  91468. if( chngToIN ){
  91469. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  91470. int iColumn = -1; /* Column index on lhs of IN operator */
  91471. int iCursor = -1; /* Table cursor common to all terms */
  91472. int j = 0; /* Loop counter */
  91473. /* Search for a table and column that appears on one side or the
  91474. ** other of the == operator in every subterm. That table and column
  91475. ** will be recorded in iCursor and iColumn. There might not be any
  91476. ** such table and column. Set okToChngToIN if an appropriate table
  91477. ** and column is found but leave okToChngToIN false if not found.
  91478. */
  91479. for(j=0; j<2 && !okToChngToIN; j++){
  91480. pOrTerm = pOrWc->a;
  91481. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  91482. assert( pOrTerm->eOperator & WO_EQ );
  91483. pOrTerm->wtFlags &= ~TERM_OR_OK;
  91484. if( pOrTerm->leftCursor==iCursor ){
  91485. /* This is the 2-bit case and we are on the second iteration and
  91486. ** current term is from the first iteration. So skip this term. */
  91487. assert( j==1 );
  91488. continue;
  91489. }
  91490. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  91491. /* This term must be of the form t1.a==t2.b where t2 is in the
  91492. ** chngToIN set but t1 is not. This term will be either preceeded
  91493. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  91494. ** and use its inversion. */
  91495. testcase( pOrTerm->wtFlags & TERM_COPIED );
  91496. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  91497. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  91498. continue;
  91499. }
  91500. iColumn = pOrTerm->u.leftColumn;
  91501. iCursor = pOrTerm->leftCursor;
  91502. break;
  91503. }
  91504. if( i<0 ){
  91505. /* No candidate table+column was found. This can only occur
  91506. ** on the second iteration */
  91507. assert( j==1 );
  91508. assert( IsPowerOfTwo(chngToIN) );
  91509. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  91510. break;
  91511. }
  91512. testcase( j==1 );
  91513. /* We have found a candidate table and column. Check to see if that
  91514. ** table and column is common to every term in the OR clause */
  91515. okToChngToIN = 1;
  91516. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  91517. assert( pOrTerm->eOperator & WO_EQ );
  91518. if( pOrTerm->leftCursor!=iCursor ){
  91519. pOrTerm->wtFlags &= ~TERM_OR_OK;
  91520. }else if( pOrTerm->u.leftColumn!=iColumn ){
  91521. okToChngToIN = 0;
  91522. }else{
  91523. int affLeft, affRight;
  91524. /* If the right-hand side is also a column, then the affinities
  91525. ** of both right and left sides must be such that no type
  91526. ** conversions are required on the right. (Ticket #2249)
  91527. */
  91528. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  91529. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  91530. if( affRight!=0 && affRight!=affLeft ){
  91531. okToChngToIN = 0;
  91532. }else{
  91533. pOrTerm->wtFlags |= TERM_OR_OK;
  91534. }
  91535. }
  91536. }
  91537. }
  91538. /* At this point, okToChngToIN is true if original pTerm satisfies
  91539. ** case 1. In that case, construct a new virtual term that is
  91540. ** pTerm converted into an IN operator.
  91541. */
  91542. if( okToChngToIN ){
  91543. Expr *pDup; /* A transient duplicate expression */
  91544. ExprList *pList = 0; /* The RHS of the IN operator */
  91545. Expr *pLeft = 0; /* The LHS of the IN operator */
  91546. Expr *pNew; /* The complete IN operator */
  91547. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  91548. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  91549. assert( pOrTerm->eOperator & WO_EQ );
  91550. assert( pOrTerm->leftCursor==iCursor );
  91551. assert( pOrTerm->u.leftColumn==iColumn );
  91552. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  91553. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  91554. pLeft = pOrTerm->pExpr->pLeft;
  91555. }
  91556. assert( pLeft!=0 );
  91557. pDup = sqlite3ExprDup(db, pLeft, 0);
  91558. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  91559. if( pNew ){
  91560. int idxNew;
  91561. transferJoinMarkings(pNew, pExpr);
  91562. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  91563. pNew->x.pList = pList;
  91564. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  91565. testcase( idxNew==0 );
  91566. exprAnalyze(pSrc, pWC, idxNew);
  91567. pTerm = &pWC->a[idxTerm];
  91568. pWC->a[idxNew].iParent = idxTerm;
  91569. pTerm->nChild = 1;
  91570. }else{
  91571. sqlite3ExprListDelete(db, pList);
  91572. }
  91573. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  91574. }
  91575. }
  91576. }
  91577. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  91578. /*
  91579. ** The input to this routine is an WhereTerm structure with only the
  91580. ** "pExpr" field filled in. The job of this routine is to analyze the
  91581. ** subexpression and populate all the other fields of the WhereTerm
  91582. ** structure.
  91583. **
  91584. ** If the expression is of the form "<expr> <op> X" it gets commuted
  91585. ** to the standard form of "X <op> <expr>".
  91586. **
  91587. ** If the expression is of the form "X <op> Y" where both X and Y are
  91588. ** columns, then the original expression is unchanged and a new virtual
  91589. ** term of the form "Y <op> X" is added to the WHERE clause and
  91590. ** analyzed separately. The original term is marked with TERM_COPIED
  91591. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  91592. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  91593. ** is a commuted copy of a prior term.) The original term has nChild=1
  91594. ** and the copy has idxParent set to the index of the original term.
  91595. */
  91596. static void exprAnalyze(
  91597. SrcList *pSrc, /* the FROM clause */
  91598. WhereClause *pWC, /* the WHERE clause */
  91599. int idxTerm /* Index of the term to be analyzed */
  91600. ){
  91601. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  91602. WhereTerm *pTerm; /* The term to be analyzed */
  91603. WhereMaskSet *pMaskSet; /* Set of table index masks */
  91604. Expr *pExpr; /* The expression to be analyzed */
  91605. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  91606. Bitmask prereqAll; /* Prerequesites of pExpr */
  91607. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  91608. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  91609. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  91610. int noCase = 0; /* LIKE/GLOB distinguishes case */
  91611. int op; /* Top-level operator. pExpr->op */
  91612. Parse *pParse = pWInfo->pParse; /* Parsing context */
  91613. sqlite3 *db = pParse->db; /* Database connection */
  91614. if( db->mallocFailed ){
  91615. return;
  91616. }
  91617. pTerm = &pWC->a[idxTerm];
  91618. pMaskSet = &pWInfo->sMaskSet;
  91619. pExpr = pTerm->pExpr;
  91620. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  91621. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  91622. op = pExpr->op;
  91623. if( op==TK_IN ){
  91624. assert( pExpr->pRight==0 );
  91625. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91626. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  91627. }else{
  91628. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  91629. }
  91630. }else if( op==TK_ISNULL ){
  91631. pTerm->prereqRight = 0;
  91632. }else{
  91633. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  91634. }
  91635. prereqAll = exprTableUsage(pMaskSet, pExpr);
  91636. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  91637. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  91638. prereqAll |= x;
  91639. extraRight = x-1; /* ON clause terms may not be used with an index
  91640. ** on left table of a LEFT JOIN. Ticket #3015 */
  91641. }
  91642. pTerm->prereqAll = prereqAll;
  91643. pTerm->leftCursor = -1;
  91644. pTerm->iParent = -1;
  91645. pTerm->eOperator = 0;
  91646. if( allowedOp(op) ){
  91647. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  91648. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  91649. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  91650. if( pLeft->op==TK_COLUMN ){
  91651. pTerm->leftCursor = pLeft->iTable;
  91652. pTerm->u.leftColumn = pLeft->iColumn;
  91653. pTerm->eOperator = operatorMask(op) & opMask;
  91654. }
  91655. if( pRight && pRight->op==TK_COLUMN ){
  91656. WhereTerm *pNew;
  91657. Expr *pDup;
  91658. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  91659. if( pTerm->leftCursor>=0 ){
  91660. int idxNew;
  91661. pDup = sqlite3ExprDup(db, pExpr, 0);
  91662. if( db->mallocFailed ){
  91663. sqlite3ExprDelete(db, pDup);
  91664. return;
  91665. }
  91666. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  91667. if( idxNew==0 ) return;
  91668. pNew = &pWC->a[idxNew];
  91669. pNew->iParent = idxTerm;
  91670. pTerm = &pWC->a[idxTerm];
  91671. pTerm->nChild = 1;
  91672. pTerm->wtFlags |= TERM_COPIED;
  91673. if( pExpr->op==TK_EQ
  91674. && !ExprHasProperty(pExpr, EP_FromJoin)
  91675. && OptimizationEnabled(db, SQLITE_Transitive)
  91676. ){
  91677. pTerm->eOperator |= WO_EQUIV;
  91678. eExtraOp = WO_EQUIV;
  91679. }
  91680. }else{
  91681. pDup = pExpr;
  91682. pNew = pTerm;
  91683. }
  91684. exprCommute(pParse, pDup);
  91685. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  91686. pNew->leftCursor = pLeft->iTable;
  91687. pNew->u.leftColumn = pLeft->iColumn;
  91688. testcase( (prereqLeft | extraRight) != prereqLeft );
  91689. pNew->prereqRight = prereqLeft | extraRight;
  91690. pNew->prereqAll = prereqAll;
  91691. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  91692. }
  91693. }
  91694. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  91695. /* If a term is the BETWEEN operator, create two new virtual terms
  91696. ** that define the range that the BETWEEN implements. For example:
  91697. **
  91698. ** a BETWEEN b AND c
  91699. **
  91700. ** is converted into:
  91701. **
  91702. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  91703. **
  91704. ** The two new terms are added onto the end of the WhereClause object.
  91705. ** The new terms are "dynamic" and are children of the original BETWEEN
  91706. ** term. That means that if the BETWEEN term is coded, the children are
  91707. ** skipped. Or, if the children are satisfied by an index, the original
  91708. ** BETWEEN term is skipped.
  91709. */
  91710. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  91711. ExprList *pList = pExpr->x.pList;
  91712. int i;
  91713. static const u8 ops[] = {TK_GE, TK_LE};
  91714. assert( pList!=0 );
  91715. assert( pList->nExpr==2 );
  91716. for(i=0; i<2; i++){
  91717. Expr *pNewExpr;
  91718. int idxNew;
  91719. pNewExpr = sqlite3PExpr(pParse, ops[i],
  91720. sqlite3ExprDup(db, pExpr->pLeft, 0),
  91721. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  91722. transferJoinMarkings(pNewExpr, pExpr);
  91723. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  91724. testcase( idxNew==0 );
  91725. exprAnalyze(pSrc, pWC, idxNew);
  91726. pTerm = &pWC->a[idxTerm];
  91727. pWC->a[idxNew].iParent = idxTerm;
  91728. }
  91729. pTerm->nChild = 2;
  91730. }
  91731. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  91732. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  91733. /* Analyze a term that is composed of two or more subterms connected by
  91734. ** an OR operator.
  91735. */
  91736. else if( pExpr->op==TK_OR ){
  91737. assert( pWC->op==TK_AND );
  91738. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  91739. pTerm = &pWC->a[idxTerm];
  91740. }
  91741. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  91742. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  91743. /* Add constraints to reduce the search space on a LIKE or GLOB
  91744. ** operator.
  91745. **
  91746. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  91747. **
  91748. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  91749. **
  91750. ** The last character of the prefix "abc" is incremented to form the
  91751. ** termination condition "abd".
  91752. */
  91753. if( pWC->op==TK_AND
  91754. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  91755. ){
  91756. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  91757. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  91758. Expr *pNewExpr1;
  91759. Expr *pNewExpr2;
  91760. int idxNew1;
  91761. int idxNew2;
  91762. Token sCollSeqName; /* Name of collating sequence */
  91763. pLeft = pExpr->x.pList->a[1].pExpr;
  91764. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  91765. if( !db->mallocFailed ){
  91766. u8 c, *pC; /* Last character before the first wildcard */
  91767. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  91768. c = *pC;
  91769. if( noCase ){
  91770. /* The point is to increment the last character before the first
  91771. ** wildcard. But if we increment '@', that will push it into the
  91772. ** alphabetic range where case conversions will mess up the
  91773. ** inequality. To avoid this, make sure to also run the full
  91774. ** LIKE on all candidate expressions by clearing the isComplete flag
  91775. */
  91776. if( c=='A'-1 ) isComplete = 0;
  91777. c = sqlite3UpperToLower[c];
  91778. }
  91779. *pC = c + 1;
  91780. }
  91781. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  91782. sCollSeqName.n = 6;
  91783. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  91784. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  91785. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  91786. pStr1, 0);
  91787. transferJoinMarkings(pNewExpr1, pExpr);
  91788. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  91789. testcase( idxNew1==0 );
  91790. exprAnalyze(pSrc, pWC, idxNew1);
  91791. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  91792. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  91793. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  91794. pStr2, 0);
  91795. transferJoinMarkings(pNewExpr2, pExpr);
  91796. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  91797. testcase( idxNew2==0 );
  91798. exprAnalyze(pSrc, pWC, idxNew2);
  91799. pTerm = &pWC->a[idxTerm];
  91800. if( isComplete ){
  91801. pWC->a[idxNew1].iParent = idxTerm;
  91802. pWC->a[idxNew2].iParent = idxTerm;
  91803. pTerm->nChild = 2;
  91804. }
  91805. }
  91806. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  91807. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91808. /* Add a WO_MATCH auxiliary term to the constraint set if the
  91809. ** current expression is of the form: column MATCH expr.
  91810. ** This information is used by the xBestIndex methods of
  91811. ** virtual tables. The native query optimizer does not attempt
  91812. ** to do anything with MATCH functions.
  91813. */
  91814. if( isMatchOfColumn(pExpr) ){
  91815. int idxNew;
  91816. Expr *pRight, *pLeft;
  91817. WhereTerm *pNewTerm;
  91818. Bitmask prereqColumn, prereqExpr;
  91819. pRight = pExpr->x.pList->a[0].pExpr;
  91820. pLeft = pExpr->x.pList->a[1].pExpr;
  91821. prereqExpr = exprTableUsage(pMaskSet, pRight);
  91822. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  91823. if( (prereqExpr & prereqColumn)==0 ){
  91824. Expr *pNewExpr;
  91825. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  91826. 0, sqlite3ExprDup(db, pRight, 0), 0);
  91827. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  91828. testcase( idxNew==0 );
  91829. pNewTerm = &pWC->a[idxNew];
  91830. pNewTerm->prereqRight = prereqExpr;
  91831. pNewTerm->leftCursor = pLeft->iTable;
  91832. pNewTerm->u.leftColumn = pLeft->iColumn;
  91833. pNewTerm->eOperator = WO_MATCH;
  91834. pNewTerm->iParent = idxTerm;
  91835. pTerm = &pWC->a[idxTerm];
  91836. pTerm->nChild = 1;
  91837. pTerm->wtFlags |= TERM_COPIED;
  91838. pNewTerm->prereqAll = pTerm->prereqAll;
  91839. }
  91840. }
  91841. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91842. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91843. /* When sqlite_stat3 histogram data is available an operator of the
  91844. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  91845. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  91846. ** virtual term of that form.
  91847. **
  91848. ** Note that the virtual term must be tagged with TERM_VNULL. This
  91849. ** TERM_VNULL tag will suppress the not-null check at the beginning
  91850. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  91851. ** the start of the loop will prevent any results from being returned.
  91852. */
  91853. if( pExpr->op==TK_NOTNULL
  91854. && pExpr->pLeft->op==TK_COLUMN
  91855. && pExpr->pLeft->iColumn>=0
  91856. && OptimizationEnabled(db, SQLITE_Stat3)
  91857. ){
  91858. Expr *pNewExpr;
  91859. Expr *pLeft = pExpr->pLeft;
  91860. int idxNew;
  91861. WhereTerm *pNewTerm;
  91862. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  91863. sqlite3ExprDup(db, pLeft, 0),
  91864. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  91865. idxNew = whereClauseInsert(pWC, pNewExpr,
  91866. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  91867. if( idxNew ){
  91868. pNewTerm = &pWC->a[idxNew];
  91869. pNewTerm->prereqRight = 0;
  91870. pNewTerm->leftCursor = pLeft->iTable;
  91871. pNewTerm->u.leftColumn = pLeft->iColumn;
  91872. pNewTerm->eOperator = WO_GT;
  91873. pNewTerm->iParent = idxTerm;
  91874. pTerm = &pWC->a[idxTerm];
  91875. pTerm->nChild = 1;
  91876. pTerm->wtFlags |= TERM_COPIED;
  91877. pNewTerm->prereqAll = pTerm->prereqAll;
  91878. }
  91879. }
  91880. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91881. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  91882. ** an index for tables to the left of the join.
  91883. */
  91884. pTerm->prereqRight |= extraRight;
  91885. }
  91886. /*
  91887. ** This function searches pList for a entry that matches the iCol-th column
  91888. ** of index pIdx.
  91889. **
  91890. ** If such an expression is found, its index in pList->a[] is returned. If
  91891. ** no expression is found, -1 is returned.
  91892. */
  91893. static int findIndexCol(
  91894. Parse *pParse, /* Parse context */
  91895. ExprList *pList, /* Expression list to search */
  91896. int iBase, /* Cursor for table associated with pIdx */
  91897. Index *pIdx, /* Index to match column of */
  91898. int iCol /* Column of index to match */
  91899. ){
  91900. int i;
  91901. const char *zColl = pIdx->azColl[iCol];
  91902. for(i=0; i<pList->nExpr; i++){
  91903. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  91904. if( p->op==TK_COLUMN
  91905. && p->iColumn==pIdx->aiColumn[iCol]
  91906. && p->iTable==iBase
  91907. ){
  91908. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  91909. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  91910. return i;
  91911. }
  91912. }
  91913. }
  91914. return -1;
  91915. }
  91916. /*
  91917. ** Return true if the DISTINCT expression-list passed as the third argument
  91918. ** is redundant.
  91919. **
  91920. ** A DISTINCT list is redundant if the database contains some subset of
  91921. ** columns that are unique and non-null.
  91922. */
  91923. static int isDistinctRedundant(
  91924. Parse *pParse, /* Parsing context */
  91925. SrcList *pTabList, /* The FROM clause */
  91926. WhereClause *pWC, /* The WHERE clause */
  91927. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  91928. ){
  91929. Table *pTab;
  91930. Index *pIdx;
  91931. int i;
  91932. int iBase;
  91933. /* If there is more than one table or sub-select in the FROM clause of
  91934. ** this query, then it will not be possible to show that the DISTINCT
  91935. ** clause is redundant. */
  91936. if( pTabList->nSrc!=1 ) return 0;
  91937. iBase = pTabList->a[0].iCursor;
  91938. pTab = pTabList->a[0].pTab;
  91939. /* If any of the expressions is an IPK column on table iBase, then return
  91940. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  91941. ** current SELECT is a correlated sub-query.
  91942. */
  91943. for(i=0; i<pDistinct->nExpr; i++){
  91944. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  91945. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  91946. }
  91947. /* Loop through all indices on the table, checking each to see if it makes
  91948. ** the DISTINCT qualifier redundant. It does so if:
  91949. **
  91950. ** 1. The index is itself UNIQUE, and
  91951. **
  91952. ** 2. All of the columns in the index are either part of the pDistinct
  91953. ** list, or else the WHERE clause contains a term of the form "col=X",
  91954. ** where X is a constant value. The collation sequences of the
  91955. ** comparison and select-list expressions must match those of the index.
  91956. **
  91957. ** 3. All of those index columns for which the WHERE clause does not
  91958. ** contain a "col=X" term are subject to a NOT NULL constraint.
  91959. */
  91960. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91961. if( pIdx->onError==OE_None ) continue;
  91962. for(i=0; i<pIdx->nColumn; i++){
  91963. int iCol = pIdx->aiColumn[i];
  91964. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  91965. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  91966. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  91967. break;
  91968. }
  91969. }
  91970. }
  91971. if( i==pIdx->nColumn ){
  91972. /* This index implies that the DISTINCT qualifier is redundant. */
  91973. return 1;
  91974. }
  91975. }
  91976. return 0;
  91977. }
  91978. /*
  91979. ** Estimate the logarithm of the input value to base 2.
  91980. */
  91981. static LogEst estLog(LogEst N){
  91982. LogEst x = sqlite3LogEst(N);
  91983. return x>33 ? x - 33 : 0;
  91984. }
  91985. /*
  91986. ** Two routines for printing the content of an sqlite3_index_info
  91987. ** structure. Used for testing and debugging only. If neither
  91988. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  91989. ** are no-ops.
  91990. */
  91991. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  91992. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  91993. int i;
  91994. if( !sqlite3WhereTrace ) return;
  91995. for(i=0; i<p->nConstraint; i++){
  91996. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  91997. i,
  91998. p->aConstraint[i].iColumn,
  91999. p->aConstraint[i].iTermOffset,
  92000. p->aConstraint[i].op,
  92001. p->aConstraint[i].usable);
  92002. }
  92003. for(i=0; i<p->nOrderBy; i++){
  92004. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  92005. i,
  92006. p->aOrderBy[i].iColumn,
  92007. p->aOrderBy[i].desc);
  92008. }
  92009. }
  92010. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  92011. int i;
  92012. if( !sqlite3WhereTrace ) return;
  92013. for(i=0; i<p->nConstraint; i++){
  92014. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  92015. i,
  92016. p->aConstraintUsage[i].argvIndex,
  92017. p->aConstraintUsage[i].omit);
  92018. }
  92019. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  92020. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  92021. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  92022. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  92023. }
  92024. #else
  92025. #define TRACE_IDX_INPUTS(A)
  92026. #define TRACE_IDX_OUTPUTS(A)
  92027. #endif
  92028. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92029. /*
  92030. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  92031. ** could be used with an index to access pSrc, assuming an appropriate
  92032. ** index existed.
  92033. */
  92034. static int termCanDriveIndex(
  92035. WhereTerm *pTerm, /* WHERE clause term to check */
  92036. struct SrcList_item *pSrc, /* Table we are trying to access */
  92037. Bitmask notReady /* Tables in outer loops of the join */
  92038. ){
  92039. char aff;
  92040. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  92041. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  92042. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  92043. if( pTerm->u.leftColumn<0 ) return 0;
  92044. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  92045. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  92046. return 1;
  92047. }
  92048. #endif
  92049. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92050. /*
  92051. ** Generate code to construct the Index object for an automatic index
  92052. ** and to set up the WhereLevel object pLevel so that the code generator
  92053. ** makes use of the automatic index.
  92054. */
  92055. static void constructAutomaticIndex(
  92056. Parse *pParse, /* The parsing context */
  92057. WhereClause *pWC, /* The WHERE clause */
  92058. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  92059. Bitmask notReady, /* Mask of cursors that are not available */
  92060. WhereLevel *pLevel /* Write new index here */
  92061. ){
  92062. int nColumn; /* Number of columns in the constructed index */
  92063. WhereTerm *pTerm; /* A single term of the WHERE clause */
  92064. WhereTerm *pWCEnd; /* End of pWC->a[] */
  92065. int nByte; /* Byte of memory needed for pIdx */
  92066. Index *pIdx; /* Object describing the transient index */
  92067. Vdbe *v; /* Prepared statement under construction */
  92068. int addrInit; /* Address of the initialization bypass jump */
  92069. Table *pTable; /* The table being indexed */
  92070. KeyInfo *pKeyinfo; /* Key information for the index */
  92071. int addrTop; /* Top of the index fill loop */
  92072. int regRecord; /* Register holding an index record */
  92073. int n; /* Column counter */
  92074. int i; /* Loop counter */
  92075. int mxBitCol; /* Maximum column in pSrc->colUsed */
  92076. CollSeq *pColl; /* Collating sequence to on a column */
  92077. WhereLoop *pLoop; /* The Loop object */
  92078. Bitmask idxCols; /* Bitmap of columns used for indexing */
  92079. Bitmask extraCols; /* Bitmap of additional columns */
  92080. u8 sentWarning = 0; /* True if a warnning has been issued */
  92081. /* Generate code to skip over the creation and initialization of the
  92082. ** transient index on 2nd and subsequent iterations of the loop. */
  92083. v = pParse->pVdbe;
  92084. assert( v!=0 );
  92085. addrInit = sqlite3CodeOnce(pParse);
  92086. /* Count the number of columns that will be added to the index
  92087. ** and used to match WHERE clause constraints */
  92088. nColumn = 0;
  92089. pTable = pSrc->pTab;
  92090. pWCEnd = &pWC->a[pWC->nTerm];
  92091. pLoop = pLevel->pWLoop;
  92092. idxCols = 0;
  92093. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92094. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92095. int iCol = pTerm->u.leftColumn;
  92096. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  92097. testcase( iCol==BMS );
  92098. testcase( iCol==BMS-1 );
  92099. if( !sentWarning ){
  92100. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  92101. "automatic index on %s(%s)", pTable->zName,
  92102. pTable->aCol[iCol].zName);
  92103. sentWarning = 1;
  92104. }
  92105. if( (idxCols & cMask)==0 ){
  92106. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  92107. pLoop->aLTerm[nColumn++] = pTerm;
  92108. idxCols |= cMask;
  92109. }
  92110. }
  92111. }
  92112. assert( nColumn>0 );
  92113. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  92114. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  92115. | WHERE_AUTO_INDEX;
  92116. /* Count the number of additional columns needed to create a
  92117. ** covering index. A "covering index" is an index that contains all
  92118. ** columns that are needed by the query. With a covering index, the
  92119. ** original table never needs to be accessed. Automatic indices must
  92120. ** be a covering index because the index will not be updated if the
  92121. ** original table changes and the index and table cannot both be used
  92122. ** if they go out of sync.
  92123. */
  92124. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  92125. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  92126. testcase( pTable->nCol==BMS-1 );
  92127. testcase( pTable->nCol==BMS-2 );
  92128. for(i=0; i<mxBitCol; i++){
  92129. if( extraCols & MASKBIT(i) ) nColumn++;
  92130. }
  92131. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  92132. nColumn += pTable->nCol - BMS + 1;
  92133. }
  92134. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  92135. /* Construct the Index object to describe this index */
  92136. nByte = sizeof(Index);
  92137. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  92138. nByte += nColumn*sizeof(char*); /* Index.azColl */
  92139. nByte += nColumn; /* Index.aSortOrder */
  92140. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  92141. if( pIdx==0 ) return;
  92142. pLoop->u.btree.pIndex = pIdx;
  92143. pIdx->azColl = (char**)&pIdx[1];
  92144. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  92145. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  92146. pIdx->zName = "auto-index";
  92147. pIdx->nColumn = nColumn;
  92148. pIdx->pTable = pTable;
  92149. n = 0;
  92150. idxCols = 0;
  92151. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92152. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92153. int iCol = pTerm->u.leftColumn;
  92154. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  92155. testcase( iCol==BMS-1 );
  92156. testcase( iCol==BMS );
  92157. if( (idxCols & cMask)==0 ){
  92158. Expr *pX = pTerm->pExpr;
  92159. idxCols |= cMask;
  92160. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  92161. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  92162. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  92163. n++;
  92164. }
  92165. }
  92166. }
  92167. assert( (u32)n==pLoop->u.btree.nEq );
  92168. /* Add additional columns needed to make the automatic index into
  92169. ** a covering index */
  92170. for(i=0; i<mxBitCol; i++){
  92171. if( extraCols & MASKBIT(i) ){
  92172. pIdx->aiColumn[n] = i;
  92173. pIdx->azColl[n] = "BINARY";
  92174. n++;
  92175. }
  92176. }
  92177. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  92178. for(i=BMS-1; i<pTable->nCol; i++){
  92179. pIdx->aiColumn[n] = i;
  92180. pIdx->azColl[n] = "BINARY";
  92181. n++;
  92182. }
  92183. }
  92184. assert( n==nColumn );
  92185. /* Create the automatic index */
  92186. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  92187. assert( pLevel->iIdxCur>=0 );
  92188. pLevel->iIdxCur = pParse->nTab++;
  92189. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  92190. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  92191. VdbeComment((v, "for %s", pTable->zName));
  92192. /* Fill the automatic index with content */
  92193. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  92194. regRecord = sqlite3GetTempReg(pParse);
  92195. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  92196. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  92197. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  92198. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  92199. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  92200. sqlite3VdbeJumpHere(v, addrTop);
  92201. sqlite3ReleaseTempReg(pParse, regRecord);
  92202. /* Jump here when skipping the initialization */
  92203. sqlite3VdbeJumpHere(v, addrInit);
  92204. }
  92205. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  92206. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92207. /*
  92208. ** Allocate and populate an sqlite3_index_info structure. It is the
  92209. ** responsibility of the caller to eventually release the structure
  92210. ** by passing the pointer returned by this function to sqlite3_free().
  92211. */
  92212. static sqlite3_index_info *allocateIndexInfo(
  92213. Parse *pParse,
  92214. WhereClause *pWC,
  92215. struct SrcList_item *pSrc,
  92216. ExprList *pOrderBy
  92217. ){
  92218. int i, j;
  92219. int nTerm;
  92220. struct sqlite3_index_constraint *pIdxCons;
  92221. struct sqlite3_index_orderby *pIdxOrderBy;
  92222. struct sqlite3_index_constraint_usage *pUsage;
  92223. WhereTerm *pTerm;
  92224. int nOrderBy;
  92225. sqlite3_index_info *pIdxInfo;
  92226. /* Count the number of possible WHERE clause constraints referring
  92227. ** to this virtual table */
  92228. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  92229. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  92230. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  92231. testcase( pTerm->eOperator & WO_IN );
  92232. testcase( pTerm->eOperator & WO_ISNULL );
  92233. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  92234. if( pTerm->wtFlags & TERM_VNULL ) continue;
  92235. nTerm++;
  92236. }
  92237. /* If the ORDER BY clause contains only columns in the current
  92238. ** virtual table then allocate space for the aOrderBy part of
  92239. ** the sqlite3_index_info structure.
  92240. */
  92241. nOrderBy = 0;
  92242. if( pOrderBy ){
  92243. int n = pOrderBy->nExpr;
  92244. for(i=0; i<n; i++){
  92245. Expr *pExpr = pOrderBy->a[i].pExpr;
  92246. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  92247. }
  92248. if( i==n){
  92249. nOrderBy = n;
  92250. }
  92251. }
  92252. /* Allocate the sqlite3_index_info structure
  92253. */
  92254. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  92255. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  92256. + sizeof(*pIdxOrderBy)*nOrderBy );
  92257. if( pIdxInfo==0 ){
  92258. sqlite3ErrorMsg(pParse, "out of memory");
  92259. return 0;
  92260. }
  92261. /* Initialize the structure. The sqlite3_index_info structure contains
  92262. ** many fields that are declared "const" to prevent xBestIndex from
  92263. ** changing them. We have to do some funky casting in order to
  92264. ** initialize those fields.
  92265. */
  92266. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  92267. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  92268. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  92269. *(int*)&pIdxInfo->nConstraint = nTerm;
  92270. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  92271. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  92272. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  92273. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  92274. pUsage;
  92275. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  92276. u8 op;
  92277. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  92278. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  92279. testcase( pTerm->eOperator & WO_IN );
  92280. testcase( pTerm->eOperator & WO_ISNULL );
  92281. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  92282. if( pTerm->wtFlags & TERM_VNULL ) continue;
  92283. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  92284. pIdxCons[j].iTermOffset = i;
  92285. op = (u8)pTerm->eOperator & WO_ALL;
  92286. if( op==WO_IN ) op = WO_EQ;
  92287. pIdxCons[j].op = op;
  92288. /* The direct assignment in the previous line is possible only because
  92289. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  92290. ** following asserts verify this fact. */
  92291. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  92292. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  92293. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  92294. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  92295. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  92296. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  92297. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  92298. j++;
  92299. }
  92300. for(i=0; i<nOrderBy; i++){
  92301. Expr *pExpr = pOrderBy->a[i].pExpr;
  92302. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  92303. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  92304. }
  92305. return pIdxInfo;
  92306. }
  92307. /*
  92308. ** The table object reference passed as the second argument to this function
  92309. ** must represent a virtual table. This function invokes the xBestIndex()
  92310. ** method of the virtual table with the sqlite3_index_info object that
  92311. ** comes in as the 3rd argument to this function.
  92312. **
  92313. ** If an error occurs, pParse is populated with an error message and a
  92314. ** non-zero value is returned. Otherwise, 0 is returned and the output
  92315. ** part of the sqlite3_index_info structure is left populated.
  92316. **
  92317. ** Whether or not an error is returned, it is the responsibility of the
  92318. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  92319. ** that this is required.
  92320. */
  92321. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  92322. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  92323. int i;
  92324. int rc;
  92325. TRACE_IDX_INPUTS(p);
  92326. rc = pVtab->pModule->xBestIndex(pVtab, p);
  92327. TRACE_IDX_OUTPUTS(p);
  92328. if( rc!=SQLITE_OK ){
  92329. if( rc==SQLITE_NOMEM ){
  92330. pParse->db->mallocFailed = 1;
  92331. }else if( !pVtab->zErrMsg ){
  92332. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  92333. }else{
  92334. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  92335. }
  92336. }
  92337. sqlite3_free(pVtab->zErrMsg);
  92338. pVtab->zErrMsg = 0;
  92339. for(i=0; i<p->nConstraint; i++){
  92340. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  92341. sqlite3ErrorMsg(pParse,
  92342. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  92343. }
  92344. }
  92345. return pParse->nErr;
  92346. }
  92347. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  92348. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92349. /*
  92350. ** Estimate the location of a particular key among all keys in an
  92351. ** index. Store the results in aStat as follows:
  92352. **
  92353. ** aStat[0] Est. number of rows less than pVal
  92354. ** aStat[1] Est. number of rows equal to pVal
  92355. **
  92356. ** Return SQLITE_OK on success.
  92357. */
  92358. static void whereKeyStats(
  92359. Parse *pParse, /* Database connection */
  92360. Index *pIdx, /* Index to consider domain of */
  92361. UnpackedRecord *pRec, /* Vector of values to consider */
  92362. int roundUp, /* Round up if true. Round down if false */
  92363. tRowcnt *aStat /* OUT: stats written here */
  92364. ){
  92365. IndexSample *aSample = pIdx->aSample;
  92366. int iCol; /* Index of required stats in anEq[] etc. */
  92367. int iMin = 0; /* Smallest sample not yet tested */
  92368. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  92369. int iTest; /* Next sample to test */
  92370. int res; /* Result of comparison operation */
  92371. #ifndef SQLITE_DEBUG
  92372. UNUSED_PARAMETER( pParse );
  92373. #endif
  92374. assert( pRec!=0 || pParse->db->mallocFailed );
  92375. if( pRec==0 ) return;
  92376. iCol = pRec->nField - 1;
  92377. assert( pIdx->nSample>0 );
  92378. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  92379. do{
  92380. iTest = (iMin+i)/2;
  92381. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  92382. if( res<0 ){
  92383. iMin = iTest+1;
  92384. }else{
  92385. i = iTest;
  92386. }
  92387. }while( res && iMin<i );
  92388. #ifdef SQLITE_DEBUG
  92389. /* The following assert statements check that the binary search code
  92390. ** above found the right answer. This block serves no purpose other
  92391. ** than to invoke the asserts. */
  92392. if( res==0 ){
  92393. /* If (res==0) is true, then sample $i must be equal to pRec */
  92394. assert( i<pIdx->nSample );
  92395. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  92396. || pParse->db->mallocFailed );
  92397. }else{
  92398. /* Otherwise, pRec must be smaller than sample $i and larger than
  92399. ** sample ($i-1). */
  92400. assert( i==pIdx->nSample
  92401. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  92402. || pParse->db->mallocFailed );
  92403. assert( i==0
  92404. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  92405. || pParse->db->mallocFailed );
  92406. }
  92407. #endif /* ifdef SQLITE_DEBUG */
  92408. /* At this point, aSample[i] is the first sample that is greater than
  92409. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  92410. ** than pVal. If aSample[i]==pVal, then res==0.
  92411. */
  92412. if( res==0 ){
  92413. aStat[0] = aSample[i].anLt[iCol];
  92414. aStat[1] = aSample[i].anEq[iCol];
  92415. }else{
  92416. tRowcnt iLower, iUpper, iGap;
  92417. if( i==0 ){
  92418. iLower = 0;
  92419. iUpper = aSample[0].anLt[iCol];
  92420. }else{
  92421. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  92422. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  92423. }
  92424. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  92425. if( iLower>=iUpper ){
  92426. iGap = 0;
  92427. }else{
  92428. iGap = iUpper - iLower;
  92429. }
  92430. if( roundUp ){
  92431. iGap = (iGap*2)/3;
  92432. }else{
  92433. iGap = iGap/3;
  92434. }
  92435. aStat[0] = iLower + iGap;
  92436. }
  92437. }
  92438. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92439. /*
  92440. ** This function is used to estimate the number of rows that will be visited
  92441. ** by scanning an index for a range of values. The range may have an upper
  92442. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  92443. ** and lower bounds are represented by pLower and pUpper respectively. For
  92444. ** example, assuming that index p is on t1(a):
  92445. **
  92446. ** ... FROM t1 WHERE a > ? AND a < ? ...
  92447. ** |_____| |_____|
  92448. ** | |
  92449. ** pLower pUpper
  92450. **
  92451. ** If either of the upper or lower bound is not present, then NULL is passed in
  92452. ** place of the corresponding WhereTerm.
  92453. **
  92454. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  92455. ** column subject to the range constraint. Or, equivalently, the number of
  92456. ** equality constraints optimized by the proposed index scan. For example,
  92457. ** assuming index p is on t1(a, b), and the SQL query is:
  92458. **
  92459. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  92460. **
  92461. ** then nEq is set to 1 (as the range restricted column, b, is the second
  92462. ** left-most column of the index). Or, if the query is:
  92463. **
  92464. ** ... FROM t1 WHERE a > ? AND a < ? ...
  92465. **
  92466. ** then nEq is set to 0.
  92467. **
  92468. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  92469. ** number of rows that the index scan is expected to visit without
  92470. ** considering the range constraints. If nEq is 0, this is the number of
  92471. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  92472. ** to account for the range contraints pLower and pUpper.
  92473. **
  92474. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  92475. ** used, each range inequality reduces the search space by a factor of 4.
  92476. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  92477. ** rows visited by a factor of 16.
  92478. */
  92479. static int whereRangeScanEst(
  92480. Parse *pParse, /* Parsing & code generating context */
  92481. WhereLoopBuilder *pBuilder,
  92482. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  92483. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  92484. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  92485. ){
  92486. int rc = SQLITE_OK;
  92487. int nOut = pLoop->nOut;
  92488. LogEst nNew;
  92489. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92490. Index *p = pLoop->u.btree.pIndex;
  92491. int nEq = pLoop->u.btree.nEq;
  92492. if( p->nSample>0
  92493. && nEq==pBuilder->nRecValid
  92494. && nEq<p->nSampleCol
  92495. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  92496. ){
  92497. UnpackedRecord *pRec = pBuilder->pRec;
  92498. tRowcnt a[2];
  92499. u8 aff;
  92500. /* Variable iLower will be set to the estimate of the number of rows in
  92501. ** the index that are less than the lower bound of the range query. The
  92502. ** lower bound being the concatenation of $P and $L, where $P is the
  92503. ** key-prefix formed by the nEq values matched against the nEq left-most
  92504. ** columns of the index, and $L is the value in pLower.
  92505. **
  92506. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  92507. ** is not a simple variable or literal value), the lower bound of the
  92508. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  92509. ** if $L is available, whereKeyStats() is called for both ($P) and
  92510. ** ($P:$L) and the larger of the two returned values used.
  92511. **
  92512. ** Similarly, iUpper is to be set to the estimate of the number of rows
  92513. ** less than the upper bound of the range query. Where the upper bound
  92514. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  92515. ** of iUpper are requested of whereKeyStats() and the smaller used.
  92516. */
  92517. tRowcnt iLower;
  92518. tRowcnt iUpper;
  92519. if( nEq==p->nColumn ){
  92520. aff = SQLITE_AFF_INTEGER;
  92521. }else{
  92522. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  92523. }
  92524. /* Determine iLower and iUpper using ($P) only. */
  92525. if( nEq==0 ){
  92526. iLower = 0;
  92527. iUpper = p->aiRowEst[0];
  92528. }else{
  92529. /* Note: this call could be optimized away - since the same values must
  92530. ** have been requested when testing key $P in whereEqualScanEst(). */
  92531. whereKeyStats(pParse, p, pRec, 0, a);
  92532. iLower = a[0];
  92533. iUpper = a[0] + a[1];
  92534. }
  92535. /* If possible, improve on the iLower estimate using ($P:$L). */
  92536. if( pLower ){
  92537. int bOk; /* True if value is extracted from pExpr */
  92538. Expr *pExpr = pLower->pExpr->pRight;
  92539. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  92540. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  92541. if( rc==SQLITE_OK && bOk ){
  92542. tRowcnt iNew;
  92543. whereKeyStats(pParse, p, pRec, 0, a);
  92544. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  92545. if( iNew>iLower ) iLower = iNew;
  92546. nOut--;
  92547. }
  92548. }
  92549. /* If possible, improve on the iUpper estimate using ($P:$U). */
  92550. if( pUpper ){
  92551. int bOk; /* True if value is extracted from pExpr */
  92552. Expr *pExpr = pUpper->pExpr->pRight;
  92553. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  92554. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  92555. if( rc==SQLITE_OK && bOk ){
  92556. tRowcnt iNew;
  92557. whereKeyStats(pParse, p, pRec, 1, a);
  92558. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  92559. if( iNew<iUpper ) iUpper = iNew;
  92560. nOut--;
  92561. }
  92562. }
  92563. pBuilder->pRec = pRec;
  92564. if( rc==SQLITE_OK ){
  92565. if( iUpper>iLower ){
  92566. nNew = sqlite3LogEst(iUpper - iLower);
  92567. }else{
  92568. nNew = 10; assert( 10==sqlite3LogEst(2) );
  92569. }
  92570. if( nNew<nOut ){
  92571. nOut = nNew;
  92572. }
  92573. pLoop->nOut = (LogEst)nOut;
  92574. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  92575. (u32)iLower, (u32)iUpper, nOut));
  92576. return SQLITE_OK;
  92577. }
  92578. }
  92579. #else
  92580. UNUSED_PARAMETER(pParse);
  92581. UNUSED_PARAMETER(pBuilder);
  92582. #endif
  92583. assert( pLower || pUpper );
  92584. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  92585. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  92586. nNew = nOut;
  92587. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  92588. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  92589. nOut--;
  92590. }
  92591. if( pUpper ){
  92592. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  92593. nOut--;
  92594. }
  92595. if( nNew<10 ) nNew = 10;
  92596. if( nNew<nOut ) nOut = nNew;
  92597. pLoop->nOut = (LogEst)nOut;
  92598. return rc;
  92599. }
  92600. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92601. /*
  92602. ** Estimate the number of rows that will be returned based on
  92603. ** an equality constraint x=VALUE and where that VALUE occurs in
  92604. ** the histogram data. This only works when x is the left-most
  92605. ** column of an index and sqlite_stat3 histogram data is available
  92606. ** for that index. When pExpr==NULL that means the constraint is
  92607. ** "x IS NULL" instead of "x=VALUE".
  92608. **
  92609. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  92610. ** If unable to make an estimate, leave *pnRow unchanged and return
  92611. ** non-zero.
  92612. **
  92613. ** This routine can fail if it is unable to load a collating sequence
  92614. ** required for string comparison, or if unable to allocate memory
  92615. ** for a UTF conversion required for comparison. The error is stored
  92616. ** in the pParse structure.
  92617. */
  92618. static int whereEqualScanEst(
  92619. Parse *pParse, /* Parsing & code generating context */
  92620. WhereLoopBuilder *pBuilder,
  92621. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  92622. tRowcnt *pnRow /* Write the revised row estimate here */
  92623. ){
  92624. Index *p = pBuilder->pNew->u.btree.pIndex;
  92625. int nEq = pBuilder->pNew->u.btree.nEq;
  92626. UnpackedRecord *pRec = pBuilder->pRec;
  92627. u8 aff; /* Column affinity */
  92628. int rc; /* Subfunction return code */
  92629. tRowcnt a[2]; /* Statistics */
  92630. int bOk;
  92631. assert( nEq>=1 );
  92632. assert( nEq<=(p->nColumn+1) );
  92633. assert( p->aSample!=0 );
  92634. assert( p->nSample>0 );
  92635. assert( pBuilder->nRecValid<nEq );
  92636. /* If values are not available for all fields of the index to the left
  92637. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  92638. if( pBuilder->nRecValid<(nEq-1) ){
  92639. return SQLITE_NOTFOUND;
  92640. }
  92641. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  92642. ** below would return the same value. */
  92643. if( nEq>p->nColumn ){
  92644. *pnRow = 1;
  92645. return SQLITE_OK;
  92646. }
  92647. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  92648. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  92649. pBuilder->pRec = pRec;
  92650. if( rc!=SQLITE_OK ) return rc;
  92651. if( bOk==0 ) return SQLITE_NOTFOUND;
  92652. pBuilder->nRecValid = nEq;
  92653. whereKeyStats(pParse, p, pRec, 0, a);
  92654. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  92655. *pnRow = a[1];
  92656. return rc;
  92657. }
  92658. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92659. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92660. /*
  92661. ** Estimate the number of rows that will be returned based on
  92662. ** an IN constraint where the right-hand side of the IN operator
  92663. ** is a list of values. Example:
  92664. **
  92665. ** WHERE x IN (1,2,3,4)
  92666. **
  92667. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  92668. ** If unable to make an estimate, leave *pnRow unchanged and return
  92669. ** non-zero.
  92670. **
  92671. ** This routine can fail if it is unable to load a collating sequence
  92672. ** required for string comparison, or if unable to allocate memory
  92673. ** for a UTF conversion required for comparison. The error is stored
  92674. ** in the pParse structure.
  92675. */
  92676. static int whereInScanEst(
  92677. Parse *pParse, /* Parsing & code generating context */
  92678. WhereLoopBuilder *pBuilder,
  92679. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  92680. tRowcnt *pnRow /* Write the revised row estimate here */
  92681. ){
  92682. Index *p = pBuilder->pNew->u.btree.pIndex;
  92683. int nRecValid = pBuilder->nRecValid;
  92684. int rc = SQLITE_OK; /* Subfunction return code */
  92685. tRowcnt nEst; /* Number of rows for a single term */
  92686. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  92687. int i; /* Loop counter */
  92688. assert( p->aSample!=0 );
  92689. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  92690. nEst = p->aiRowEst[0];
  92691. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  92692. nRowEst += nEst;
  92693. pBuilder->nRecValid = nRecValid;
  92694. }
  92695. if( rc==SQLITE_OK ){
  92696. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  92697. *pnRow = nRowEst;
  92698. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  92699. }
  92700. assert( pBuilder->nRecValid==nRecValid );
  92701. return rc;
  92702. }
  92703. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92704. /*
  92705. ** Disable a term in the WHERE clause. Except, do not disable the term
  92706. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  92707. ** or USING clause of that join.
  92708. **
  92709. ** Consider the term t2.z='ok' in the following queries:
  92710. **
  92711. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  92712. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  92713. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  92714. **
  92715. ** The t2.z='ok' is disabled in the in (2) because it originates
  92716. ** in the ON clause. The term is disabled in (3) because it is not part
  92717. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  92718. **
  92719. ** Disabling a term causes that term to not be tested in the inner loop
  92720. ** of the join. Disabling is an optimization. When terms are satisfied
  92721. ** by indices, we disable them to prevent redundant tests in the inner
  92722. ** loop. We would get the correct results if nothing were ever disabled,
  92723. ** but joins might run a little slower. The trick is to disable as much
  92724. ** as we can without disabling too much. If we disabled in (1), we'd get
  92725. ** the wrong answer. See ticket #813.
  92726. */
  92727. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  92728. if( pTerm
  92729. && (pTerm->wtFlags & TERM_CODED)==0
  92730. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  92731. && (pLevel->notReady & pTerm->prereqAll)==0
  92732. ){
  92733. pTerm->wtFlags |= TERM_CODED;
  92734. if( pTerm->iParent>=0 ){
  92735. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  92736. if( (--pOther->nChild)==0 ){
  92737. disableTerm(pLevel, pOther);
  92738. }
  92739. }
  92740. }
  92741. }
  92742. /*
  92743. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  92744. ** to the n registers starting at base.
  92745. **
  92746. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  92747. ** beginning and end of zAff are ignored. If all entries in zAff are
  92748. ** SQLITE_AFF_NONE, then no code gets generated.
  92749. **
  92750. ** This routine makes its own copy of zAff so that the caller is free
  92751. ** to modify zAff after this routine returns.
  92752. */
  92753. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  92754. Vdbe *v = pParse->pVdbe;
  92755. if( zAff==0 ){
  92756. assert( pParse->db->mallocFailed );
  92757. return;
  92758. }
  92759. assert( v!=0 );
  92760. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  92761. ** and end of the affinity string.
  92762. */
  92763. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  92764. n--;
  92765. base++;
  92766. zAff++;
  92767. }
  92768. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  92769. n--;
  92770. }
  92771. /* Code the OP_Affinity opcode if there is anything left to do. */
  92772. if( n>0 ){
  92773. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  92774. sqlite3VdbeChangeP4(v, -1, zAff, n);
  92775. sqlite3ExprCacheAffinityChange(pParse, base, n);
  92776. }
  92777. }
  92778. /*
  92779. ** Generate code for a single equality term of the WHERE clause. An equality
  92780. ** term can be either X=expr or X IN (...). pTerm is the term to be
  92781. ** coded.
  92782. **
  92783. ** The current value for the constraint is left in register iReg.
  92784. **
  92785. ** For a constraint of the form X=expr, the expression is evaluated and its
  92786. ** result is left on the stack. For constraints of the form X IN (...)
  92787. ** this routine sets up a loop that will iterate over all values of X.
  92788. */
  92789. static int codeEqualityTerm(
  92790. Parse *pParse, /* The parsing context */
  92791. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  92792. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  92793. int iEq, /* Index of the equality term within this level */
  92794. int bRev, /* True for reverse-order IN operations */
  92795. int iTarget /* Attempt to leave results in this register */
  92796. ){
  92797. Expr *pX = pTerm->pExpr;
  92798. Vdbe *v = pParse->pVdbe;
  92799. int iReg; /* Register holding results */
  92800. assert( iTarget>0 );
  92801. if( pX->op==TK_EQ ){
  92802. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  92803. }else if( pX->op==TK_ISNULL ){
  92804. iReg = iTarget;
  92805. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  92806. #ifndef SQLITE_OMIT_SUBQUERY
  92807. }else{
  92808. int eType;
  92809. int iTab;
  92810. struct InLoop *pIn;
  92811. WhereLoop *pLoop = pLevel->pWLoop;
  92812. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  92813. && pLoop->u.btree.pIndex!=0
  92814. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  92815. ){
  92816. testcase( iEq==0 );
  92817. testcase( bRev );
  92818. bRev = !bRev;
  92819. }
  92820. assert( pX->op==TK_IN );
  92821. iReg = iTarget;
  92822. eType = sqlite3FindInIndex(pParse, pX, 0);
  92823. if( eType==IN_INDEX_INDEX_DESC ){
  92824. testcase( bRev );
  92825. bRev = !bRev;
  92826. }
  92827. iTab = pX->iTable;
  92828. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  92829. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  92830. pLoop->wsFlags |= WHERE_IN_ABLE;
  92831. if( pLevel->u.in.nIn==0 ){
  92832. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  92833. }
  92834. pLevel->u.in.nIn++;
  92835. pLevel->u.in.aInLoop =
  92836. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  92837. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  92838. pIn = pLevel->u.in.aInLoop;
  92839. if( pIn ){
  92840. pIn += pLevel->u.in.nIn - 1;
  92841. pIn->iCur = iTab;
  92842. if( eType==IN_INDEX_ROWID ){
  92843. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  92844. }else{
  92845. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  92846. }
  92847. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  92848. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  92849. }else{
  92850. pLevel->u.in.nIn = 0;
  92851. }
  92852. #endif
  92853. }
  92854. disableTerm(pLevel, pTerm);
  92855. return iReg;
  92856. }
  92857. /*
  92858. ** Generate code that will evaluate all == and IN constraints for an
  92859. ** index.
  92860. **
  92861. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  92862. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  92863. ** The index has as many as three equality constraints, but in this
  92864. ** example, the third "c" value is an inequality. So only two
  92865. ** constraints are coded. This routine will generate code to evaluate
  92866. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  92867. ** in consecutive registers and the index of the first register is returned.
  92868. **
  92869. ** In the example above nEq==2. But this subroutine works for any value
  92870. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  92871. ** The only thing it does is allocate the pLevel->iMem memory cell and
  92872. ** compute the affinity string.
  92873. **
  92874. ** This routine always allocates at least one memory cell and returns
  92875. ** the index of that memory cell. The code that
  92876. ** calls this routine will use that memory cell to store the termination
  92877. ** key value of the loop. If one or more IN operators appear, then
  92878. ** this routine allocates an additional nEq memory cells for internal
  92879. ** use.
  92880. **
  92881. ** Before returning, *pzAff is set to point to a buffer containing a
  92882. ** copy of the column affinity string of the index allocated using
  92883. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  92884. ** with equality constraints that use NONE affinity are set to
  92885. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  92886. **
  92887. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  92888. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  92889. **
  92890. ** In the example above, the index on t1(a) has TEXT affinity. But since
  92891. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  92892. ** no conversion should be attempted before using a t2.b value as part of
  92893. ** a key to search the index. Hence the first byte in the returned affinity
  92894. ** string in this example would be set to SQLITE_AFF_NONE.
  92895. */
  92896. static int codeAllEqualityTerms(
  92897. Parse *pParse, /* Parsing context */
  92898. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  92899. int bRev, /* Reverse the order of IN operators */
  92900. int nExtraReg, /* Number of extra registers to allocate */
  92901. char **pzAff /* OUT: Set to point to affinity string */
  92902. ){
  92903. int nEq; /* The number of == or IN constraints to code */
  92904. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  92905. Index *pIdx; /* The index being used for this loop */
  92906. WhereTerm *pTerm; /* A single constraint term */
  92907. WhereLoop *pLoop; /* The WhereLoop object */
  92908. int j; /* Loop counter */
  92909. int regBase; /* Base register */
  92910. int nReg; /* Number of registers to allocate */
  92911. char *zAff; /* Affinity string to return */
  92912. /* This module is only called on query plans that use an index. */
  92913. pLoop = pLevel->pWLoop;
  92914. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  92915. nEq = pLoop->u.btree.nEq;
  92916. pIdx = pLoop->u.btree.pIndex;
  92917. assert( pIdx!=0 );
  92918. /* Figure out how many memory cells we will need then allocate them.
  92919. */
  92920. regBase = pParse->nMem + 1;
  92921. nReg = pLoop->u.btree.nEq + nExtraReg;
  92922. pParse->nMem += nReg;
  92923. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  92924. if( !zAff ){
  92925. pParse->db->mallocFailed = 1;
  92926. }
  92927. /* Evaluate the equality constraints
  92928. */
  92929. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  92930. for(j=0; j<nEq; j++){
  92931. int r1;
  92932. pTerm = pLoop->aLTerm[j];
  92933. assert( pTerm!=0 );
  92934. /* The following true for indices with redundant columns.
  92935. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  92936. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  92937. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  92938. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  92939. if( r1!=regBase+j ){
  92940. if( nReg==1 ){
  92941. sqlite3ReleaseTempReg(pParse, regBase);
  92942. regBase = r1;
  92943. }else{
  92944. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  92945. }
  92946. }
  92947. testcase( pTerm->eOperator & WO_ISNULL );
  92948. testcase( pTerm->eOperator & WO_IN );
  92949. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  92950. Expr *pRight = pTerm->pExpr->pRight;
  92951. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  92952. if( zAff ){
  92953. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  92954. zAff[j] = SQLITE_AFF_NONE;
  92955. }
  92956. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  92957. zAff[j] = SQLITE_AFF_NONE;
  92958. }
  92959. }
  92960. }
  92961. }
  92962. *pzAff = zAff;
  92963. return regBase;
  92964. }
  92965. #ifndef SQLITE_OMIT_EXPLAIN
  92966. /*
  92967. ** This routine is a helper for explainIndexRange() below
  92968. **
  92969. ** pStr holds the text of an expression that we are building up one term
  92970. ** at a time. This routine adds a new term to the end of the expression.
  92971. ** Terms are separated by AND so add the "AND" text for second and subsequent
  92972. ** terms only.
  92973. */
  92974. static void explainAppendTerm(
  92975. StrAccum *pStr, /* The text expression being built */
  92976. int iTerm, /* Index of this term. First is zero */
  92977. const char *zColumn, /* Name of the column */
  92978. const char *zOp /* Name of the operator */
  92979. ){
  92980. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  92981. sqlite3StrAccumAppend(pStr, zColumn, -1);
  92982. sqlite3StrAccumAppend(pStr, zOp, 1);
  92983. sqlite3StrAccumAppend(pStr, "?", 1);
  92984. }
  92985. /*
  92986. ** Argument pLevel describes a strategy for scanning table pTab. This
  92987. ** function returns a pointer to a string buffer containing a description
  92988. ** of the subset of table rows scanned by the strategy in the form of an
  92989. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  92990. **
  92991. ** For example, if the query:
  92992. **
  92993. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  92994. **
  92995. ** is run and there is an index on (a, b), then this function returns a
  92996. ** string similar to:
  92997. **
  92998. ** "a=? AND b>?"
  92999. **
  93000. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  93001. ** It is the responsibility of the caller to free the buffer when it is
  93002. ** no longer required.
  93003. */
  93004. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  93005. Index *pIndex = pLoop->u.btree.pIndex;
  93006. int nEq = pLoop->u.btree.nEq;
  93007. int i, j;
  93008. Column *aCol = pTab->aCol;
  93009. int *aiColumn = pIndex->aiColumn;
  93010. StrAccum txt;
  93011. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  93012. return 0;
  93013. }
  93014. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  93015. txt.db = db;
  93016. sqlite3StrAccumAppend(&txt, " (", 2);
  93017. for(i=0; i<nEq; i++){
  93018. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  93019. explainAppendTerm(&txt, i, z, "=");
  93020. }
  93021. j = i;
  93022. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  93023. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  93024. explainAppendTerm(&txt, i++, z, ">");
  93025. }
  93026. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  93027. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  93028. explainAppendTerm(&txt, i, z, "<");
  93029. }
  93030. sqlite3StrAccumAppend(&txt, ")", 1);
  93031. return sqlite3StrAccumFinish(&txt);
  93032. }
  93033. /*
  93034. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  93035. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  93036. ** record is added to the output to describe the table scan strategy in
  93037. ** pLevel.
  93038. */
  93039. static void explainOneScan(
  93040. Parse *pParse, /* Parse context */
  93041. SrcList *pTabList, /* Table list this loop refers to */
  93042. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  93043. int iLevel, /* Value for "level" column of output */
  93044. int iFrom, /* Value for "from" column of output */
  93045. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  93046. ){
  93047. if( pParse->explain==2 ){
  93048. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  93049. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  93050. sqlite3 *db = pParse->db; /* Database handle */
  93051. char *zMsg; /* Text to add to EQP output */
  93052. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  93053. int isSearch; /* True for a SEARCH. False for SCAN. */
  93054. WhereLoop *pLoop; /* The controlling WhereLoop object */
  93055. u32 flags; /* Flags that describe this loop */
  93056. pLoop = pLevel->pWLoop;
  93057. flags = pLoop->wsFlags;
  93058. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  93059. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  93060. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  93061. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  93062. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  93063. if( pItem->pSelect ){
  93064. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  93065. }else{
  93066. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  93067. }
  93068. if( pItem->zAlias ){
  93069. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  93070. }
  93071. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  93072. && ALWAYS(pLoop->u.btree.pIndex!=0)
  93073. ){
  93074. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  93075. zMsg = sqlite3MAppendf(db, zMsg,
  93076. ((flags & WHERE_AUTO_INDEX) ?
  93077. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  93078. "%s USING %sINDEX %s%s"),
  93079. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  93080. pLoop->u.btree.pIndex->zName, zWhere);
  93081. sqlite3DbFree(db, zWhere);
  93082. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  93083. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  93084. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  93085. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  93086. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  93087. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  93088. }else if( flags&WHERE_BTM_LIMIT ){
  93089. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  93090. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  93091. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  93092. }
  93093. }
  93094. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93095. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  93096. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  93097. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  93098. }
  93099. #endif
  93100. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  93101. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  93102. }
  93103. }
  93104. #else
  93105. # define explainOneScan(u,v,w,x,y,z)
  93106. #endif /* SQLITE_OMIT_EXPLAIN */
  93107. /*
  93108. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  93109. ** implementation described by pWInfo.
  93110. */
  93111. static Bitmask codeOneLoopStart(
  93112. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  93113. int iLevel, /* Which level of pWInfo->a[] should be coded */
  93114. Bitmask notReady /* Which tables are currently available */
  93115. ){
  93116. int j, k; /* Loop counters */
  93117. int iCur; /* The VDBE cursor for the table */
  93118. int addrNxt; /* Where to jump to continue with the next IN case */
  93119. int omitTable; /* True if we use the index only */
  93120. int bRev; /* True if we need to scan in reverse order */
  93121. WhereLevel *pLevel; /* The where level to be coded */
  93122. WhereLoop *pLoop; /* The WhereLoop object being coded */
  93123. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  93124. WhereTerm *pTerm; /* A WHERE clause term */
  93125. Parse *pParse; /* Parsing context */
  93126. sqlite3 *db; /* Database connection */
  93127. Vdbe *v; /* The prepared stmt under constructions */
  93128. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  93129. int addrBrk; /* Jump here to break out of the loop */
  93130. int addrCont; /* Jump here to continue with next cycle */
  93131. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  93132. int iReleaseReg = 0; /* Temp register to free before returning */
  93133. pParse = pWInfo->pParse;
  93134. v = pParse->pVdbe;
  93135. pWC = &pWInfo->sWC;
  93136. db = pParse->db;
  93137. pLevel = &pWInfo->a[iLevel];
  93138. pLoop = pLevel->pWLoop;
  93139. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  93140. iCur = pTabItem->iCursor;
  93141. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  93142. bRev = (pWInfo->revMask>>iLevel)&1;
  93143. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  93144. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  93145. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  93146. /* Create labels for the "break" and "continue" instructions
  93147. ** for the current loop. Jump to addrBrk to break out of a loop.
  93148. ** Jump to cont to go immediately to the next iteration of the
  93149. ** loop.
  93150. **
  93151. ** When there is an IN operator, we also have a "addrNxt" label that
  93152. ** means to continue with the next IN value combination. When
  93153. ** there are no IN operators in the constraints, the "addrNxt" label
  93154. ** is the same as "addrBrk".
  93155. */
  93156. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  93157. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  93158. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  93159. ** initialize a memory cell that records if this table matches any
  93160. ** row of the left table of the join.
  93161. */
  93162. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  93163. pLevel->iLeftJoin = ++pParse->nMem;
  93164. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  93165. VdbeComment((v, "init LEFT JOIN no-match flag"));
  93166. }
  93167. /* Special case of a FROM clause subquery implemented as a co-routine */
  93168. if( pTabItem->viaCoroutine ){
  93169. int regYield = pTabItem->regReturn;
  93170. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  93171. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  93172. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  93173. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  93174. pLevel->op = OP_Goto;
  93175. }else
  93176. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93177. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  93178. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  93179. ** to access the data.
  93180. */
  93181. int iReg; /* P3 Value for OP_VFilter */
  93182. int addrNotFound;
  93183. int nConstraint = pLoop->nLTerm;
  93184. sqlite3ExprCachePush(pParse);
  93185. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  93186. addrNotFound = pLevel->addrBrk;
  93187. for(j=0; j<nConstraint; j++){
  93188. int iTarget = iReg+j+2;
  93189. pTerm = pLoop->aLTerm[j];
  93190. if( pTerm==0 ) continue;
  93191. if( pTerm->eOperator & WO_IN ){
  93192. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  93193. addrNotFound = pLevel->addrNxt;
  93194. }else{
  93195. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  93196. }
  93197. }
  93198. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  93199. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  93200. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  93201. pLoop->u.vtab.idxStr,
  93202. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  93203. pLoop->u.vtab.needFree = 0;
  93204. for(j=0; j<nConstraint && j<16; j++){
  93205. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  93206. disableTerm(pLevel, pLoop->aLTerm[j]);
  93207. }
  93208. }
  93209. pLevel->op = OP_VNext;
  93210. pLevel->p1 = iCur;
  93211. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  93212. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  93213. sqlite3ExprCachePop(pParse, 1);
  93214. }else
  93215. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  93216. if( (pLoop->wsFlags & WHERE_IPK)!=0
  93217. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  93218. ){
  93219. /* Case 2: We can directly reference a single row using an
  93220. ** equality comparison against the ROWID field. Or
  93221. ** we reference multiple rows using a "rowid IN (...)"
  93222. ** construct.
  93223. */
  93224. assert( pLoop->u.btree.nEq==1 );
  93225. iReleaseReg = sqlite3GetTempReg(pParse);
  93226. pTerm = pLoop->aLTerm[0];
  93227. assert( pTerm!=0 );
  93228. assert( pTerm->pExpr!=0 );
  93229. assert( omitTable==0 );
  93230. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93231. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  93232. addrNxt = pLevel->addrNxt;
  93233. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  93234. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  93235. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  93236. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93237. VdbeComment((v, "pk"));
  93238. pLevel->op = OP_Noop;
  93239. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  93240. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  93241. ){
  93242. /* Case 3: We have an inequality comparison against the ROWID field.
  93243. */
  93244. int testOp = OP_Noop;
  93245. int start;
  93246. int memEndValue = 0;
  93247. WhereTerm *pStart, *pEnd;
  93248. assert( omitTable==0 );
  93249. j = 0;
  93250. pStart = pEnd = 0;
  93251. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  93252. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  93253. assert( pStart!=0 || pEnd!=0 );
  93254. if( bRev ){
  93255. pTerm = pStart;
  93256. pStart = pEnd;
  93257. pEnd = pTerm;
  93258. }
  93259. if( pStart ){
  93260. Expr *pX; /* The expression that defines the start bound */
  93261. int r1, rTemp; /* Registers for holding the start boundary */
  93262. /* The following constant maps TK_xx codes into corresponding
  93263. ** seek opcodes. It depends on a particular ordering of TK_xx
  93264. */
  93265. const u8 aMoveOp[] = {
  93266. /* TK_GT */ OP_SeekGt,
  93267. /* TK_LE */ OP_SeekLe,
  93268. /* TK_LT */ OP_SeekLt,
  93269. /* TK_GE */ OP_SeekGe
  93270. };
  93271. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  93272. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  93273. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  93274. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  93275. testcase( pStart->wtFlags & TERM_VIRTUAL );
  93276. pX = pStart->pExpr;
  93277. assert( pX!=0 );
  93278. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  93279. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  93280. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  93281. VdbeComment((v, "pk"));
  93282. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  93283. sqlite3ReleaseTempReg(pParse, rTemp);
  93284. disableTerm(pLevel, pStart);
  93285. }else{
  93286. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  93287. }
  93288. if( pEnd ){
  93289. Expr *pX;
  93290. pX = pEnd->pExpr;
  93291. assert( pX!=0 );
  93292. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  93293. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  93294. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  93295. memEndValue = ++pParse->nMem;
  93296. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  93297. if( pX->op==TK_LT || pX->op==TK_GT ){
  93298. testOp = bRev ? OP_Le : OP_Ge;
  93299. }else{
  93300. testOp = bRev ? OP_Lt : OP_Gt;
  93301. }
  93302. disableTerm(pLevel, pEnd);
  93303. }
  93304. start = sqlite3VdbeCurrentAddr(v);
  93305. pLevel->op = bRev ? OP_Prev : OP_Next;
  93306. pLevel->p1 = iCur;
  93307. pLevel->p2 = start;
  93308. assert( pLevel->p5==0 );
  93309. if( testOp!=OP_Noop ){
  93310. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  93311. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  93312. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93313. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  93314. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  93315. }
  93316. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  93317. /* Case 4: A scan using an index.
  93318. **
  93319. ** The WHERE clause may contain zero or more equality
  93320. ** terms ("==" or "IN" operators) that refer to the N
  93321. ** left-most columns of the index. It may also contain
  93322. ** inequality constraints (>, <, >= or <=) on the indexed
  93323. ** column that immediately follows the N equalities. Only
  93324. ** the right-most column can be an inequality - the rest must
  93325. ** use the "==" and "IN" operators. For example, if the
  93326. ** index is on (x,y,z), then the following clauses are all
  93327. ** optimized:
  93328. **
  93329. ** x=5
  93330. ** x=5 AND y=10
  93331. ** x=5 AND y<10
  93332. ** x=5 AND y>5 AND y<10
  93333. ** x=5 AND y=5 AND z<=10
  93334. **
  93335. ** The z<10 term of the following cannot be used, only
  93336. ** the x=5 term:
  93337. **
  93338. ** x=5 AND z<10
  93339. **
  93340. ** N may be zero if there are inequality constraints.
  93341. ** If there are no inequality constraints, then N is at
  93342. ** least one.
  93343. **
  93344. ** This case is also used when there are no WHERE clause
  93345. ** constraints but an index is selected anyway, in order
  93346. ** to force the output order to conform to an ORDER BY.
  93347. */
  93348. static const u8 aStartOp[] = {
  93349. 0,
  93350. 0,
  93351. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  93352. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  93353. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  93354. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  93355. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  93356. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  93357. };
  93358. static const u8 aEndOp[] = {
  93359. OP_Noop, /* 0: (!end_constraints) */
  93360. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  93361. OP_IdxLT /* 2: (end_constraints && bRev) */
  93362. };
  93363. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  93364. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  93365. int regBase; /* Base register holding constraint values */
  93366. int r1; /* Temp register */
  93367. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  93368. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  93369. int startEq; /* True if range start uses ==, >= or <= */
  93370. int endEq; /* True if range end uses ==, >= or <= */
  93371. int start_constraints; /* Start of range is constrained */
  93372. int nConstraint; /* Number of constraint terms */
  93373. Index *pIdx; /* The index we will be using */
  93374. int iIdxCur; /* The VDBE cursor for the index */
  93375. int nExtraReg = 0; /* Number of extra registers needed */
  93376. int op; /* Instruction opcode */
  93377. char *zStartAff; /* Affinity for start of range constraint */
  93378. char *zEndAff; /* Affinity for end of range constraint */
  93379. pIdx = pLoop->u.btree.pIndex;
  93380. iIdxCur = pLevel->iIdxCur;
  93381. /* If this loop satisfies a sort order (pOrderBy) request that
  93382. ** was passed to this function to implement a "SELECT min(x) ..."
  93383. ** query, then the caller will only allow the loop to run for
  93384. ** a single iteration. This means that the first row returned
  93385. ** should not have a NULL value stored in 'x'. If column 'x' is
  93386. ** the first one after the nEq equality constraints in the index,
  93387. ** this requires some special handling.
  93388. */
  93389. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  93390. && (pWInfo->bOBSat!=0)
  93391. && (pIdx->nColumn>nEq)
  93392. ){
  93393. /* assert( pOrderBy->nExpr==1 ); */
  93394. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  93395. isMinQuery = 1;
  93396. nExtraReg = 1;
  93397. }
  93398. /* Find any inequality constraint terms for the start and end
  93399. ** of the range.
  93400. */
  93401. j = nEq;
  93402. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  93403. pRangeStart = pLoop->aLTerm[j++];
  93404. nExtraReg = 1;
  93405. }
  93406. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  93407. pRangeEnd = pLoop->aLTerm[j++];
  93408. nExtraReg = 1;
  93409. }
  93410. /* Generate code to evaluate all constraint terms using == or IN
  93411. ** and store the values of those terms in an array of registers
  93412. ** starting at regBase.
  93413. */
  93414. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  93415. zEndAff = sqlite3DbStrDup(db, zStartAff);
  93416. addrNxt = pLevel->addrNxt;
  93417. /* If we are doing a reverse order scan on an ascending index, or
  93418. ** a forward order scan on a descending index, interchange the
  93419. ** start and end terms (pRangeStart and pRangeEnd).
  93420. */
  93421. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  93422. || (bRev && pIdx->nColumn==nEq)
  93423. ){
  93424. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  93425. }
  93426. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  93427. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  93428. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  93429. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  93430. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  93431. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  93432. start_constraints = pRangeStart || nEq>0;
  93433. /* Seek the index cursor to the start of the range. */
  93434. nConstraint = nEq;
  93435. if( pRangeStart ){
  93436. Expr *pRight = pRangeStart->pExpr->pRight;
  93437. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  93438. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  93439. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  93440. }
  93441. if( zStartAff ){
  93442. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  93443. /* Since the comparison is to be performed with no conversions
  93444. ** applied to the operands, set the affinity to apply to pRight to
  93445. ** SQLITE_AFF_NONE. */
  93446. zStartAff[nEq] = SQLITE_AFF_NONE;
  93447. }
  93448. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  93449. zStartAff[nEq] = SQLITE_AFF_NONE;
  93450. }
  93451. }
  93452. nConstraint++;
  93453. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  93454. }else if( isMinQuery ){
  93455. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  93456. nConstraint++;
  93457. startEq = 0;
  93458. start_constraints = 1;
  93459. }
  93460. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  93461. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  93462. assert( op!=0 );
  93463. testcase( op==OP_Rewind );
  93464. testcase( op==OP_Last );
  93465. testcase( op==OP_SeekGt );
  93466. testcase( op==OP_SeekGe );
  93467. testcase( op==OP_SeekLe );
  93468. testcase( op==OP_SeekLt );
  93469. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  93470. /* Load the value for the inequality constraint at the end of the
  93471. ** range (if any).
  93472. */
  93473. nConstraint = nEq;
  93474. if( pRangeEnd ){
  93475. Expr *pRight = pRangeEnd->pExpr->pRight;
  93476. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  93477. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  93478. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  93479. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  93480. }
  93481. if( zEndAff ){
  93482. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  93483. /* Since the comparison is to be performed with no conversions
  93484. ** applied to the operands, set the affinity to apply to pRight to
  93485. ** SQLITE_AFF_NONE. */
  93486. zEndAff[nEq] = SQLITE_AFF_NONE;
  93487. }
  93488. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  93489. zEndAff[nEq] = SQLITE_AFF_NONE;
  93490. }
  93491. }
  93492. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  93493. nConstraint++;
  93494. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  93495. }
  93496. sqlite3DbFree(db, zStartAff);
  93497. sqlite3DbFree(db, zEndAff);
  93498. /* Top of the loop body */
  93499. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  93500. /* Check if the index cursor is past the end of the range. */
  93501. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  93502. testcase( op==OP_Noop );
  93503. testcase( op==OP_IdxGE );
  93504. testcase( op==OP_IdxLT );
  93505. if( op!=OP_Noop ){
  93506. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  93507. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  93508. }
  93509. /* If there are inequality constraints, check that the value
  93510. ** of the table column that the inequality contrains is not NULL.
  93511. ** If it is, jump to the next iteration of the loop.
  93512. */
  93513. r1 = sqlite3GetTempReg(pParse);
  93514. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  93515. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  93516. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  93517. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  93518. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  93519. }
  93520. sqlite3ReleaseTempReg(pParse, r1);
  93521. /* Seek the table cursor, if required */
  93522. disableTerm(pLevel, pRangeStart);
  93523. disableTerm(pLevel, pRangeEnd);
  93524. if( !omitTable ){
  93525. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  93526. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  93527. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  93528. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  93529. }
  93530. /* Record the instruction used to terminate the loop. Disable
  93531. ** WHERE clause terms made redundant by the index range scan.
  93532. */
  93533. if( pLoop->wsFlags & WHERE_ONEROW ){
  93534. pLevel->op = OP_Noop;
  93535. }else if( bRev ){
  93536. pLevel->op = OP_Prev;
  93537. }else{
  93538. pLevel->op = OP_Next;
  93539. }
  93540. pLevel->p1 = iIdxCur;
  93541. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  93542. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  93543. }else{
  93544. assert( pLevel->p5==0 );
  93545. }
  93546. }else
  93547. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  93548. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  93549. /* Case 5: Two or more separately indexed terms connected by OR
  93550. **
  93551. ** Example:
  93552. **
  93553. ** CREATE TABLE t1(a,b,c,d);
  93554. ** CREATE INDEX i1 ON t1(a);
  93555. ** CREATE INDEX i2 ON t1(b);
  93556. ** CREATE INDEX i3 ON t1(c);
  93557. **
  93558. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  93559. **
  93560. ** In the example, there are three indexed terms connected by OR.
  93561. ** The top of the loop looks like this:
  93562. **
  93563. ** Null 1 # Zero the rowset in reg 1
  93564. **
  93565. ** Then, for each indexed term, the following. The arguments to
  93566. ** RowSetTest are such that the rowid of the current row is inserted
  93567. ** into the RowSet. If it is already present, control skips the
  93568. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  93569. **
  93570. ** sqlite3WhereBegin(<term>)
  93571. ** RowSetTest # Insert rowid into rowset
  93572. ** Gosub 2 A
  93573. ** sqlite3WhereEnd()
  93574. **
  93575. ** Following the above, code to terminate the loop. Label A, the target
  93576. ** of the Gosub above, jumps to the instruction right after the Goto.
  93577. **
  93578. ** Null 1 # Zero the rowset in reg 1
  93579. ** Goto B # The loop is finished.
  93580. **
  93581. ** A: <loop body> # Return data, whatever.
  93582. **
  93583. ** Return 2 # Jump back to the Gosub
  93584. **
  93585. ** B: <after the loop>
  93586. **
  93587. */
  93588. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  93589. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  93590. Index *pCov = 0; /* Potential covering index (or NULL) */
  93591. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  93592. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  93593. int regRowset = 0; /* Register for RowSet object */
  93594. int regRowid = 0; /* Register holding rowid */
  93595. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  93596. int iRetInit; /* Address of regReturn init */
  93597. int untestedTerms = 0; /* Some terms not completely tested */
  93598. int ii; /* Loop counter */
  93599. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  93600. pTerm = pLoop->aLTerm[0];
  93601. assert( pTerm!=0 );
  93602. assert( pTerm->eOperator & WO_OR );
  93603. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  93604. pOrWc = &pTerm->u.pOrInfo->wc;
  93605. pLevel->op = OP_Return;
  93606. pLevel->p1 = regReturn;
  93607. /* Set up a new SrcList in pOrTab containing the table being scanned
  93608. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  93609. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  93610. */
  93611. if( pWInfo->nLevel>1 ){
  93612. int nNotReady; /* The number of notReady tables */
  93613. struct SrcList_item *origSrc; /* Original list of tables */
  93614. nNotReady = pWInfo->nLevel - iLevel - 1;
  93615. pOrTab = sqlite3StackAllocRaw(db,
  93616. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  93617. if( pOrTab==0 ) return notReady;
  93618. pOrTab->nAlloc = (u8)(nNotReady + 1);
  93619. pOrTab->nSrc = pOrTab->nAlloc;
  93620. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  93621. origSrc = pWInfo->pTabList->a;
  93622. for(k=1; k<=nNotReady; k++){
  93623. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  93624. }
  93625. }else{
  93626. pOrTab = pWInfo->pTabList;
  93627. }
  93628. /* Initialize the rowset register to contain NULL. An SQL NULL is
  93629. ** equivalent to an empty rowset.
  93630. **
  93631. ** Also initialize regReturn to contain the address of the instruction
  93632. ** immediately following the OP_Return at the bottom of the loop. This
  93633. ** is required in a few obscure LEFT JOIN cases where control jumps
  93634. ** over the top of the loop into the body of it. In this case the
  93635. ** correct response for the end-of-loop code (the OP_Return) is to
  93636. ** fall through to the next instruction, just as an OP_Next does if
  93637. ** called on an uninitialized cursor.
  93638. */
  93639. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  93640. regRowset = ++pParse->nMem;
  93641. regRowid = ++pParse->nMem;
  93642. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  93643. }
  93644. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  93645. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  93646. ** Then for every term xN, evaluate as the subexpression: xN AND z
  93647. ** That way, terms in y that are factored into the disjunction will
  93648. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  93649. **
  93650. ** Actually, each subexpression is converted to "xN AND w" where w is
  93651. ** the "interesting" terms of z - terms that did not originate in the
  93652. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  93653. ** indices.
  93654. **
  93655. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  93656. ** is not contained in the ON clause of a LEFT JOIN.
  93657. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  93658. */
  93659. if( pWC->nTerm>1 ){
  93660. int iTerm;
  93661. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  93662. Expr *pExpr = pWC->a[iTerm].pExpr;
  93663. if( &pWC->a[iTerm] == pTerm ) continue;
  93664. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  93665. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  93666. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  93667. pExpr = sqlite3ExprDup(db, pExpr, 0);
  93668. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  93669. }
  93670. if( pAndExpr ){
  93671. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  93672. }
  93673. }
  93674. for(ii=0; ii<pOrWc->nTerm; ii++){
  93675. WhereTerm *pOrTerm = &pOrWc->a[ii];
  93676. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  93677. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  93678. Expr *pOrExpr = pOrTerm->pExpr;
  93679. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  93680. pAndExpr->pLeft = pOrExpr;
  93681. pOrExpr = pAndExpr;
  93682. }
  93683. /* Loop through table entries that match term pOrTerm. */
  93684. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  93685. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  93686. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  93687. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  93688. if( pSubWInfo ){
  93689. WhereLoop *pSubLoop;
  93690. explainOneScan(
  93691. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  93692. );
  93693. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  93694. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  93695. int r;
  93696. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  93697. regRowid, 0);
  93698. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  93699. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  93700. }
  93701. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  93702. /* The pSubWInfo->untestedTerms flag means that this OR term
  93703. ** contained one or more AND term from a notReady table. The
  93704. ** terms from the notReady table could not be tested and will
  93705. ** need to be tested later.
  93706. */
  93707. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  93708. /* If all of the OR-connected terms are optimized using the same
  93709. ** index, and the index is opened using the same cursor number
  93710. ** by each call to sqlite3WhereBegin() made by this loop, it may
  93711. ** be possible to use that index as a covering index.
  93712. **
  93713. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  93714. ** uses an index, and this is either the first OR-connected term
  93715. ** processed or the index is the same as that used by all previous
  93716. ** terms, set pCov to the candidate covering index. Otherwise, set
  93717. ** pCov to NULL to indicate that no candidate covering index will
  93718. ** be available.
  93719. */
  93720. pSubLoop = pSubWInfo->a[0].pWLoop;
  93721. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  93722. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  93723. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  93724. ){
  93725. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  93726. pCov = pSubLoop->u.btree.pIndex;
  93727. }else{
  93728. pCov = 0;
  93729. }
  93730. /* Finish the loop through table entries that match term pOrTerm. */
  93731. sqlite3WhereEnd(pSubWInfo);
  93732. }
  93733. }
  93734. }
  93735. pLevel->u.pCovidx = pCov;
  93736. if( pCov ) pLevel->iIdxCur = iCovCur;
  93737. if( pAndExpr ){
  93738. pAndExpr->pLeft = 0;
  93739. sqlite3ExprDelete(db, pAndExpr);
  93740. }
  93741. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  93742. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  93743. sqlite3VdbeResolveLabel(v, iLoopBody);
  93744. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  93745. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  93746. }else
  93747. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  93748. {
  93749. /* Case 6: There is no usable index. We must do a complete
  93750. ** scan of the entire table.
  93751. */
  93752. static const u8 aStep[] = { OP_Next, OP_Prev };
  93753. static const u8 aStart[] = { OP_Rewind, OP_Last };
  93754. assert( bRev==0 || bRev==1 );
  93755. pLevel->op = aStep[bRev];
  93756. pLevel->p1 = iCur;
  93757. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  93758. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  93759. }
  93760. /* Insert code to test every subexpression that can be completely
  93761. ** computed using the current set of tables.
  93762. */
  93763. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  93764. Expr *pE;
  93765. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93766. testcase( pTerm->wtFlags & TERM_CODED );
  93767. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93768. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  93769. testcase( pWInfo->untestedTerms==0
  93770. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  93771. pWInfo->untestedTerms = 1;
  93772. continue;
  93773. }
  93774. pE = pTerm->pExpr;
  93775. assert( pE!=0 );
  93776. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  93777. continue;
  93778. }
  93779. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  93780. pTerm->wtFlags |= TERM_CODED;
  93781. }
  93782. /* Insert code to test for implied constraints based on transitivity
  93783. ** of the "==" operator.
  93784. **
  93785. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  93786. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  93787. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  93788. ** the implied "t1.a=123" constraint.
  93789. */
  93790. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  93791. Expr *pE, *pEAlt;
  93792. WhereTerm *pAlt;
  93793. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93794. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  93795. if( pTerm->leftCursor!=iCur ) continue;
  93796. if( pLevel->iLeftJoin ) continue;
  93797. pE = pTerm->pExpr;
  93798. assert( !ExprHasProperty(pE, EP_FromJoin) );
  93799. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  93800. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  93801. if( pAlt==0 ) continue;
  93802. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  93803. testcase( pAlt->eOperator & WO_EQ );
  93804. testcase( pAlt->eOperator & WO_IN );
  93805. VdbeNoopComment((v, "begin transitive constraint"));
  93806. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  93807. if( pEAlt ){
  93808. *pEAlt = *pAlt->pExpr;
  93809. pEAlt->pLeft = pE->pLeft;
  93810. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  93811. sqlite3StackFree(db, pEAlt);
  93812. }
  93813. }
  93814. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  93815. ** at least one row of the right table has matched the left table.
  93816. */
  93817. if( pLevel->iLeftJoin ){
  93818. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  93819. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  93820. VdbeComment((v, "record LEFT JOIN hit"));
  93821. sqlite3ExprCacheClear(pParse);
  93822. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  93823. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  93824. testcase( pTerm->wtFlags & TERM_CODED );
  93825. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  93826. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  93827. assert( pWInfo->untestedTerms );
  93828. continue;
  93829. }
  93830. assert( pTerm->pExpr );
  93831. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  93832. pTerm->wtFlags |= TERM_CODED;
  93833. }
  93834. }
  93835. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  93836. return pLevel->notReady;
  93837. }
  93838. #ifdef WHERETRACE_ENABLED
  93839. /*
  93840. ** Print a WhereLoop object for debugging purposes
  93841. */
  93842. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  93843. int nb = 1+(pTabList->nSrc+7)/8;
  93844. struct SrcList_item *pItem = pTabList->a + p->iTab;
  93845. Table *pTab = pItem->pTab;
  93846. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  93847. p->iTab, nb, p->maskSelf, nb, p->prereq);
  93848. sqlite3DebugPrintf(" %12s",
  93849. pItem->zAlias ? pItem->zAlias : pTab->zName);
  93850. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  93851. if( p->u.btree.pIndex ){
  93852. const char *zName = p->u.btree.pIndex->zName;
  93853. if( zName==0 ) zName = "ipk";
  93854. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  93855. int i = sqlite3Strlen30(zName) - 1;
  93856. while( zName[i]!='_' ) i--;
  93857. zName += i;
  93858. }
  93859. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  93860. }else{
  93861. sqlite3DebugPrintf("%20s","");
  93862. }
  93863. }else{
  93864. char *z;
  93865. if( p->u.vtab.idxStr ){
  93866. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  93867. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  93868. }else{
  93869. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  93870. }
  93871. sqlite3DebugPrintf(" %-19s", z);
  93872. sqlite3_free(z);
  93873. }
  93874. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  93875. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  93876. }
  93877. #endif
  93878. /*
  93879. ** Convert bulk memory into a valid WhereLoop that can be passed
  93880. ** to whereLoopClear harmlessly.
  93881. */
  93882. static void whereLoopInit(WhereLoop *p){
  93883. p->aLTerm = p->aLTermSpace;
  93884. p->nLTerm = 0;
  93885. p->nLSlot = ArraySize(p->aLTermSpace);
  93886. p->wsFlags = 0;
  93887. }
  93888. /*
  93889. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  93890. */
  93891. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  93892. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  93893. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  93894. sqlite3_free(p->u.vtab.idxStr);
  93895. p->u.vtab.needFree = 0;
  93896. p->u.vtab.idxStr = 0;
  93897. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  93898. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  93899. sqlite3DbFree(db, p->u.btree.pIndex);
  93900. p->u.btree.pIndex = 0;
  93901. }
  93902. }
  93903. }
  93904. /*
  93905. ** Deallocate internal memory used by a WhereLoop object
  93906. */
  93907. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  93908. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  93909. whereLoopClearUnion(db, p);
  93910. whereLoopInit(p);
  93911. }
  93912. /*
  93913. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  93914. */
  93915. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  93916. WhereTerm **paNew;
  93917. if( p->nLSlot>=n ) return SQLITE_OK;
  93918. n = (n+7)&~7;
  93919. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  93920. if( paNew==0 ) return SQLITE_NOMEM;
  93921. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  93922. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  93923. p->aLTerm = paNew;
  93924. p->nLSlot = n;
  93925. return SQLITE_OK;
  93926. }
  93927. /*
  93928. ** Transfer content from the second pLoop into the first.
  93929. */
  93930. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  93931. whereLoopClearUnion(db, pTo);
  93932. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  93933. memset(&pTo->u, 0, sizeof(pTo->u));
  93934. return SQLITE_NOMEM;
  93935. }
  93936. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  93937. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  93938. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  93939. pFrom->u.vtab.needFree = 0;
  93940. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  93941. pFrom->u.btree.pIndex = 0;
  93942. }
  93943. return SQLITE_OK;
  93944. }
  93945. /*
  93946. ** Delete a WhereLoop object
  93947. */
  93948. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  93949. whereLoopClear(db, p);
  93950. sqlite3DbFree(db, p);
  93951. }
  93952. /*
  93953. ** Free a WhereInfo structure
  93954. */
  93955. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  93956. if( ALWAYS(pWInfo) ){
  93957. whereClauseClear(&pWInfo->sWC);
  93958. while( pWInfo->pLoops ){
  93959. WhereLoop *p = pWInfo->pLoops;
  93960. pWInfo->pLoops = p->pNextLoop;
  93961. whereLoopDelete(db, p);
  93962. }
  93963. sqlite3DbFree(db, pWInfo);
  93964. }
  93965. }
  93966. /*
  93967. ** Insert or replace a WhereLoop entry using the template supplied.
  93968. **
  93969. ** An existing WhereLoop entry might be overwritten if the new template
  93970. ** is better and has fewer dependencies. Or the template will be ignored
  93971. ** and no insert will occur if an existing WhereLoop is faster and has
  93972. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  93973. ** added based on the template.
  93974. **
  93975. ** If pBuilder->pOrSet is not NULL then we only care about only the
  93976. ** prerequisites and rRun and nOut costs of the N best loops. That
  93977. ** information is gathered in the pBuilder->pOrSet object. This special
  93978. ** processing mode is used only for OR clause processing.
  93979. **
  93980. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  93981. ** still might overwrite similar loops with the new template if the
  93982. ** template is better. Loops may be overwritten if the following
  93983. ** conditions are met:
  93984. **
  93985. ** (1) They have the same iTab.
  93986. ** (2) They have the same iSortIdx.
  93987. ** (3) The template has same or fewer dependencies than the current loop
  93988. ** (4) The template has the same or lower cost than the current loop
  93989. ** (5) The template uses more terms of the same index but has no additional
  93990. ** dependencies
  93991. */
  93992. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  93993. WhereLoop **ppPrev, *p, *pNext = 0;
  93994. WhereInfo *pWInfo = pBuilder->pWInfo;
  93995. sqlite3 *db = pWInfo->pParse->db;
  93996. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  93997. ** and prereqs.
  93998. */
  93999. if( pBuilder->pOrSet!=0 ){
  94000. #if WHERETRACE_ENABLED
  94001. u16 n = pBuilder->pOrSet->n;
  94002. int x =
  94003. #endif
  94004. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  94005. pTemplate->nOut);
  94006. #if WHERETRACE_ENABLED
  94007. if( sqlite3WhereTrace & 0x8 ){
  94008. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  94009. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94010. }
  94011. #endif
  94012. return SQLITE_OK;
  94013. }
  94014. /* Search for an existing WhereLoop to overwrite, or which takes
  94015. ** priority over pTemplate.
  94016. */
  94017. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  94018. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  94019. /* If either the iTab or iSortIdx values for two WhereLoop are different
  94020. ** then those WhereLoops need to be considered separately. Neither is
  94021. ** a candidate to replace the other. */
  94022. continue;
  94023. }
  94024. /* In the current implementation, the rSetup value is either zero
  94025. ** or the cost of building an automatic index (NlogN) and the NlogN
  94026. ** is the same for compatible WhereLoops. */
  94027. assert( p->rSetup==0 || pTemplate->rSetup==0
  94028. || p->rSetup==pTemplate->rSetup );
  94029. /* whereLoopAddBtree() always generates and inserts the automatic index
  94030. ** case first. Hence compatible candidate WhereLoops never have a larger
  94031. ** rSetup. Call this SETUP-INVARIANT */
  94032. assert( p->rSetup>=pTemplate->rSetup );
  94033. if( (p->prereq & pTemplate->prereq)==p->prereq
  94034. && p->rSetup<=pTemplate->rSetup
  94035. && p->rRun<=pTemplate->rRun
  94036. && p->nOut<=pTemplate->nOut
  94037. ){
  94038. /* This branch taken when p is equal or better than pTemplate in
  94039. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  94040. ** (4) number of output rows. */
  94041. assert( p->rSetup==pTemplate->rSetup );
  94042. if( p->prereq==pTemplate->prereq
  94043. && p->nLTerm<pTemplate->nLTerm
  94044. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  94045. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  94046. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  94047. ){
  94048. /* Overwrite an existing WhereLoop with an similar one that uses
  94049. ** more terms of the index */
  94050. pNext = p->pNextLoop;
  94051. break;
  94052. }else{
  94053. /* pTemplate is not helpful.
  94054. ** Return without changing or adding anything */
  94055. goto whereLoopInsert_noop;
  94056. }
  94057. }
  94058. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  94059. && p->rRun>=pTemplate->rRun
  94060. && p->nOut>=pTemplate->nOut
  94061. ){
  94062. /* Overwrite an existing WhereLoop with a better one: one that is
  94063. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  94064. ** or (4) number of output rows, and is no worse in any of those
  94065. ** categories. */
  94066. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  94067. pNext = p->pNextLoop;
  94068. break;
  94069. }
  94070. }
  94071. /* If we reach this point it means that either p[] should be overwritten
  94072. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  94073. ** WhereLoop and insert it.
  94074. */
  94075. #if WHERETRACE_ENABLED
  94076. if( sqlite3WhereTrace & 0x8 ){
  94077. if( p!=0 ){
  94078. sqlite3DebugPrintf("ins-del: ");
  94079. whereLoopPrint(p, pWInfo->pTabList);
  94080. }
  94081. sqlite3DebugPrintf("ins-new: ");
  94082. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94083. }
  94084. #endif
  94085. if( p==0 ){
  94086. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  94087. if( p==0 ) return SQLITE_NOMEM;
  94088. whereLoopInit(p);
  94089. }
  94090. whereLoopXfer(db, p, pTemplate);
  94091. p->pNextLoop = pNext;
  94092. *ppPrev = p;
  94093. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  94094. Index *pIndex = p->u.btree.pIndex;
  94095. if( pIndex && pIndex->tnum==0 ){
  94096. p->u.btree.pIndex = 0;
  94097. }
  94098. }
  94099. return SQLITE_OK;
  94100. /* Jump here if the insert is a no-op */
  94101. whereLoopInsert_noop:
  94102. #if WHERETRACE_ENABLED
  94103. if( sqlite3WhereTrace & 0x8 ){
  94104. sqlite3DebugPrintf("ins-noop: ");
  94105. whereLoopPrint(pTemplate, pWInfo->pTabList);
  94106. }
  94107. #endif
  94108. return SQLITE_OK;
  94109. }
  94110. /*
  94111. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  94112. ** WHERE clause that reference the loop but which are not used by an
  94113. ** index.
  94114. **
  94115. ** In the current implementation, the first extra WHERE clause term reduces
  94116. ** the number of output rows by a factor of 10 and each additional term
  94117. ** reduces the number of output rows by sqrt(2).
  94118. */
  94119. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  94120. WhereTerm *pTerm, *pX;
  94121. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  94122. int i, j;
  94123. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  94124. return;
  94125. }
  94126. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  94127. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  94128. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  94129. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  94130. for(j=pLoop->nLTerm-1; j>=0; j--){
  94131. pX = pLoop->aLTerm[j];
  94132. if( pX==pTerm ) break;
  94133. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  94134. }
  94135. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  94136. }
  94137. }
  94138. /*
  94139. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  94140. ** Try to match one more.
  94141. **
  94142. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  94143. ** INTEGER PRIMARY KEY.
  94144. */
  94145. static int whereLoopAddBtreeIndex(
  94146. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  94147. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  94148. Index *pProbe, /* An index on pSrc */
  94149. LogEst nInMul /* log(Number of iterations due to IN) */
  94150. ){
  94151. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  94152. Parse *pParse = pWInfo->pParse; /* Parsing context */
  94153. sqlite3 *db = pParse->db; /* Database connection malloc context */
  94154. WhereLoop *pNew; /* Template WhereLoop under construction */
  94155. WhereTerm *pTerm; /* A WhereTerm under consideration */
  94156. int opMask; /* Valid operators for constraints */
  94157. WhereScan scan; /* Iterator for WHERE terms */
  94158. Bitmask saved_prereq; /* Original value of pNew->prereq */
  94159. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  94160. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  94161. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  94162. LogEst saved_nOut; /* Original value of pNew->nOut */
  94163. int iCol; /* Index of the column in the table */
  94164. int rc = SQLITE_OK; /* Return code */
  94165. LogEst nRowEst; /* Estimated index selectivity */
  94166. LogEst rLogSize; /* Logarithm of table size */
  94167. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  94168. pNew = pBuilder->pNew;
  94169. if( db->mallocFailed ) return SQLITE_NOMEM;
  94170. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  94171. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  94172. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  94173. opMask = WO_LT|WO_LE;
  94174. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  94175. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  94176. }else{
  94177. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  94178. }
  94179. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  94180. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  94181. if( pNew->u.btree.nEq < pProbe->nColumn ){
  94182. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  94183. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  94184. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  94185. }else{
  94186. iCol = -1;
  94187. nRowEst = 0;
  94188. }
  94189. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  94190. opMask, pProbe);
  94191. saved_nEq = pNew->u.btree.nEq;
  94192. saved_nLTerm = pNew->nLTerm;
  94193. saved_wsFlags = pNew->wsFlags;
  94194. saved_prereq = pNew->prereq;
  94195. saved_nOut = pNew->nOut;
  94196. pNew->rSetup = 0;
  94197. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  94198. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  94199. int nIn = 0;
  94200. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94201. int nRecValid = pBuilder->nRecValid;
  94202. #endif
  94203. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  94204. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  94205. ){
  94206. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  94207. }
  94208. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  94209. assert( pNew->nOut==saved_nOut );
  94210. pNew->wsFlags = saved_wsFlags;
  94211. pNew->u.btree.nEq = saved_nEq;
  94212. pNew->nLTerm = saved_nLTerm;
  94213. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  94214. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  94215. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  94216. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  94217. if( pTerm->eOperator & WO_IN ){
  94218. Expr *pExpr = pTerm->pExpr;
  94219. pNew->wsFlags |= WHERE_COLUMN_IN;
  94220. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  94221. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  94222. nIn = 46; assert( 46==sqlite3LogEst(25) );
  94223. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  94224. /* "x IN (value, value, ...)" */
  94225. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  94226. }
  94227. pNew->rRun += nIn;
  94228. pNew->u.btree.nEq++;
  94229. pNew->nOut = nRowEst + nInMul + nIn;
  94230. }else if( pTerm->eOperator & (WO_EQ) ){
  94231. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  94232. || nInMul==0 );
  94233. pNew->wsFlags |= WHERE_COLUMN_EQ;
  94234. if( iCol<0
  94235. || (pProbe->onError!=OE_None && nInMul==0
  94236. && pNew->u.btree.nEq==pProbe->nColumn-1)
  94237. ){
  94238. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  94239. pNew->wsFlags |= WHERE_ONEROW;
  94240. }
  94241. pNew->u.btree.nEq++;
  94242. pNew->nOut = nRowEst + nInMul;
  94243. }else if( pTerm->eOperator & (WO_ISNULL) ){
  94244. pNew->wsFlags |= WHERE_COLUMN_NULL;
  94245. pNew->u.btree.nEq++;
  94246. /* TUNING: IS NULL selects 2 rows */
  94247. nIn = 10; assert( 10==sqlite3LogEst(2) );
  94248. pNew->nOut = nRowEst + nInMul + nIn;
  94249. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  94250. testcase( pTerm->eOperator & WO_GT );
  94251. testcase( pTerm->eOperator & WO_GE );
  94252. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  94253. pBtm = pTerm;
  94254. pTop = 0;
  94255. }else{
  94256. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  94257. testcase( pTerm->eOperator & WO_LT );
  94258. testcase( pTerm->eOperator & WO_LE );
  94259. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  94260. pTop = pTerm;
  94261. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  94262. pNew->aLTerm[pNew->nLTerm-2] : 0;
  94263. }
  94264. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  94265. /* Adjust nOut and rRun for STAT3 range values */
  94266. assert( pNew->nOut==saved_nOut );
  94267. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  94268. }
  94269. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94270. if( nInMul==0
  94271. && pProbe->nSample
  94272. && pNew->u.btree.nEq<=pProbe->nSampleCol
  94273. && OptimizationEnabled(db, SQLITE_Stat3)
  94274. ){
  94275. Expr *pExpr = pTerm->pExpr;
  94276. tRowcnt nOut = 0;
  94277. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  94278. testcase( pTerm->eOperator & WO_EQ );
  94279. testcase( pTerm->eOperator & WO_ISNULL );
  94280. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  94281. }else if( (pTerm->eOperator & WO_IN)
  94282. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  94283. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  94284. }
  94285. assert( nOut==0 || rc==SQLITE_OK );
  94286. if( nOut ){
  94287. pNew->nOut = sqlite3LogEst(nOut);
  94288. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  94289. }
  94290. }
  94291. #endif
  94292. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  94293. /* Each row involves a step of the index, then a binary search of
  94294. ** the main table */
  94295. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  94296. }
  94297. /* Step cost for each output row */
  94298. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  94299. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  94300. rc = whereLoopInsert(pBuilder, pNew);
  94301. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  94302. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  94303. ){
  94304. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  94305. }
  94306. pNew->nOut = saved_nOut;
  94307. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94308. pBuilder->nRecValid = nRecValid;
  94309. #endif
  94310. }
  94311. pNew->prereq = saved_prereq;
  94312. pNew->u.btree.nEq = saved_nEq;
  94313. pNew->wsFlags = saved_wsFlags;
  94314. pNew->nOut = saved_nOut;
  94315. pNew->nLTerm = saved_nLTerm;
  94316. return rc;
  94317. }
  94318. /*
  94319. ** Return True if it is possible that pIndex might be useful in
  94320. ** implementing the ORDER BY clause in pBuilder.
  94321. **
  94322. ** Return False if pBuilder does not contain an ORDER BY clause or
  94323. ** if there is no way for pIndex to be useful in implementing that
  94324. ** ORDER BY clause.
  94325. */
  94326. static int indexMightHelpWithOrderBy(
  94327. WhereLoopBuilder *pBuilder,
  94328. Index *pIndex,
  94329. int iCursor
  94330. ){
  94331. ExprList *pOB;
  94332. int ii, jj;
  94333. if( pIndex->bUnordered ) return 0;
  94334. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  94335. for(ii=0; ii<pOB->nExpr; ii++){
  94336. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  94337. if( pExpr->op!=TK_COLUMN ) return 0;
  94338. if( pExpr->iTable==iCursor ){
  94339. for(jj=0; jj<pIndex->nColumn; jj++){
  94340. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  94341. }
  94342. }
  94343. }
  94344. return 0;
  94345. }
  94346. /*
  94347. ** Return a bitmask where 1s indicate that the corresponding column of
  94348. ** the table is used by an index. Only the first 63 columns are considered.
  94349. */
  94350. static Bitmask columnsInIndex(Index *pIdx){
  94351. Bitmask m = 0;
  94352. int j;
  94353. for(j=pIdx->nColumn-1; j>=0; j--){
  94354. int x = pIdx->aiColumn[j];
  94355. assert( x>=0 );
  94356. testcase( x==BMS-1 );
  94357. testcase( x==BMS-2 );
  94358. if( x<BMS-1 ) m |= MASKBIT(x);
  94359. }
  94360. return m;
  94361. }
  94362. /* Check to see if a partial index with pPartIndexWhere can be used
  94363. ** in the current query. Return true if it can be and false if not.
  94364. */
  94365. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  94366. int i;
  94367. WhereTerm *pTerm;
  94368. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  94369. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  94370. }
  94371. return 0;
  94372. }
  94373. /*
  94374. ** Add all WhereLoop objects for a single table of the join where the table
  94375. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  94376. ** a b-tree table, not a virtual table.
  94377. */
  94378. static int whereLoopAddBtree(
  94379. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  94380. Bitmask mExtra /* Extra prerequesites for using this table */
  94381. ){
  94382. WhereInfo *pWInfo; /* WHERE analysis context */
  94383. Index *pProbe; /* An index we are evaluating */
  94384. Index sPk; /* A fake index object for the primary key */
  94385. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  94386. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  94387. SrcList *pTabList; /* The FROM clause */
  94388. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  94389. WhereLoop *pNew; /* Template WhereLoop object */
  94390. int rc = SQLITE_OK; /* Return code */
  94391. int iSortIdx = 1; /* Index number */
  94392. int b; /* A boolean value */
  94393. LogEst rSize; /* number of rows in the table */
  94394. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  94395. WhereClause *pWC; /* The parsed WHERE clause */
  94396. Table *pTab; /* Table being queried */
  94397. pNew = pBuilder->pNew;
  94398. pWInfo = pBuilder->pWInfo;
  94399. pTabList = pWInfo->pTabList;
  94400. pSrc = pTabList->a + pNew->iTab;
  94401. pTab = pSrc->pTab;
  94402. pWC = pBuilder->pWC;
  94403. assert( !IsVirtual(pSrc->pTab) );
  94404. if( pSrc->pIndex ){
  94405. /* An INDEXED BY clause specifies a particular index to use */
  94406. pProbe = pSrc->pIndex;
  94407. }else{
  94408. /* There is no INDEXED BY clause. Create a fake Index object in local
  94409. ** variable sPk to represent the rowid primary key index. Make this
  94410. ** fake index the first in a chain of Index objects with all of the real
  94411. ** indices to follow */
  94412. Index *pFirst; /* First of real indices on the table */
  94413. memset(&sPk, 0, sizeof(Index));
  94414. sPk.nColumn = 1;
  94415. sPk.aiColumn = &aiColumnPk;
  94416. sPk.aiRowEst = aiRowEstPk;
  94417. sPk.onError = OE_Replace;
  94418. sPk.pTable = pTab;
  94419. aiRowEstPk[0] = pTab->nRowEst;
  94420. aiRowEstPk[1] = 1;
  94421. pFirst = pSrc->pTab->pIndex;
  94422. if( pSrc->notIndexed==0 ){
  94423. /* The real indices of the table are only considered if the
  94424. ** NOT INDEXED qualifier is omitted from the FROM clause */
  94425. sPk.pNext = pFirst;
  94426. }
  94427. pProbe = &sPk;
  94428. }
  94429. rSize = sqlite3LogEst(pTab->nRowEst);
  94430. rLogSize = estLog(rSize);
  94431. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  94432. /* Automatic indexes */
  94433. if( !pBuilder->pOrSet
  94434. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  94435. && pSrc->pIndex==0
  94436. && !pSrc->viaCoroutine
  94437. && !pSrc->notIndexed
  94438. && !pSrc->isCorrelated
  94439. ){
  94440. /* Generate auto-index WhereLoops */
  94441. WhereTerm *pTerm;
  94442. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  94443. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  94444. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  94445. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  94446. pNew->u.btree.nEq = 1;
  94447. pNew->u.btree.pIndex = 0;
  94448. pNew->nLTerm = 1;
  94449. pNew->aLTerm[0] = pTerm;
  94450. /* TUNING: One-time cost for computing the automatic index is
  94451. ** approximately 7*N*log2(N) where N is the number of rows in
  94452. ** the table being indexed. */
  94453. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  94454. /* TUNING: Each index lookup yields 20 rows in the table. This
  94455. ** is more than the usual guess of 10 rows, since we have no way
  94456. ** of knowning how selective the index will ultimately be. It would
  94457. ** not be unreasonable to make this value much larger. */
  94458. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  94459. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  94460. pNew->wsFlags = WHERE_AUTO_INDEX;
  94461. pNew->prereq = mExtra | pTerm->prereqRight;
  94462. rc = whereLoopInsert(pBuilder, pNew);
  94463. }
  94464. }
  94465. }
  94466. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  94467. /* Loop over all indices
  94468. */
  94469. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  94470. if( pProbe->pPartIdxWhere!=0
  94471. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  94472. continue; /* Partial index inappropriate for this query */
  94473. }
  94474. pNew->u.btree.nEq = 0;
  94475. pNew->nLTerm = 0;
  94476. pNew->iSortIdx = 0;
  94477. pNew->rSetup = 0;
  94478. pNew->prereq = mExtra;
  94479. pNew->nOut = rSize;
  94480. pNew->u.btree.pIndex = pProbe;
  94481. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  94482. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  94483. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  94484. if( pProbe->tnum<=0 ){
  94485. /* Integer primary key index */
  94486. pNew->wsFlags = WHERE_IPK;
  94487. /* Full table scan */
  94488. pNew->iSortIdx = b ? iSortIdx : 0;
  94489. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  94490. ** + The extra 3 factor is to encourage the use of indexed lookups
  94491. ** over full scans. FIXME */
  94492. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  94493. whereLoopOutputAdjust(pWC, pNew);
  94494. rc = whereLoopInsert(pBuilder, pNew);
  94495. pNew->nOut = rSize;
  94496. if( rc ) break;
  94497. }else{
  94498. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  94499. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  94500. /* Full scan via index */
  94501. if( b
  94502. || ( m==0
  94503. && pProbe->bUnordered==0
  94504. && pProbe->szIdxRow<pTab->szTabRow
  94505. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  94506. && sqlite3GlobalConfig.bUseCis
  94507. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  94508. )
  94509. ){
  94510. pNew->iSortIdx = b ? iSortIdx : 0;
  94511. if( m==0 ){
  94512. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  94513. ** + The extra factor K of between 1.1 and 3.0 that depends
  94514. ** on the relative sizes of the table and the index. K
  94515. ** is smaller for smaller indices, thus favoring them.
  94516. */
  94517. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  94518. (15*pProbe->szIdxRow)/pTab->szTabRow;
  94519. }else{
  94520. assert( b!=0 );
  94521. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  94522. ** which we will simplify to just N*log2(N) */
  94523. pNew->rRun = rSize + rLogSize;
  94524. }
  94525. whereLoopOutputAdjust(pWC, pNew);
  94526. rc = whereLoopInsert(pBuilder, pNew);
  94527. pNew->nOut = rSize;
  94528. if( rc ) break;
  94529. }
  94530. }
  94531. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  94532. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94533. sqlite3Stat4ProbeFree(pBuilder->pRec);
  94534. pBuilder->nRecValid = 0;
  94535. pBuilder->pRec = 0;
  94536. #endif
  94537. /* If there was an INDEXED BY clause, then only that one index is
  94538. ** considered. */
  94539. if( pSrc->pIndex ) break;
  94540. }
  94541. return rc;
  94542. }
  94543. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94544. /*
  94545. ** Add all WhereLoop objects for a table of the join identified by
  94546. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  94547. */
  94548. static int whereLoopAddVirtual(
  94549. WhereLoopBuilder *pBuilder /* WHERE clause information */
  94550. ){
  94551. WhereInfo *pWInfo; /* WHERE analysis context */
  94552. Parse *pParse; /* The parsing context */
  94553. WhereClause *pWC; /* The WHERE clause */
  94554. struct SrcList_item *pSrc; /* The FROM clause term to search */
  94555. Table *pTab;
  94556. sqlite3 *db;
  94557. sqlite3_index_info *pIdxInfo;
  94558. struct sqlite3_index_constraint *pIdxCons;
  94559. struct sqlite3_index_constraint_usage *pUsage;
  94560. WhereTerm *pTerm;
  94561. int i, j;
  94562. int iTerm, mxTerm;
  94563. int nConstraint;
  94564. int seenIn = 0; /* True if an IN operator is seen */
  94565. int seenVar = 0; /* True if a non-constant constraint is seen */
  94566. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  94567. WhereLoop *pNew;
  94568. int rc = SQLITE_OK;
  94569. pWInfo = pBuilder->pWInfo;
  94570. pParse = pWInfo->pParse;
  94571. db = pParse->db;
  94572. pWC = pBuilder->pWC;
  94573. pNew = pBuilder->pNew;
  94574. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  94575. pTab = pSrc->pTab;
  94576. assert( IsVirtual(pTab) );
  94577. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  94578. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  94579. pNew->prereq = 0;
  94580. pNew->rSetup = 0;
  94581. pNew->wsFlags = WHERE_VIRTUALTABLE;
  94582. pNew->nLTerm = 0;
  94583. pNew->u.vtab.needFree = 0;
  94584. pUsage = pIdxInfo->aConstraintUsage;
  94585. nConstraint = pIdxInfo->nConstraint;
  94586. if( whereLoopResize(db, pNew, nConstraint) ){
  94587. sqlite3DbFree(db, pIdxInfo);
  94588. return SQLITE_NOMEM;
  94589. }
  94590. for(iPhase=0; iPhase<=3; iPhase++){
  94591. if( !seenIn && (iPhase&1)!=0 ){
  94592. iPhase++;
  94593. if( iPhase>3 ) break;
  94594. }
  94595. if( !seenVar && iPhase>1 ) break;
  94596. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  94597. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  94598. j = pIdxCons->iTermOffset;
  94599. pTerm = &pWC->a[j];
  94600. switch( iPhase ){
  94601. case 0: /* Constants without IN operator */
  94602. pIdxCons->usable = 0;
  94603. if( (pTerm->eOperator & WO_IN)!=0 ){
  94604. seenIn = 1;
  94605. }
  94606. if( pTerm->prereqRight!=0 ){
  94607. seenVar = 1;
  94608. }else if( (pTerm->eOperator & WO_IN)==0 ){
  94609. pIdxCons->usable = 1;
  94610. }
  94611. break;
  94612. case 1: /* Constants with IN operators */
  94613. assert( seenIn );
  94614. pIdxCons->usable = (pTerm->prereqRight==0);
  94615. break;
  94616. case 2: /* Variables without IN */
  94617. assert( seenVar );
  94618. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  94619. break;
  94620. default: /* Variables with IN */
  94621. assert( seenVar && seenIn );
  94622. pIdxCons->usable = 1;
  94623. break;
  94624. }
  94625. }
  94626. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  94627. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  94628. pIdxInfo->idxStr = 0;
  94629. pIdxInfo->idxNum = 0;
  94630. pIdxInfo->needToFreeIdxStr = 0;
  94631. pIdxInfo->orderByConsumed = 0;
  94632. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  94633. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  94634. if( rc ) goto whereLoopAddVtab_exit;
  94635. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  94636. pNew->prereq = 0;
  94637. mxTerm = -1;
  94638. assert( pNew->nLSlot>=nConstraint );
  94639. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  94640. pNew->u.vtab.omitMask = 0;
  94641. for(i=0; i<nConstraint; i++, pIdxCons++){
  94642. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  94643. j = pIdxCons->iTermOffset;
  94644. if( iTerm>=nConstraint
  94645. || j<0
  94646. || j>=pWC->nTerm
  94647. || pNew->aLTerm[iTerm]!=0
  94648. ){
  94649. rc = SQLITE_ERROR;
  94650. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  94651. goto whereLoopAddVtab_exit;
  94652. }
  94653. testcase( iTerm==nConstraint-1 );
  94654. testcase( j==0 );
  94655. testcase( j==pWC->nTerm-1 );
  94656. pTerm = &pWC->a[j];
  94657. pNew->prereq |= pTerm->prereqRight;
  94658. assert( iTerm<pNew->nLSlot );
  94659. pNew->aLTerm[iTerm] = pTerm;
  94660. if( iTerm>mxTerm ) mxTerm = iTerm;
  94661. testcase( iTerm==15 );
  94662. testcase( iTerm==16 );
  94663. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  94664. if( (pTerm->eOperator & WO_IN)!=0 ){
  94665. if( pUsage[i].omit==0 ){
  94666. /* Do not attempt to use an IN constraint if the virtual table
  94667. ** says that the equivalent EQ constraint cannot be safely omitted.
  94668. ** If we do attempt to use such a constraint, some rows might be
  94669. ** repeated in the output. */
  94670. break;
  94671. }
  94672. /* A virtual table that is constrained by an IN clause may not
  94673. ** consume the ORDER BY clause because (1) the order of IN terms
  94674. ** is not necessarily related to the order of output terms and
  94675. ** (2) Multiple outputs from a single IN value will not merge
  94676. ** together. */
  94677. pIdxInfo->orderByConsumed = 0;
  94678. }
  94679. }
  94680. }
  94681. if( i>=nConstraint ){
  94682. pNew->nLTerm = mxTerm+1;
  94683. assert( pNew->nLTerm<=pNew->nLSlot );
  94684. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  94685. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  94686. pIdxInfo->needToFreeIdxStr = 0;
  94687. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  94688. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  94689. && pIdxInfo->orderByConsumed);
  94690. pNew->rSetup = 0;
  94691. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  94692. /* TUNING: Every virtual table query returns 25 rows */
  94693. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  94694. whereLoopInsert(pBuilder, pNew);
  94695. if( pNew->u.vtab.needFree ){
  94696. sqlite3_free(pNew->u.vtab.idxStr);
  94697. pNew->u.vtab.needFree = 0;
  94698. }
  94699. }
  94700. }
  94701. whereLoopAddVtab_exit:
  94702. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  94703. sqlite3DbFree(db, pIdxInfo);
  94704. return rc;
  94705. }
  94706. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  94707. /*
  94708. ** Add WhereLoop entries to handle OR terms. This works for either
  94709. ** btrees or virtual tables.
  94710. */
  94711. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  94712. WhereInfo *pWInfo = pBuilder->pWInfo;
  94713. WhereClause *pWC;
  94714. WhereLoop *pNew;
  94715. WhereTerm *pTerm, *pWCEnd;
  94716. int rc = SQLITE_OK;
  94717. int iCur;
  94718. WhereClause tempWC;
  94719. WhereLoopBuilder sSubBuild;
  94720. WhereOrSet sSum, sCur, sPrev;
  94721. struct SrcList_item *pItem;
  94722. pWC = pBuilder->pWC;
  94723. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  94724. pWCEnd = pWC->a + pWC->nTerm;
  94725. pNew = pBuilder->pNew;
  94726. memset(&sSum, 0, sizeof(sSum));
  94727. pItem = pWInfo->pTabList->a + pNew->iTab;
  94728. iCur = pItem->iCursor;
  94729. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  94730. if( (pTerm->eOperator & WO_OR)!=0
  94731. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  94732. ){
  94733. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  94734. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  94735. WhereTerm *pOrTerm;
  94736. int once = 1;
  94737. int i, j;
  94738. sSubBuild = *pBuilder;
  94739. sSubBuild.pOrderBy = 0;
  94740. sSubBuild.pOrSet = &sCur;
  94741. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  94742. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  94743. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  94744. }else if( pOrTerm->leftCursor==iCur ){
  94745. tempWC.pWInfo = pWC->pWInfo;
  94746. tempWC.pOuter = pWC;
  94747. tempWC.op = TK_AND;
  94748. tempWC.nTerm = 1;
  94749. tempWC.a = pOrTerm;
  94750. sSubBuild.pWC = &tempWC;
  94751. }else{
  94752. continue;
  94753. }
  94754. sCur.n = 0;
  94755. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94756. if( IsVirtual(pItem->pTab) ){
  94757. rc = whereLoopAddVirtual(&sSubBuild);
  94758. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  94759. }else
  94760. #endif
  94761. {
  94762. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  94763. }
  94764. assert( rc==SQLITE_OK || sCur.n==0 );
  94765. if( sCur.n==0 ){
  94766. sSum.n = 0;
  94767. break;
  94768. }else if( once ){
  94769. whereOrMove(&sSum, &sCur);
  94770. once = 0;
  94771. }else{
  94772. whereOrMove(&sPrev, &sSum);
  94773. sSum.n = 0;
  94774. for(i=0; i<sPrev.n; i++){
  94775. for(j=0; j<sCur.n; j++){
  94776. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  94777. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  94778. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  94779. }
  94780. }
  94781. }
  94782. }
  94783. pNew->nLTerm = 1;
  94784. pNew->aLTerm[0] = pTerm;
  94785. pNew->wsFlags = WHERE_MULTI_OR;
  94786. pNew->rSetup = 0;
  94787. pNew->iSortIdx = 0;
  94788. memset(&pNew->u, 0, sizeof(pNew->u));
  94789. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  94790. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  94791. pNew->rRun = sSum.a[i].rRun + 18;
  94792. pNew->nOut = sSum.a[i].nOut;
  94793. pNew->prereq = sSum.a[i].prereq;
  94794. rc = whereLoopInsert(pBuilder, pNew);
  94795. }
  94796. }
  94797. }
  94798. return rc;
  94799. }
  94800. /*
  94801. ** Add all WhereLoop objects for all tables
  94802. */
  94803. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  94804. WhereInfo *pWInfo = pBuilder->pWInfo;
  94805. Bitmask mExtra = 0;
  94806. Bitmask mPrior = 0;
  94807. int iTab;
  94808. SrcList *pTabList = pWInfo->pTabList;
  94809. struct SrcList_item *pItem;
  94810. sqlite3 *db = pWInfo->pParse->db;
  94811. int nTabList = pWInfo->nLevel;
  94812. int rc = SQLITE_OK;
  94813. u8 priorJoinType = 0;
  94814. WhereLoop *pNew;
  94815. /* Loop over the tables in the join, from left to right */
  94816. pNew = pBuilder->pNew;
  94817. whereLoopInit(pNew);
  94818. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  94819. pNew->iTab = iTab;
  94820. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  94821. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  94822. mExtra = mPrior;
  94823. }
  94824. priorJoinType = pItem->jointype;
  94825. if( IsVirtual(pItem->pTab) ){
  94826. rc = whereLoopAddVirtual(pBuilder);
  94827. }else{
  94828. rc = whereLoopAddBtree(pBuilder, mExtra);
  94829. }
  94830. if( rc==SQLITE_OK ){
  94831. rc = whereLoopAddOr(pBuilder, mExtra);
  94832. }
  94833. mPrior |= pNew->maskSelf;
  94834. if( rc || db->mallocFailed ) break;
  94835. }
  94836. whereLoopClear(db, pNew);
  94837. return rc;
  94838. }
  94839. /*
  94840. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  94841. ** parameters) to see if it outputs rows in the requested ORDER BY
  94842. ** (or GROUP BY) without requiring a separate sort operation. Return:
  94843. **
  94844. ** 0: ORDER BY is not satisfied. Sorting required
  94845. ** 1: ORDER BY is satisfied. Omit sorting
  94846. ** -1: Unknown at this time
  94847. **
  94848. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  94849. ** strict. With GROUP BY and DISTINCT the only requirement is that
  94850. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  94851. ** and DISTINT do not require rows to appear in any particular order as long
  94852. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  94853. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  94854. ** pOrderBy terms must be matched in strict left-to-right order.
  94855. */
  94856. static int wherePathSatisfiesOrderBy(
  94857. WhereInfo *pWInfo, /* The WHERE clause */
  94858. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  94859. WherePath *pPath, /* The WherePath to check */
  94860. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  94861. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  94862. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  94863. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  94864. ){
  94865. u8 revSet; /* True if rev is known */
  94866. u8 rev; /* Composite sort order */
  94867. u8 revIdx; /* Index sort order */
  94868. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  94869. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  94870. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  94871. u16 nColumn; /* Number of columns in pIndex */
  94872. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  94873. int iLoop; /* Index of WhereLoop in pPath being processed */
  94874. int i, j; /* Loop counters */
  94875. int iCur; /* Cursor number for current WhereLoop */
  94876. int iColumn; /* A column number within table iCur */
  94877. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  94878. WhereTerm *pTerm; /* A single term of the WHERE clause */
  94879. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  94880. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  94881. Index *pIndex; /* The index associated with pLoop */
  94882. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  94883. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  94884. Bitmask obDone; /* Mask of all ORDER BY terms */
  94885. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  94886. Bitmask ready; /* Mask of inner loops */
  94887. /*
  94888. ** We say the WhereLoop is "one-row" if it generates no more than one
  94889. ** row of output. A WhereLoop is one-row if all of the following are true:
  94890. ** (a) All index columns match with WHERE_COLUMN_EQ.
  94891. ** (b) The index is unique
  94892. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  94893. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  94894. **
  94895. ** We say the WhereLoop is "order-distinct" if the set of columns from
  94896. ** that WhereLoop that are in the ORDER BY clause are different for every
  94897. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  94898. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  94899. ** is not order-distinct. To be order-distinct is not quite the same as being
  94900. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  94901. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  94902. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  94903. **
  94904. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  94905. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  94906. ** automatically order-distinct.
  94907. */
  94908. assert( pOrderBy!=0 );
  94909. /* Sortability of virtual tables is determined by the xBestIndex method
  94910. ** of the virtual table itself */
  94911. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  94912. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  94913. ** no ORDER BY terms */
  94914. return pLast->u.vtab.isOrdered;
  94915. }
  94916. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  94917. nOrderBy = pOrderBy->nExpr;
  94918. testcase( nOrderBy==BMS-1 );
  94919. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  94920. isOrderDistinct = 1;
  94921. obDone = MASKBIT(nOrderBy)-1;
  94922. orderDistinctMask = 0;
  94923. ready = 0;
  94924. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  94925. if( iLoop>0 ) ready |= pLoop->maskSelf;
  94926. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  94927. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  94928. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  94929. /* Mark off any ORDER BY term X that is a column in the table of
  94930. ** the current loop for which there is term in the WHERE
  94931. ** clause of the form X IS NULL or X=? that reference only outer
  94932. ** loops.
  94933. */
  94934. for(i=0; i<nOrderBy; i++){
  94935. if( MASKBIT(i) & obSat ) continue;
  94936. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  94937. if( pOBExpr->op!=TK_COLUMN ) continue;
  94938. if( pOBExpr->iTable!=iCur ) continue;
  94939. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  94940. ~ready, WO_EQ|WO_ISNULL, 0);
  94941. if( pTerm==0 ) continue;
  94942. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  94943. const char *z1, *z2;
  94944. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  94945. if( !pColl ) pColl = db->pDfltColl;
  94946. z1 = pColl->zName;
  94947. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  94948. if( !pColl ) pColl = db->pDfltColl;
  94949. z2 = pColl->zName;
  94950. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  94951. }
  94952. obSat |= MASKBIT(i);
  94953. }
  94954. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  94955. if( pLoop->wsFlags & WHERE_IPK ){
  94956. pIndex = 0;
  94957. nColumn = 0;
  94958. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  94959. return 0;
  94960. }else{
  94961. nColumn = pIndex->nColumn;
  94962. isOrderDistinct = pIndex->onError!=OE_None;
  94963. }
  94964. /* Loop through all columns of the index and deal with the ones
  94965. ** that are not constrained by == or IN.
  94966. */
  94967. rev = revSet = 0;
  94968. distinctColumns = 0;
  94969. for(j=0; j<=nColumn; j++){
  94970. u8 bOnce; /* True to run the ORDER BY search loop */
  94971. /* Skip over == and IS NULL terms */
  94972. if( j<pLoop->u.btree.nEq
  94973. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  94974. ){
  94975. if( i & WO_ISNULL ){
  94976. testcase( isOrderDistinct );
  94977. isOrderDistinct = 0;
  94978. }
  94979. continue;
  94980. }
  94981. /* Get the column number in the table (iColumn) and sort order
  94982. ** (revIdx) for the j-th column of the index.
  94983. */
  94984. if( j<nColumn ){
  94985. /* Normal index columns */
  94986. iColumn = pIndex->aiColumn[j];
  94987. revIdx = pIndex->aSortOrder[j];
  94988. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  94989. }else{
  94990. /* The ROWID column at the end */
  94991. assert( j==nColumn );
  94992. iColumn = -1;
  94993. revIdx = 0;
  94994. }
  94995. /* An unconstrained column that might be NULL means that this
  94996. ** WhereLoop is not well-ordered
  94997. */
  94998. if( isOrderDistinct
  94999. && iColumn>=0
  95000. && j>=pLoop->u.btree.nEq
  95001. && pIndex->pTable->aCol[iColumn].notNull==0
  95002. ){
  95003. isOrderDistinct = 0;
  95004. }
  95005. /* Find the ORDER BY term that corresponds to the j-th column
  95006. ** of the index and and mark that ORDER BY term off
  95007. */
  95008. bOnce = 1;
  95009. isMatch = 0;
  95010. for(i=0; bOnce && i<nOrderBy; i++){
  95011. if( MASKBIT(i) & obSat ) continue;
  95012. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  95013. testcase( wctrlFlags & WHERE_GROUPBY );
  95014. testcase( wctrlFlags & WHERE_DISTINCTBY );
  95015. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  95016. if( pOBExpr->op!=TK_COLUMN ) continue;
  95017. if( pOBExpr->iTable!=iCur ) continue;
  95018. if( pOBExpr->iColumn!=iColumn ) continue;
  95019. if( iColumn>=0 ){
  95020. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  95021. if( !pColl ) pColl = db->pDfltColl;
  95022. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  95023. }
  95024. isMatch = 1;
  95025. break;
  95026. }
  95027. if( isMatch ){
  95028. if( iColumn<0 ){
  95029. testcase( distinctColumns==0 );
  95030. distinctColumns = 1;
  95031. }
  95032. obSat |= MASKBIT(i);
  95033. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  95034. /* Make sure the sort order is compatible in an ORDER BY clause.
  95035. ** Sort order is irrelevant for a GROUP BY clause. */
  95036. if( revSet ){
  95037. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  95038. }else{
  95039. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  95040. if( rev ) *pRevMask |= MASKBIT(iLoop);
  95041. revSet = 1;
  95042. }
  95043. }
  95044. }else{
  95045. /* No match found */
  95046. if( j==0 || j<nColumn ){
  95047. testcase( isOrderDistinct!=0 );
  95048. isOrderDistinct = 0;
  95049. }
  95050. break;
  95051. }
  95052. } /* end Loop over all index columns */
  95053. if( distinctColumns ){
  95054. testcase( isOrderDistinct==0 );
  95055. isOrderDistinct = 1;
  95056. }
  95057. } /* end-if not one-row */
  95058. /* Mark off any other ORDER BY terms that reference pLoop */
  95059. if( isOrderDistinct ){
  95060. orderDistinctMask |= pLoop->maskSelf;
  95061. for(i=0; i<nOrderBy; i++){
  95062. Expr *p;
  95063. if( MASKBIT(i) & obSat ) continue;
  95064. p = pOrderBy->a[i].pExpr;
  95065. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  95066. obSat |= MASKBIT(i);
  95067. }
  95068. }
  95069. }
  95070. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  95071. if( obSat==obDone ) return 1;
  95072. if( !isOrderDistinct ) return 0;
  95073. return -1;
  95074. }
  95075. #ifdef WHERETRACE_ENABLED
  95076. /* For debugging use only: */
  95077. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  95078. static char zName[65];
  95079. int i;
  95080. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  95081. if( pLast ) zName[i++] = pLast->cId;
  95082. zName[i] = 0;
  95083. return zName;
  95084. }
  95085. #endif
  95086. /*
  95087. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  95088. ** attempts to find the lowest cost path that visits each WhereLoop
  95089. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  95090. **
  95091. ** Assume that the total number of output rows that will need to be sorted
  95092. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  95093. ** costs if nRowEst==0.
  95094. **
  95095. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  95096. ** error occurs.
  95097. */
  95098. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  95099. int mxChoice; /* Maximum number of simultaneous paths tracked */
  95100. int nLoop; /* Number of terms in the join */
  95101. Parse *pParse; /* Parsing context */
  95102. sqlite3 *db; /* The database connection */
  95103. int iLoop; /* Loop counter over the terms of the join */
  95104. int ii, jj; /* Loop counters */
  95105. int mxI = 0; /* Index of next entry to replace */
  95106. LogEst rCost; /* Cost of a path */
  95107. LogEst nOut; /* Number of outputs */
  95108. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  95109. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  95110. LogEst rSortCost; /* Cost to do a sort */
  95111. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  95112. WherePath *aFrom; /* All nFrom paths at the previous level */
  95113. WherePath *aTo; /* The nTo best paths at the current level */
  95114. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  95115. WherePath *pTo; /* An element of aTo[] that we are working on */
  95116. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  95117. WhereLoop **pX; /* Used to divy up the pSpace memory */
  95118. char *pSpace; /* Temporary memory used by this routine */
  95119. pParse = pWInfo->pParse;
  95120. db = pParse->db;
  95121. nLoop = pWInfo->nLevel;
  95122. /* TUNING: For simple queries, only the best path is tracked.
  95123. ** For 2-way joins, the 5 best paths are followed.
  95124. ** For joins of 3 or more tables, track the 10 best paths */
  95125. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  95126. assert( nLoop<=pWInfo->pTabList->nSrc );
  95127. WHERETRACE(0x002, ("---- begin solver\n"));
  95128. /* Allocate and initialize space for aTo and aFrom */
  95129. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  95130. pSpace = sqlite3DbMallocRaw(db, ii);
  95131. if( pSpace==0 ) return SQLITE_NOMEM;
  95132. aTo = (WherePath*)pSpace;
  95133. aFrom = aTo+mxChoice;
  95134. memset(aFrom, 0, sizeof(aFrom[0]));
  95135. pX = (WhereLoop**)(aFrom+mxChoice);
  95136. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  95137. pFrom->aLoop = pX;
  95138. }
  95139. /* Seed the search with a single WherePath containing zero WhereLoops.
  95140. **
  95141. ** TUNING: Do not let the number of iterations go above 25. If the cost
  95142. ** of computing an automatic index is not paid back within the first 25
  95143. ** rows, then do not use the automatic index. */
  95144. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  95145. nFrom = 1;
  95146. /* Precompute the cost of sorting the final result set, if the caller
  95147. ** to sqlite3WhereBegin() was concerned about sorting */
  95148. rSortCost = 0;
  95149. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  95150. aFrom[0].isOrderedValid = 1;
  95151. }else{
  95152. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  95153. ** number of output rows. The 48 is the expected size of a row to sort.
  95154. ** FIXME: compute a better estimate of the 48 multiplier based on the
  95155. ** result set expressions. */
  95156. rSortCost = nRowEst + estLog(nRowEst);
  95157. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  95158. }
  95159. /* Compute successively longer WherePaths using the previous generation
  95160. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  95161. ** best paths at each generation */
  95162. for(iLoop=0; iLoop<nLoop; iLoop++){
  95163. nTo = 0;
  95164. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  95165. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  95166. Bitmask maskNew;
  95167. Bitmask revMask = 0;
  95168. u8 isOrderedValid = pFrom->isOrderedValid;
  95169. u8 isOrdered = pFrom->isOrdered;
  95170. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  95171. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  95172. /* At this point, pWLoop is a candidate to be the next loop.
  95173. ** Compute its cost */
  95174. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  95175. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  95176. nOut = pFrom->nRow + pWLoop->nOut;
  95177. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  95178. if( !isOrderedValid ){
  95179. switch( wherePathSatisfiesOrderBy(pWInfo,
  95180. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  95181. iLoop, pWLoop, &revMask) ){
  95182. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  95183. isOrdered = 1;
  95184. isOrderedValid = 1;
  95185. break;
  95186. case 0: /* No. pFrom+pWLoop will require a separate sort */
  95187. isOrdered = 0;
  95188. isOrderedValid = 1;
  95189. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  95190. break;
  95191. default: /* Cannot tell yet. Try again on the next iteration */
  95192. break;
  95193. }
  95194. }else{
  95195. revMask = pFrom->revLoop;
  95196. }
  95197. /* Check to see if pWLoop should be added to the mxChoice best so far */
  95198. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  95199. if( pTo->maskLoop==maskNew
  95200. && pTo->isOrderedValid==isOrderedValid
  95201. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  95202. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  95203. ){
  95204. testcase( jj==nTo-1 );
  95205. break;
  95206. }
  95207. }
  95208. if( jj>=nTo ){
  95209. if( nTo>=mxChoice && rCost>=mxCost ){
  95210. #ifdef WHERETRACE_ENABLED
  95211. if( sqlite3WhereTrace&0x4 ){
  95212. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  95213. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95214. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95215. }
  95216. #endif
  95217. continue;
  95218. }
  95219. /* Add a new Path to the aTo[] set */
  95220. if( nTo<mxChoice ){
  95221. /* Increase the size of the aTo set by one */
  95222. jj = nTo++;
  95223. }else{
  95224. /* New path replaces the prior worst to keep count below mxChoice */
  95225. jj = mxI;
  95226. }
  95227. pTo = &aTo[jj];
  95228. #ifdef WHERETRACE_ENABLED
  95229. if( sqlite3WhereTrace&0x4 ){
  95230. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  95231. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95232. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95233. }
  95234. #endif
  95235. }else{
  95236. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  95237. #ifdef WHERETRACE_ENABLED
  95238. if( sqlite3WhereTrace&0x4 ){
  95239. sqlite3DebugPrintf(
  95240. "Skip %s cost=%-3d,%3d order=%c",
  95241. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95242. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95243. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  95244. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95245. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95246. }
  95247. #endif
  95248. testcase( pTo->rCost==rCost );
  95249. continue;
  95250. }
  95251. testcase( pTo->rCost==rCost+1 );
  95252. /* A new and better score for a previously created equivalent path */
  95253. #ifdef WHERETRACE_ENABLED
  95254. if( sqlite3WhereTrace&0x4 ){
  95255. sqlite3DebugPrintf(
  95256. "Update %s cost=%-3d,%3d order=%c",
  95257. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  95258. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  95259. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  95260. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95261. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95262. }
  95263. #endif
  95264. }
  95265. /* pWLoop is a winner. Add it to the set of best so far */
  95266. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  95267. pTo->revLoop = revMask;
  95268. pTo->nRow = nOut;
  95269. pTo->rCost = rCost;
  95270. pTo->isOrderedValid = isOrderedValid;
  95271. pTo->isOrdered = isOrdered;
  95272. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  95273. pTo->aLoop[iLoop] = pWLoop;
  95274. if( nTo>=mxChoice ){
  95275. mxI = 0;
  95276. mxCost = aTo[0].rCost;
  95277. mxOut = aTo[0].nRow;
  95278. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  95279. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  95280. mxCost = pTo->rCost;
  95281. mxOut = pTo->nRow;
  95282. mxI = jj;
  95283. }
  95284. }
  95285. }
  95286. }
  95287. }
  95288. #ifdef WHERETRACE_ENABLED
  95289. if( sqlite3WhereTrace>=2 ){
  95290. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  95291. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  95292. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  95293. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  95294. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  95295. if( pTo->isOrderedValid && pTo->isOrdered ){
  95296. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  95297. }else{
  95298. sqlite3DebugPrintf("\n");
  95299. }
  95300. }
  95301. }
  95302. #endif
  95303. /* Swap the roles of aFrom and aTo for the next generation */
  95304. pFrom = aTo;
  95305. aTo = aFrom;
  95306. aFrom = pFrom;
  95307. nFrom = nTo;
  95308. }
  95309. if( nFrom==0 ){
  95310. sqlite3ErrorMsg(pParse, "no query solution");
  95311. sqlite3DbFree(db, pSpace);
  95312. return SQLITE_ERROR;
  95313. }
  95314. /* Find the lowest cost path. pFrom will be left pointing to that path */
  95315. pFrom = aFrom;
  95316. for(ii=1; ii<nFrom; ii++){
  95317. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  95318. }
  95319. assert( pWInfo->nLevel==nLoop );
  95320. /* Load the lowest cost path into pWInfo */
  95321. for(iLoop=0; iLoop<nLoop; iLoop++){
  95322. WhereLevel *pLevel = pWInfo->a + iLoop;
  95323. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  95324. pLevel->iFrom = pWLoop->iTab;
  95325. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  95326. }
  95327. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  95328. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  95329. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  95330. && nRowEst
  95331. ){
  95332. Bitmask notUsed;
  95333. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  95334. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  95335. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  95336. }
  95337. if( pFrom->isOrdered ){
  95338. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  95339. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  95340. }else{
  95341. pWInfo->bOBSat = 1;
  95342. pWInfo->revMask = pFrom->revLoop;
  95343. }
  95344. }
  95345. pWInfo->nRowOut = pFrom->nRow;
  95346. /* Free temporary memory and return success */
  95347. sqlite3DbFree(db, pSpace);
  95348. return SQLITE_OK;
  95349. }
  95350. /*
  95351. ** Most queries use only a single table (they are not joins) and have
  95352. ** simple == constraints against indexed fields. This routine attempts
  95353. ** to plan those simple cases using much less ceremony than the
  95354. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  95355. ** times for the common case.
  95356. **
  95357. ** Return non-zero on success, if this query can be handled by this
  95358. ** no-frills query planner. Return zero if this query needs the
  95359. ** general-purpose query planner.
  95360. */
  95361. static int whereShortCut(WhereLoopBuilder *pBuilder){
  95362. WhereInfo *pWInfo;
  95363. struct SrcList_item *pItem;
  95364. WhereClause *pWC;
  95365. WhereTerm *pTerm;
  95366. WhereLoop *pLoop;
  95367. int iCur;
  95368. int j;
  95369. Table *pTab;
  95370. Index *pIdx;
  95371. pWInfo = pBuilder->pWInfo;
  95372. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  95373. assert( pWInfo->pTabList->nSrc>=1 );
  95374. pItem = pWInfo->pTabList->a;
  95375. pTab = pItem->pTab;
  95376. if( IsVirtual(pTab) ) return 0;
  95377. if( pItem->zIndex ) return 0;
  95378. iCur = pItem->iCursor;
  95379. pWC = &pWInfo->sWC;
  95380. pLoop = pBuilder->pNew;
  95381. pLoop->wsFlags = 0;
  95382. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  95383. if( pTerm ){
  95384. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  95385. pLoop->aLTerm[0] = pTerm;
  95386. pLoop->nLTerm = 1;
  95387. pLoop->u.btree.nEq = 1;
  95388. /* TUNING: Cost of a rowid lookup is 10 */
  95389. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  95390. }else{
  95391. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95392. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  95393. assert( ArraySize(pLoop->aLTermSpace)==4 );
  95394. if( pIdx->onError==OE_None
  95395. || pIdx->pPartIdxWhere!=0
  95396. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  95397. ) continue;
  95398. for(j=0; j<pIdx->nColumn; j++){
  95399. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  95400. if( pTerm==0 ) break;
  95401. pLoop->aLTerm[j] = pTerm;
  95402. }
  95403. if( j!=pIdx->nColumn ) continue;
  95404. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  95405. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  95406. pLoop->wsFlags |= WHERE_IDX_ONLY;
  95407. }
  95408. pLoop->nLTerm = j;
  95409. pLoop->u.btree.nEq = j;
  95410. pLoop->u.btree.pIndex = pIdx;
  95411. /* TUNING: Cost of a unique index lookup is 15 */
  95412. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  95413. break;
  95414. }
  95415. }
  95416. if( pLoop->wsFlags ){
  95417. pLoop->nOut = (LogEst)1;
  95418. pWInfo->a[0].pWLoop = pLoop;
  95419. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  95420. pWInfo->a[0].iTabCur = iCur;
  95421. pWInfo->nRowOut = 1;
  95422. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  95423. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  95424. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95425. }
  95426. #ifdef SQLITE_DEBUG
  95427. pLoop->cId = '0';
  95428. #endif
  95429. return 1;
  95430. }
  95431. return 0;
  95432. }
  95433. /*
  95434. ** Generate the beginning of the loop used for WHERE clause processing.
  95435. ** The return value is a pointer to an opaque structure that contains
  95436. ** information needed to terminate the loop. Later, the calling routine
  95437. ** should invoke sqlite3WhereEnd() with the return value of this function
  95438. ** in order to complete the WHERE clause processing.
  95439. **
  95440. ** If an error occurs, this routine returns NULL.
  95441. **
  95442. ** The basic idea is to do a nested loop, one loop for each table in
  95443. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  95444. ** same as a SELECT with only a single table in the FROM clause.) For
  95445. ** example, if the SQL is this:
  95446. **
  95447. ** SELECT * FROM t1, t2, t3 WHERE ...;
  95448. **
  95449. ** Then the code generated is conceptually like the following:
  95450. **
  95451. ** foreach row1 in t1 do \ Code generated
  95452. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  95453. ** foreach row3 in t3 do /
  95454. ** ...
  95455. ** end \ Code generated
  95456. ** end |-- by sqlite3WhereEnd()
  95457. ** end /
  95458. **
  95459. ** Note that the loops might not be nested in the order in which they
  95460. ** appear in the FROM clause if a different order is better able to make
  95461. ** use of indices. Note also that when the IN operator appears in
  95462. ** the WHERE clause, it might result in additional nested loops for
  95463. ** scanning through all values on the right-hand side of the IN.
  95464. **
  95465. ** There are Btree cursors associated with each table. t1 uses cursor
  95466. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  95467. ** And so forth. This routine generates code to open those VDBE cursors
  95468. ** and sqlite3WhereEnd() generates the code to close them.
  95469. **
  95470. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  95471. ** in pTabList pointing at their appropriate entries. The [...] code
  95472. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  95473. ** data from the various tables of the loop.
  95474. **
  95475. ** If the WHERE clause is empty, the foreach loops must each scan their
  95476. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  95477. ** the tables have indices and there are terms in the WHERE clause that
  95478. ** refer to those indices, a complete table scan can be avoided and the
  95479. ** code will run much faster. Most of the work of this routine is checking
  95480. ** to see if there are indices that can be used to speed up the loop.
  95481. **
  95482. ** Terms of the WHERE clause are also used to limit which rows actually
  95483. ** make it to the "..." in the middle of the loop. After each "foreach",
  95484. ** terms of the WHERE clause that use only terms in that loop and outer
  95485. ** loops are evaluated and if false a jump is made around all subsequent
  95486. ** inner loops (or around the "..." if the test occurs within the inner-
  95487. ** most loop)
  95488. **
  95489. ** OUTER JOINS
  95490. **
  95491. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  95492. **
  95493. ** foreach row1 in t1 do
  95494. ** flag = 0
  95495. ** foreach row2 in t2 do
  95496. ** start:
  95497. ** ...
  95498. ** flag = 1
  95499. ** end
  95500. ** if flag==0 then
  95501. ** move the row2 cursor to a null row
  95502. ** goto start
  95503. ** fi
  95504. ** end
  95505. **
  95506. ** ORDER BY CLAUSE PROCESSING
  95507. **
  95508. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  95509. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  95510. ** if there is one. If there is no ORDER BY clause or if this routine
  95511. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  95512. */
  95513. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  95514. Parse *pParse, /* The parser context */
  95515. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  95516. Expr *pWhere, /* The WHERE clause */
  95517. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  95518. ExprList *pResultSet, /* Result set of the query */
  95519. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  95520. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  95521. ){
  95522. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  95523. int nTabList; /* Number of elements in pTabList */
  95524. WhereInfo *pWInfo; /* Will become the return value of this function */
  95525. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  95526. Bitmask notReady; /* Cursors that are not yet positioned */
  95527. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  95528. WhereMaskSet *pMaskSet; /* The expression mask set */
  95529. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  95530. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  95531. int ii; /* Loop counter */
  95532. sqlite3 *db; /* Database connection */
  95533. int rc; /* Return code */
  95534. /* Variable initialization */
  95535. db = pParse->db;
  95536. memset(&sWLB, 0, sizeof(sWLB));
  95537. sWLB.pOrderBy = pOrderBy;
  95538. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  95539. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  95540. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  95541. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  95542. }
  95543. /* The number of tables in the FROM clause is limited by the number of
  95544. ** bits in a Bitmask
  95545. */
  95546. testcase( pTabList->nSrc==BMS );
  95547. if( pTabList->nSrc>BMS ){
  95548. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  95549. return 0;
  95550. }
  95551. /* This function normally generates a nested loop for all tables in
  95552. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  95553. ** only generate code for the first table in pTabList and assume that
  95554. ** any cursors associated with subsequent tables are uninitialized.
  95555. */
  95556. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  95557. /* Allocate and initialize the WhereInfo structure that will become the
  95558. ** return value. A single allocation is used to store the WhereInfo
  95559. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  95560. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  95561. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  95562. ** some architectures. Hence the ROUND8() below.
  95563. */
  95564. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  95565. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  95566. if( db->mallocFailed ){
  95567. sqlite3DbFree(db, pWInfo);
  95568. pWInfo = 0;
  95569. goto whereBeginError;
  95570. }
  95571. pWInfo->nLevel = nTabList;
  95572. pWInfo->pParse = pParse;
  95573. pWInfo->pTabList = pTabList;
  95574. pWInfo->pOrderBy = pOrderBy;
  95575. pWInfo->pResultSet = pResultSet;
  95576. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  95577. pWInfo->wctrlFlags = wctrlFlags;
  95578. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  95579. pMaskSet = &pWInfo->sMaskSet;
  95580. sWLB.pWInfo = pWInfo;
  95581. sWLB.pWC = &pWInfo->sWC;
  95582. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  95583. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  95584. whereLoopInit(sWLB.pNew);
  95585. #ifdef SQLITE_DEBUG
  95586. sWLB.pNew->cId = '*';
  95587. #endif
  95588. /* Split the WHERE clause into separate subexpressions where each
  95589. ** subexpression is separated by an AND operator.
  95590. */
  95591. initMaskSet(pMaskSet);
  95592. whereClauseInit(&pWInfo->sWC, pWInfo);
  95593. sqlite3ExprCodeConstants(pParse, pWhere);
  95594. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  95595. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  95596. /* Special case: a WHERE clause that is constant. Evaluate the
  95597. ** expression and either jump over all of the code or fall thru.
  95598. */
  95599. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  95600. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  95601. pWhere = 0;
  95602. }
  95603. /* Special case: No FROM clause
  95604. */
  95605. if( nTabList==0 ){
  95606. if( pOrderBy ) pWInfo->bOBSat = 1;
  95607. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  95608. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95609. }
  95610. }
  95611. /* Assign a bit from the bitmask to every term in the FROM clause.
  95612. **
  95613. ** When assigning bitmask values to FROM clause cursors, it must be
  95614. ** the case that if X is the bitmask for the N-th FROM clause term then
  95615. ** the bitmask for all FROM clause terms to the left of the N-th term
  95616. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  95617. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  95618. ** of the join. Subtracting one from the right table bitmask gives a
  95619. ** bitmask for all tables to the left of the join. Knowing the bitmask
  95620. ** for all tables to the left of a left join is important. Ticket #3015.
  95621. **
  95622. ** Note that bitmasks are created for all pTabList->nSrc tables in
  95623. ** pTabList, not just the first nTabList tables. nTabList is normally
  95624. ** equal to pTabList->nSrc but might be shortened to 1 if the
  95625. ** WHERE_ONETABLE_ONLY flag is set.
  95626. */
  95627. for(ii=0; ii<pTabList->nSrc; ii++){
  95628. createMask(pMaskSet, pTabList->a[ii].iCursor);
  95629. }
  95630. #ifndef NDEBUG
  95631. {
  95632. Bitmask toTheLeft = 0;
  95633. for(ii=0; ii<pTabList->nSrc; ii++){
  95634. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  95635. assert( (m-1)==toTheLeft );
  95636. toTheLeft |= m;
  95637. }
  95638. }
  95639. #endif
  95640. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  95641. ** add new virtual terms onto the end of the WHERE clause. We do not
  95642. ** want to analyze these virtual terms, so start analyzing at the end
  95643. ** and work forward so that the added virtual terms are never processed.
  95644. */
  95645. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  95646. if( db->mallocFailed ){
  95647. goto whereBeginError;
  95648. }
  95649. /* If the ORDER BY (or GROUP BY) clause contains references to general
  95650. ** expressions, then we won't be able to satisfy it using indices, so
  95651. ** go ahead and disable it now.
  95652. */
  95653. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  95654. for(ii=0; ii<pOrderBy->nExpr; ii++){
  95655. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  95656. if( pExpr->op!=TK_COLUMN ){
  95657. pWInfo->pOrderBy = pOrderBy = 0;
  95658. break;
  95659. }else if( pExpr->iColumn<0 ){
  95660. break;
  95661. }
  95662. }
  95663. }
  95664. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  95665. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  95666. /* The DISTINCT marking is pointless. Ignore it. */
  95667. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  95668. }else if( pOrderBy==0 ){
  95669. /* Try to ORDER BY the result set to make distinct processing easier */
  95670. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  95671. pWInfo->pOrderBy = pResultSet;
  95672. }
  95673. }
  95674. /* Construct the WhereLoop objects */
  95675. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  95676. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  95677. rc = whereLoopAddAll(&sWLB);
  95678. if( rc ) goto whereBeginError;
  95679. /* Display all of the WhereLoop objects if wheretrace is enabled */
  95680. #ifdef WHERETRACE_ENABLED
  95681. if( sqlite3WhereTrace ){
  95682. WhereLoop *p;
  95683. int i;
  95684. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  95685. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  95686. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  95687. p->cId = zLabel[i%sizeof(zLabel)];
  95688. whereLoopPrint(p, pTabList);
  95689. }
  95690. }
  95691. #endif
  95692. wherePathSolver(pWInfo, 0);
  95693. if( db->mallocFailed ) goto whereBeginError;
  95694. if( pWInfo->pOrderBy ){
  95695. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  95696. if( db->mallocFailed ) goto whereBeginError;
  95697. }
  95698. }
  95699. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  95700. pWInfo->revMask = (Bitmask)(-1);
  95701. }
  95702. if( pParse->nErr || NEVER(db->mallocFailed) ){
  95703. goto whereBeginError;
  95704. }
  95705. #ifdef WHERETRACE_ENABLED
  95706. if( sqlite3WhereTrace ){
  95707. int ii;
  95708. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  95709. if( pWInfo->bOBSat ){
  95710. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  95711. }
  95712. switch( pWInfo->eDistinct ){
  95713. case WHERE_DISTINCT_UNIQUE: {
  95714. sqlite3DebugPrintf(" DISTINCT=unique");
  95715. break;
  95716. }
  95717. case WHERE_DISTINCT_ORDERED: {
  95718. sqlite3DebugPrintf(" DISTINCT=ordered");
  95719. break;
  95720. }
  95721. case WHERE_DISTINCT_UNORDERED: {
  95722. sqlite3DebugPrintf(" DISTINCT=unordered");
  95723. break;
  95724. }
  95725. }
  95726. sqlite3DebugPrintf("\n");
  95727. for(ii=0; ii<pWInfo->nLevel; ii++){
  95728. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  95729. }
  95730. }
  95731. #endif
  95732. /* Attempt to omit tables from the join that do not effect the result */
  95733. if( pWInfo->nLevel>=2
  95734. && pResultSet!=0
  95735. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  95736. ){
  95737. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  95738. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  95739. while( pWInfo->nLevel>=2 ){
  95740. WhereTerm *pTerm, *pEnd;
  95741. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  95742. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  95743. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  95744. && (pLoop->wsFlags & WHERE_ONEROW)==0
  95745. ){
  95746. break;
  95747. }
  95748. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  95749. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  95750. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  95751. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  95752. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  95753. ){
  95754. break;
  95755. }
  95756. }
  95757. if( pTerm<pEnd ) break;
  95758. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  95759. pWInfo->nLevel--;
  95760. nTabList--;
  95761. }
  95762. }
  95763. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  95764. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  95765. /* If the caller is an UPDATE or DELETE statement that is requesting
  95766. ** to use a one-pass algorithm, determine if this is appropriate.
  95767. ** The one-pass algorithm only works if the WHERE clause constrains
  95768. ** the statement to update a single row.
  95769. */
  95770. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  95771. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  95772. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  95773. pWInfo->okOnePass = 1;
  95774. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  95775. }
  95776. /* Open all tables in the pTabList and any indices selected for
  95777. ** searching those tables.
  95778. */
  95779. notReady = ~(Bitmask)0;
  95780. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  95781. Table *pTab; /* Table to open */
  95782. int iDb; /* Index of database containing table/index */
  95783. struct SrcList_item *pTabItem;
  95784. pTabItem = &pTabList->a[pLevel->iFrom];
  95785. pTab = pTabItem->pTab;
  95786. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95787. pLoop = pLevel->pWLoop;
  95788. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  95789. /* Do nothing */
  95790. }else
  95791. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95792. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  95793. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  95794. int iCur = pTabItem->iCursor;
  95795. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  95796. }else if( IsVirtual(pTab) ){
  95797. /* noop */
  95798. }else
  95799. #endif
  95800. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  95801. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  95802. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  95803. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  95804. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  95805. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  95806. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  95807. Bitmask b = pTabItem->colUsed;
  95808. int n = 0;
  95809. for(; b; b=b>>1, n++){}
  95810. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  95811. SQLITE_INT_TO_PTR(n), P4_INT32);
  95812. assert( n<=pTab->nCol );
  95813. }
  95814. }else{
  95815. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95816. }
  95817. if( pLoop->wsFlags & WHERE_INDEXED ){
  95818. Index *pIx = pLoop->u.btree.pIndex;
  95819. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  95820. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  95821. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  95822. assert( pIx->pSchema==pTab->pSchema );
  95823. assert( iIndexCur>=0 );
  95824. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  95825. (char*)pKey, P4_KEYINFO_HANDOFF);
  95826. VdbeComment((v, "%s", pIx->zName));
  95827. }
  95828. sqlite3CodeVerifySchema(pParse, iDb);
  95829. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  95830. }
  95831. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  95832. if( db->mallocFailed ) goto whereBeginError;
  95833. /* Generate the code to do the search. Each iteration of the for
  95834. ** loop below generates code for a single nested loop of the VM
  95835. ** program.
  95836. */
  95837. notReady = ~(Bitmask)0;
  95838. for(ii=0; ii<nTabList; ii++){
  95839. pLevel = &pWInfo->a[ii];
  95840. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  95841. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  95842. constructAutomaticIndex(pParse, &pWInfo->sWC,
  95843. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  95844. if( db->mallocFailed ) goto whereBeginError;
  95845. }
  95846. #endif
  95847. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  95848. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  95849. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  95850. pWInfo->iContinue = pLevel->addrCont;
  95851. }
  95852. /* Done. */
  95853. return pWInfo;
  95854. /* Jump here if malloc fails */
  95855. whereBeginError:
  95856. if( pWInfo ){
  95857. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95858. whereInfoFree(db, pWInfo);
  95859. }
  95860. return 0;
  95861. }
  95862. /*
  95863. ** Generate the end of the WHERE loop. See comments on
  95864. ** sqlite3WhereBegin() for additional information.
  95865. */
  95866. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  95867. Parse *pParse = pWInfo->pParse;
  95868. Vdbe *v = pParse->pVdbe;
  95869. int i;
  95870. WhereLevel *pLevel;
  95871. WhereLoop *pLoop;
  95872. SrcList *pTabList = pWInfo->pTabList;
  95873. sqlite3 *db = pParse->db;
  95874. /* Generate loop termination code.
  95875. */
  95876. sqlite3ExprCacheClear(pParse);
  95877. for(i=pWInfo->nLevel-1; i>=0; i--){
  95878. pLevel = &pWInfo->a[i];
  95879. pLoop = pLevel->pWLoop;
  95880. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  95881. if( pLevel->op!=OP_Noop ){
  95882. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  95883. sqlite3VdbeChangeP5(v, pLevel->p5);
  95884. }
  95885. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  95886. struct InLoop *pIn;
  95887. int j;
  95888. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  95889. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  95890. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  95891. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  95892. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  95893. }
  95894. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  95895. }
  95896. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  95897. if( pLevel->iLeftJoin ){
  95898. int addr;
  95899. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  95900. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  95901. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  95902. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  95903. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  95904. }
  95905. if( pLoop->wsFlags & WHERE_INDEXED ){
  95906. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  95907. }
  95908. if( pLevel->op==OP_Return ){
  95909. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  95910. }else{
  95911. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  95912. }
  95913. sqlite3VdbeJumpHere(v, addr);
  95914. }
  95915. }
  95916. /* The "break" point is here, just past the end of the outer loop.
  95917. ** Set it.
  95918. */
  95919. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  95920. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  95921. */
  95922. assert( pWInfo->nLevel<=pTabList->nSrc );
  95923. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  95924. Index *pIdx = 0;
  95925. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  95926. Table *pTab = pTabItem->pTab;
  95927. assert( pTab!=0 );
  95928. pLoop = pLevel->pWLoop;
  95929. if( (pTab->tabFlags & TF_Ephemeral)==0
  95930. && pTab->pSelect==0
  95931. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  95932. ){
  95933. int ws = pLoop->wsFlags;
  95934. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  95935. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  95936. }
  95937. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  95938. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  95939. }
  95940. }
  95941. /* If this scan uses an index, make VDBE code substitutions to read data
  95942. ** from the index instead of from the table where possible. In some cases
  95943. ** this optimization prevents the table from ever being read, which can
  95944. ** yield a significant performance boost.
  95945. **
  95946. ** Calls to the code generator in between sqlite3WhereBegin and
  95947. ** sqlite3WhereEnd will have created code that references the table
  95948. ** directly. This loop scans all that code looking for opcodes
  95949. ** that reference the table and converts them into opcodes that
  95950. ** reference the index.
  95951. */
  95952. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  95953. pIdx = pLoop->u.btree.pIndex;
  95954. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  95955. pIdx = pLevel->u.pCovidx;
  95956. }
  95957. if( pIdx && !db->mallocFailed ){
  95958. int k, j, last;
  95959. VdbeOp *pOp;
  95960. last = sqlite3VdbeCurrentAddr(v);
  95961. k = pLevel->addrBody;
  95962. pOp = sqlite3VdbeGetOp(v, k);
  95963. for(; k<last; k++, pOp++){
  95964. if( pOp->p1!=pLevel->iTabCur ) continue;
  95965. if( pOp->opcode==OP_Column ){
  95966. for(j=0; j<pIdx->nColumn; j++){
  95967. if( pOp->p2==pIdx->aiColumn[j] ){
  95968. pOp->p2 = j;
  95969. pOp->p1 = pLevel->iIdxCur;
  95970. break;
  95971. }
  95972. }
  95973. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  95974. }else if( pOp->opcode==OP_Rowid ){
  95975. pOp->p1 = pLevel->iIdxCur;
  95976. pOp->opcode = OP_IdxRowid;
  95977. }
  95978. }
  95979. }
  95980. }
  95981. /* Final cleanup
  95982. */
  95983. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95984. whereInfoFree(db, pWInfo);
  95985. return;
  95986. }
  95987. /************** End of where.c ***********************************************/
  95988. /************** Begin file parse.c *******************************************/
  95989. /* Driver template for the LEMON parser generator.
  95990. ** The author disclaims copyright to this source code.
  95991. **
  95992. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  95993. ** The only modifications are the addition of a couple of NEVER()
  95994. ** macros to disable tests that are needed in the case of a general
  95995. ** LALR(1) grammar but which are always false in the
  95996. ** specific grammar used by SQLite.
  95997. */
  95998. /* First off, code is included that follows the "include" declaration
  95999. ** in the input grammar file. */
  96000. /* #include <stdio.h> */
  96001. /*
  96002. ** Disable all error recovery processing in the parser push-down
  96003. ** automaton.
  96004. */
  96005. #define YYNOERRORRECOVERY 1
  96006. /*
  96007. ** Make yytestcase() the same as testcase()
  96008. */
  96009. #define yytestcase(X) testcase(X)
  96010. /*
  96011. ** An instance of this structure holds information about the
  96012. ** LIMIT clause of a SELECT statement.
  96013. */
  96014. struct LimitVal {
  96015. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  96016. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  96017. };
  96018. /*
  96019. ** An instance of this structure is used to store the LIKE,
  96020. ** GLOB, NOT LIKE, and NOT GLOB operators.
  96021. */
  96022. struct LikeOp {
  96023. Token eOperator; /* "like" or "glob" or "regexp" */
  96024. int bNot; /* True if the NOT keyword is present */
  96025. };
  96026. /*
  96027. ** An instance of the following structure describes the event of a
  96028. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  96029. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  96030. **
  96031. ** UPDATE ON (a,b,c)
  96032. **
  96033. ** Then the "b" IdList records the list "a,b,c".
  96034. */
  96035. struct TrigEvent { int a; IdList * b; };
  96036. /*
  96037. ** An instance of this structure holds the ATTACH key and the key type.
  96038. */
  96039. struct AttachKey { int type; Token key; };
  96040. /*
  96041. ** One or more VALUES claues
  96042. */
  96043. struct ValueList {
  96044. ExprList *pList;
  96045. Select *pSelect;
  96046. };
  96047. /* This is a utility routine used to set the ExprSpan.zStart and
  96048. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  96049. ** range of text beginning with pStart and going to the end of pEnd.
  96050. */
  96051. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  96052. pOut->zStart = pStart->z;
  96053. pOut->zEnd = &pEnd->z[pEnd->n];
  96054. }
  96055. /* Construct a new Expr object from a single identifier. Use the
  96056. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  96057. ** that created the expression.
  96058. */
  96059. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  96060. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  96061. pOut->zStart = pValue->z;
  96062. pOut->zEnd = &pValue->z[pValue->n];
  96063. }
  96064. /* This routine constructs a binary expression node out of two ExprSpan
  96065. ** objects and uses the result to populate a new ExprSpan object.
  96066. */
  96067. static void spanBinaryExpr(
  96068. ExprSpan *pOut, /* Write the result here */
  96069. Parse *pParse, /* The parsing context. Errors accumulate here */
  96070. int op, /* The binary operation */
  96071. ExprSpan *pLeft, /* The left operand */
  96072. ExprSpan *pRight /* The right operand */
  96073. ){
  96074. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  96075. pOut->zStart = pLeft->zStart;
  96076. pOut->zEnd = pRight->zEnd;
  96077. }
  96078. /* Construct an expression node for a unary postfix operator
  96079. */
  96080. static void spanUnaryPostfix(
  96081. ExprSpan *pOut, /* Write the new expression node here */
  96082. Parse *pParse, /* Parsing context to record errors */
  96083. int op, /* The operator */
  96084. ExprSpan *pOperand, /* The operand */
  96085. Token *pPostOp /* The operand token for setting the span */
  96086. ){
  96087. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  96088. pOut->zStart = pOperand->zStart;
  96089. pOut->zEnd = &pPostOp->z[pPostOp->n];
  96090. }
  96091. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  96092. ** unary TK_ISNULL or TK_NOTNULL expression. */
  96093. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  96094. sqlite3 *db = pParse->db;
  96095. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  96096. pA->op = (u8)op;
  96097. sqlite3ExprDelete(db, pA->pRight);
  96098. pA->pRight = 0;
  96099. }
  96100. }
  96101. /* Construct an expression node for a unary prefix operator
  96102. */
  96103. static void spanUnaryPrefix(
  96104. ExprSpan *pOut, /* Write the new expression node here */
  96105. Parse *pParse, /* Parsing context to record errors */
  96106. int op, /* The operator */
  96107. ExprSpan *pOperand, /* The operand */
  96108. Token *pPreOp /* The operand token for setting the span */
  96109. ){
  96110. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  96111. pOut->zStart = pPreOp->z;
  96112. pOut->zEnd = pOperand->zEnd;
  96113. }
  96114. /* Next is all token values, in a form suitable for use by makeheaders.
  96115. ** This section will be null unless lemon is run with the -m switch.
  96116. */
  96117. /*
  96118. ** These constants (all generated automatically by the parser generator)
  96119. ** specify the various kinds of tokens (terminals) that the parser
  96120. ** understands.
  96121. **
  96122. ** Each symbol here is a terminal symbol in the grammar.
  96123. */
  96124. /* Make sure the INTERFACE macro is defined.
  96125. */
  96126. #ifndef INTERFACE
  96127. # define INTERFACE 1
  96128. #endif
  96129. /* The next thing included is series of defines which control
  96130. ** various aspects of the generated parser.
  96131. ** YYCODETYPE is the data type used for storing terminal
  96132. ** and nonterminal numbers. "unsigned char" is
  96133. ** used if there are fewer than 250 terminals
  96134. ** and nonterminals. "int" is used otherwise.
  96135. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  96136. ** to no legal terminal or nonterminal number. This
  96137. ** number is used to fill in empty slots of the hash
  96138. ** table.
  96139. ** YYFALLBACK If defined, this indicates that one or more tokens
  96140. ** have fall-back values which should be used if the
  96141. ** original value of the token will not parse.
  96142. ** YYACTIONTYPE is the data type used for storing terminal
  96143. ** and nonterminal numbers. "unsigned char" is
  96144. ** used if there are fewer than 250 rules and
  96145. ** states combined. "int" is used otherwise.
  96146. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  96147. ** directly to the parser from the tokenizer.
  96148. ** YYMINORTYPE is the data type used for all minor tokens.
  96149. ** This is typically a union of many types, one of
  96150. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  96151. ** for base tokens is called "yy0".
  96152. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  96153. ** zero the stack is dynamically sized using realloc()
  96154. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  96155. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  96156. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  96157. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  96158. ** YYNSTATE the combined number of states.
  96159. ** YYNRULE the number of rules in the grammar
  96160. ** YYERRORSYMBOL is the code number of the error symbol. If not
  96161. ** defined, then do no error processing.
  96162. */
  96163. #define YYCODETYPE unsigned char
  96164. #define YYNOCODE 251
  96165. #define YYACTIONTYPE unsigned short int
  96166. #define YYWILDCARD 67
  96167. #define sqlite3ParserTOKENTYPE Token
  96168. typedef union {
  96169. int yyinit;
  96170. sqlite3ParserTOKENTYPE yy0;
  96171. struct LimitVal yy64;
  96172. Expr* yy122;
  96173. Select* yy159;
  96174. IdList* yy180;
  96175. struct {int value; int mask;} yy207;
  96176. u8 yy258;
  96177. u16 yy305;
  96178. struct LikeOp yy318;
  96179. TriggerStep* yy327;
  96180. ExprSpan yy342;
  96181. SrcList* yy347;
  96182. int yy392;
  96183. struct TrigEvent yy410;
  96184. ExprList* yy442;
  96185. struct ValueList yy487;
  96186. } YYMINORTYPE;
  96187. #ifndef YYSTACKDEPTH
  96188. #define YYSTACKDEPTH 100
  96189. #endif
  96190. #define sqlite3ParserARG_SDECL Parse *pParse;
  96191. #define sqlite3ParserARG_PDECL ,Parse *pParse
  96192. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  96193. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  96194. #define YYNSTATE 628
  96195. #define YYNRULE 327
  96196. #define YYFALLBACK 1
  96197. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  96198. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  96199. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  96200. /* The yyzerominor constant is used to initialize instances of
  96201. ** YYMINORTYPE objects to zero. */
  96202. static const YYMINORTYPE yyzerominor = { 0 };
  96203. /* Define the yytestcase() macro to be a no-op if is not already defined
  96204. ** otherwise.
  96205. **
  96206. ** Applications can choose to define yytestcase() in the %include section
  96207. ** to a macro that can assist in verifying code coverage. For production
  96208. ** code the yytestcase() macro should be turned off. But it is useful
  96209. ** for testing.
  96210. */
  96211. #ifndef yytestcase
  96212. # define yytestcase(X)
  96213. #endif
  96214. /* Next are the tables used to determine what action to take based on the
  96215. ** current state and lookahead token. These tables are used to implement
  96216. ** functions that take a state number and lookahead value and return an
  96217. ** action integer.
  96218. **
  96219. ** Suppose the action integer is N. Then the action is determined as
  96220. ** follows
  96221. **
  96222. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  96223. ** token onto the stack and goto state N.
  96224. **
  96225. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  96226. **
  96227. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  96228. **
  96229. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  96230. **
  96231. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  96232. ** slots in the yy_action[] table.
  96233. **
  96234. ** The action table is constructed as a single large table named yy_action[].
  96235. ** Given state S and lookahead X, the action is computed as
  96236. **
  96237. ** yy_action[ yy_shift_ofst[S] + X ]
  96238. **
  96239. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  96240. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  96241. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  96242. ** and that yy_default[S] should be used instead.
  96243. **
  96244. ** The formula above is for computing the action when the lookahead is
  96245. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  96246. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  96247. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  96248. ** YY_SHIFT_USE_DFLT.
  96249. **
  96250. ** The following are the tables generated in this section:
  96251. **
  96252. ** yy_action[] A single table containing all actions.
  96253. ** yy_lookahead[] A table containing the lookahead for each entry in
  96254. ** yy_action. Used to detect hash collisions.
  96255. ** yy_shift_ofst[] For each state, the offset into yy_action for
  96256. ** shifting terminals.
  96257. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  96258. ** shifting non-terminals after a reduce.
  96259. ** yy_default[] Default action for each state.
  96260. */
  96261. #define YY_ACTTAB_COUNT (1564)
  96262. static const YYACTIONTYPE yy_action[] = {
  96263. /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
  96264. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  96265. /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
  96266. /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
  96267. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
  96268. /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96269. /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
  96270. /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
  96271. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96272. /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
  96273. /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
  96274. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  96275. /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
  96276. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  96277. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
  96278. /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
  96279. /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
  96280. /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
  96281. /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
  96282. /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
  96283. /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96284. /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96285. /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
  96286. /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
  96287. /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
  96288. /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
  96289. /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
  96290. /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  96291. /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
  96292. /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
  96293. /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
  96294. /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
  96295. /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
  96296. /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
  96297. /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
  96298. /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
  96299. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96300. /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
  96301. /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
  96302. /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
  96303. /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
  96304. /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
  96305. /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96306. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  96307. /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
  96308. /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
  96309. /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
  96310. /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
  96311. /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
  96312. /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
  96313. /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
  96314. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
  96315. /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
  96316. /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
  96317. /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
  96318. /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
  96319. /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
  96320. /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96321. /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96322. /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
  96323. /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
  96324. /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
  96325. /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
  96326. /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
  96327. /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  96328. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  96329. /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
  96330. /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
  96331. /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
  96332. /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
  96333. /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
  96334. /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
  96335. /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  96336. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96337. /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
  96338. /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
  96339. /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
  96340. /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
  96341. /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
  96342. /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96343. /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
  96344. /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
  96345. /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
  96346. /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
  96347. /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
  96348. /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
  96349. /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
  96350. /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
  96351. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
  96352. /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
  96353. /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
  96354. /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
  96355. /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
  96356. /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
  96357. /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  96358. /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  96359. /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
  96360. /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
  96361. /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
  96362. /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
  96363. /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
  96364. /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
  96365. /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
  96366. /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
  96367. /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
  96368. /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
  96369. /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
  96370. /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
  96371. /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
  96372. /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  96373. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  96374. /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
  96375. /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
  96376. /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
  96377. /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
  96378. /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
  96379. /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  96380. /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
  96381. /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
  96382. /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
  96383. /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
  96384. /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
  96385. /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
  96386. /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
  96387. /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
  96388. /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
  96389. /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
  96390. /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
  96391. /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
  96392. /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
  96393. /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
  96394. /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
  96395. /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
  96396. /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
  96397. /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
  96398. /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
  96399. /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
  96400. /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
  96401. /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
  96402. /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
  96403. /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
  96404. /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
  96405. /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
  96406. /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
  96407. /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
  96408. /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
  96409. /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
  96410. /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
  96411. /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
  96412. /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
  96413. /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
  96414. /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
  96415. /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
  96416. /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
  96417. /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
  96418. /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
  96419. /* 1560 */ 400, 499, 523, 233,
  96420. };
  96421. static const YYCODETYPE yy_lookahead[] = {
  96422. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  96423. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  96424. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  96425. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  96426. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  96427. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96428. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  96429. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  96430. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96431. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  96432. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  96433. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  96434. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  96435. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  96436. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  96437. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  96438. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  96439. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  96440. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  96441. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  96442. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96443. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96444. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  96445. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  96446. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  96447. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  96448. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  96449. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96450. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  96451. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  96452. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  96453. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  96454. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  96455. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  96456. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  96457. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  96458. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96459. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  96460. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  96461. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  96462. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  96463. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  96464. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96465. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  96466. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  96467. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  96468. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  96469. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  96470. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  96471. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  96472. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  96473. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  96474. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  96475. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  96476. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  96477. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  96478. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  96479. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96480. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96481. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  96482. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  96483. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  96484. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  96485. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  96486. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96487. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  96488. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  96489. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  96490. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  96491. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  96492. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  96493. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  96494. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  96495. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96496. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  96497. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  96498. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  96499. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  96500. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  96501. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96502. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  96503. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  96504. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  96505. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  96506. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  96507. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  96508. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  96509. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  96510. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  96511. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  96512. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  96513. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  96514. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  96515. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  96516. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96517. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96518. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  96519. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  96520. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  96521. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  96522. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  96523. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96524. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  96525. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  96526. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  96527. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  96528. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  96529. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  96530. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  96531. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  96532. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96533. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  96534. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  96535. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  96536. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  96537. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  96538. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96539. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  96540. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  96541. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  96542. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  96543. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  96544. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  96545. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  96546. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  96547. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  96548. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  96549. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  96550. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  96551. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  96552. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  96553. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  96554. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  96555. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  96556. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  96557. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  96558. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  96559. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  96560. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  96561. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  96562. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  96563. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  96564. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  96565. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  96566. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  96567. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  96568. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  96569. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  96570. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  96571. /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
  96572. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  96573. /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
  96574. /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
  96575. /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
  96576. /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
  96577. /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
  96578. /* 1560 */ 191, 182, 173, 92,
  96579. };
  96580. #define YY_SHIFT_USE_DFLT (-70)
  96581. #define YY_SHIFT_COUNT (417)
  96582. #define YY_SHIFT_MIN (-69)
  96583. #define YY_SHIFT_MAX (1487)
  96584. static const short yy_shift_ofst[] = {
  96585. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  96586. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  96587. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96588. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96589. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  96590. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  96591. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  96592. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  96593. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  96594. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  96595. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  96596. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96597. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  96598. /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
  96599. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  96600. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96601. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96602. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  96603. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  96604. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  96605. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  96606. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  96607. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  96608. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
  96609. /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
  96610. /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
  96611. /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
  96612. /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
  96613. /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
  96614. /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
  96615. /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
  96616. /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
  96617. /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
  96618. /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
  96619. /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
  96620. /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
  96621. /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
  96622. /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
  96623. /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
  96624. /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
  96625. /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
  96626. /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
  96627. };
  96628. #define YY_REDUCE_USE_DFLT (-169)
  96629. #define YY_REDUCE_COUNT (309)
  96630. #define YY_REDUCE_MIN (-168)
  96631. #define YY_REDUCE_MAX (1397)
  96632. static const short yy_reduce_ofst[] = {
  96633. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  96634. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  96635. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  96636. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  96637. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  96638. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  96639. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  96640. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96641. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96642. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  96643. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  96644. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  96645. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  96646. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  96647. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  96648. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  96649. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  96650. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  96651. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  96652. /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
  96653. /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
  96654. /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
  96655. /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
  96656. /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
  96657. /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
  96658. /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
  96659. /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
  96660. /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
  96661. /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
  96662. /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
  96663. /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  96664. };
  96665. static const YYACTIONTYPE yy_default[] = {
  96666. /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
  96667. /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
  96668. /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96669. /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96670. /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96671. /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96672. /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
  96673. /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
  96674. /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
  96675. /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
  96676. /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
  96677. /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96678. /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
  96679. /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
  96680. /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96681. /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
  96682. /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96683. /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96684. /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
  96685. /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96686. /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
  96687. /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
  96688. /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
  96689. /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
  96690. /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
  96691. /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
  96692. /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
  96693. /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
  96694. /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
  96695. /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
  96696. /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
  96697. /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
  96698. /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96699. /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
  96700. /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96701. /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
  96702. /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
  96703. /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96704. /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  96705. /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
  96706. /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
  96707. /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
  96708. /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
  96709. /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
  96710. /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
  96711. /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
  96712. /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
  96713. /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
  96714. /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
  96715. /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
  96716. /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
  96717. /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
  96718. /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
  96719. /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
  96720. /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
  96721. /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
  96722. /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
  96723. /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
  96724. /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
  96725. /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
  96726. /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
  96727. /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
  96728. /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
  96729. };
  96730. /* The next table maps tokens into fallback tokens. If a construct
  96731. ** like the following:
  96732. **
  96733. ** %fallback ID X Y Z.
  96734. **
  96735. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  96736. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  96737. ** but it does not parse, the type of the token is changed to ID and
  96738. ** the parse is retried before an error is thrown.
  96739. */
  96740. #ifdef YYFALLBACK
  96741. static const YYCODETYPE yyFallback[] = {
  96742. 0, /* $ => nothing */
  96743. 0, /* SEMI => nothing */
  96744. 26, /* EXPLAIN => ID */
  96745. 26, /* QUERY => ID */
  96746. 26, /* PLAN => ID */
  96747. 26, /* BEGIN => ID */
  96748. 0, /* TRANSACTION => nothing */
  96749. 26, /* DEFERRED => ID */
  96750. 26, /* IMMEDIATE => ID */
  96751. 26, /* EXCLUSIVE => ID */
  96752. 0, /* COMMIT => nothing */
  96753. 26, /* END => ID */
  96754. 26, /* ROLLBACK => ID */
  96755. 26, /* SAVEPOINT => ID */
  96756. 26, /* RELEASE => ID */
  96757. 0, /* TO => nothing */
  96758. 0, /* TABLE => nothing */
  96759. 0, /* CREATE => nothing */
  96760. 26, /* IF => ID */
  96761. 0, /* NOT => nothing */
  96762. 0, /* EXISTS => nothing */
  96763. 26, /* TEMP => ID */
  96764. 0, /* LP => nothing */
  96765. 0, /* RP => nothing */
  96766. 0, /* AS => nothing */
  96767. 0, /* COMMA => nothing */
  96768. 0, /* ID => nothing */
  96769. 0, /* INDEXED => nothing */
  96770. 26, /* ABORT => ID */
  96771. 26, /* ACTION => ID */
  96772. 26, /* AFTER => ID */
  96773. 26, /* ANALYZE => ID */
  96774. 26, /* ASC => ID */
  96775. 26, /* ATTACH => ID */
  96776. 26, /* BEFORE => ID */
  96777. 26, /* BY => ID */
  96778. 26, /* CASCADE => ID */
  96779. 26, /* CAST => ID */
  96780. 26, /* COLUMNKW => ID */
  96781. 26, /* CONFLICT => ID */
  96782. 26, /* DATABASE => ID */
  96783. 26, /* DESC => ID */
  96784. 26, /* DETACH => ID */
  96785. 26, /* EACH => ID */
  96786. 26, /* FAIL => ID */
  96787. 26, /* FOR => ID */
  96788. 26, /* IGNORE => ID */
  96789. 26, /* INITIALLY => ID */
  96790. 26, /* INSTEAD => ID */
  96791. 26, /* LIKE_KW => ID */
  96792. 26, /* MATCH => ID */
  96793. 26, /* NO => ID */
  96794. 26, /* KEY => ID */
  96795. 26, /* OF => ID */
  96796. 26, /* OFFSET => ID */
  96797. 26, /* PRAGMA => ID */
  96798. 26, /* RAISE => ID */
  96799. 26, /* REPLACE => ID */
  96800. 26, /* RESTRICT => ID */
  96801. 26, /* ROW => ID */
  96802. 26, /* TRIGGER => ID */
  96803. 26, /* VACUUM => ID */
  96804. 26, /* VIEW => ID */
  96805. 26, /* VIRTUAL => ID */
  96806. 26, /* REINDEX => ID */
  96807. 26, /* RENAME => ID */
  96808. 26, /* CTIME_KW => ID */
  96809. };
  96810. #endif /* YYFALLBACK */
  96811. /* The following structure represents a single element of the
  96812. ** parser's stack. Information stored includes:
  96813. **
  96814. ** + The state number for the parser at this level of the stack.
  96815. **
  96816. ** + The value of the token stored at this level of the stack.
  96817. ** (In other words, the "major" token.)
  96818. **
  96819. ** + The semantic value stored at this level of the stack. This is
  96820. ** the information used by the action routines in the grammar.
  96821. ** It is sometimes called the "minor" token.
  96822. */
  96823. struct yyStackEntry {
  96824. YYACTIONTYPE stateno; /* The state-number */
  96825. YYCODETYPE major; /* The major token value. This is the code
  96826. ** number for the token at this stack level */
  96827. YYMINORTYPE minor; /* The user-supplied minor token value. This
  96828. ** is the value of the token */
  96829. };
  96830. typedef struct yyStackEntry yyStackEntry;
  96831. /* The state of the parser is completely contained in an instance of
  96832. ** the following structure */
  96833. struct yyParser {
  96834. int yyidx; /* Index of top element in stack */
  96835. #ifdef YYTRACKMAXSTACKDEPTH
  96836. int yyidxMax; /* Maximum value of yyidx */
  96837. #endif
  96838. int yyerrcnt; /* Shifts left before out of the error */
  96839. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  96840. #if YYSTACKDEPTH<=0
  96841. int yystksz; /* Current side of the stack */
  96842. yyStackEntry *yystack; /* The parser's stack */
  96843. #else
  96844. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  96845. #endif
  96846. };
  96847. typedef struct yyParser yyParser;
  96848. #ifndef NDEBUG
  96849. /* #include <stdio.h> */
  96850. static FILE *yyTraceFILE = 0;
  96851. static char *yyTracePrompt = 0;
  96852. #endif /* NDEBUG */
  96853. #ifndef NDEBUG
  96854. /*
  96855. ** Turn parser tracing on by giving a stream to which to write the trace
  96856. ** and a prompt to preface each trace message. Tracing is turned off
  96857. ** by making either argument NULL
  96858. **
  96859. ** Inputs:
  96860. ** <ul>
  96861. ** <li> A FILE* to which trace output should be written.
  96862. ** If NULL, then tracing is turned off.
  96863. ** <li> A prefix string written at the beginning of every
  96864. ** line of trace output. If NULL, then tracing is
  96865. ** turned off.
  96866. ** </ul>
  96867. **
  96868. ** Outputs:
  96869. ** None.
  96870. */
  96871. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  96872. yyTraceFILE = TraceFILE;
  96873. yyTracePrompt = zTracePrompt;
  96874. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  96875. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  96876. }
  96877. #endif /* NDEBUG */
  96878. #ifndef NDEBUG
  96879. /* For tracing shifts, the names of all terminals and nonterminals
  96880. ** are required. The following table supplies these names */
  96881. static const char *const yyTokenName[] = {
  96882. "$", "SEMI", "EXPLAIN", "QUERY",
  96883. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  96884. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  96885. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  96886. "TABLE", "CREATE", "IF", "NOT",
  96887. "EXISTS", "TEMP", "LP", "RP",
  96888. "AS", "COMMA", "ID", "INDEXED",
  96889. "ABORT", "ACTION", "AFTER", "ANALYZE",
  96890. "ASC", "ATTACH", "BEFORE", "BY",
  96891. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  96892. "DATABASE", "DESC", "DETACH", "EACH",
  96893. "FAIL", "FOR", "IGNORE", "INITIALLY",
  96894. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  96895. "KEY", "OF", "OFFSET", "PRAGMA",
  96896. "RAISE", "REPLACE", "RESTRICT", "ROW",
  96897. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  96898. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  96899. "OR", "AND", "IS", "BETWEEN",
  96900. "IN", "ISNULL", "NOTNULL", "NE",
  96901. "EQ", "GT", "LE", "LT",
  96902. "GE", "ESCAPE", "BITAND", "BITOR",
  96903. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  96904. "STAR", "SLASH", "REM", "CONCAT",
  96905. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  96906. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  96907. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  96908. "ON", "INSERT", "DELETE", "UPDATE",
  96909. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  96910. "UNION", "ALL", "EXCEPT", "INTERSECT",
  96911. "SELECT", "DISTINCT", "DOT", "FROM",
  96912. "JOIN", "USING", "ORDER", "GROUP",
  96913. "HAVING", "LIMIT", "WHERE", "INTO",
  96914. "VALUES", "INTEGER", "FLOAT", "BLOB",
  96915. "REGISTER", "VARIABLE", "CASE", "WHEN",
  96916. "THEN", "ELSE", "INDEX", "ALTER",
  96917. "ADD", "error", "input", "cmdlist",
  96918. "ecmd", "explain", "cmdx", "cmd",
  96919. "transtype", "trans_opt", "nm", "savepoint_opt",
  96920. "create_table", "create_table_args", "createkw", "temp",
  96921. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  96922. "select", "column", "columnid", "type",
  96923. "carglist", "id", "ids", "typetoken",
  96924. "typename", "signed", "plus_num", "minus_num",
  96925. "ccons", "term", "expr", "onconf",
  96926. "sortorder", "autoinc", "idxlist_opt", "refargs",
  96927. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  96928. "conslist", "tconscomma", "tcons", "idxlist",
  96929. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  96930. "ifexists", "fullname", "oneselect", "multiselect_op",
  96931. "distinct", "selcollist", "from", "where_opt",
  96932. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  96933. "sclp", "as", "seltablist", "stl_prefix",
  96934. "joinop", "indexed_opt", "on_opt", "using_opt",
  96935. "joinop2", "inscollist", "sortlist", "nexprlist",
  96936. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  96937. "exprlist", "likeop", "between_op", "in_op",
  96938. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  96939. "collate", "nmnum", "number", "trigger_decl",
  96940. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  96941. "when_clause", "trigger_cmd", "trnm", "tridxby",
  96942. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  96943. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  96944. "lp", "anylist",
  96945. };
  96946. #endif /* NDEBUG */
  96947. #ifndef NDEBUG
  96948. /* For tracing reduce actions, the names of all rules are required.
  96949. */
  96950. static const char *const yyRuleName[] = {
  96951. /* 0 */ "input ::= cmdlist",
  96952. /* 1 */ "cmdlist ::= cmdlist ecmd",
  96953. /* 2 */ "cmdlist ::= ecmd",
  96954. /* 3 */ "ecmd ::= SEMI",
  96955. /* 4 */ "ecmd ::= explain cmdx SEMI",
  96956. /* 5 */ "explain ::=",
  96957. /* 6 */ "explain ::= EXPLAIN",
  96958. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  96959. /* 8 */ "cmdx ::= cmd",
  96960. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  96961. /* 10 */ "trans_opt ::=",
  96962. /* 11 */ "trans_opt ::= TRANSACTION",
  96963. /* 12 */ "trans_opt ::= TRANSACTION nm",
  96964. /* 13 */ "transtype ::=",
  96965. /* 14 */ "transtype ::= DEFERRED",
  96966. /* 15 */ "transtype ::= IMMEDIATE",
  96967. /* 16 */ "transtype ::= EXCLUSIVE",
  96968. /* 17 */ "cmd ::= COMMIT trans_opt",
  96969. /* 18 */ "cmd ::= END trans_opt",
  96970. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  96971. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  96972. /* 21 */ "savepoint_opt ::=",
  96973. /* 22 */ "cmd ::= SAVEPOINT nm",
  96974. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  96975. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  96976. /* 25 */ "cmd ::= create_table create_table_args",
  96977. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  96978. /* 27 */ "createkw ::= CREATE",
  96979. /* 28 */ "ifnotexists ::=",
  96980. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  96981. /* 30 */ "temp ::= TEMP",
  96982. /* 31 */ "temp ::=",
  96983. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  96984. /* 33 */ "create_table_args ::= AS select",
  96985. /* 34 */ "columnlist ::= columnlist COMMA column",
  96986. /* 35 */ "columnlist ::= column",
  96987. /* 36 */ "column ::= columnid type carglist",
  96988. /* 37 */ "columnid ::= nm",
  96989. /* 38 */ "id ::= ID",
  96990. /* 39 */ "id ::= INDEXED",
  96991. /* 40 */ "ids ::= ID|STRING",
  96992. /* 41 */ "nm ::= id",
  96993. /* 42 */ "nm ::= STRING",
  96994. /* 43 */ "nm ::= JOIN_KW",
  96995. /* 44 */ "type ::=",
  96996. /* 45 */ "type ::= typetoken",
  96997. /* 46 */ "typetoken ::= typename",
  96998. /* 47 */ "typetoken ::= typename LP signed RP",
  96999. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  97000. /* 49 */ "typename ::= ids",
  97001. /* 50 */ "typename ::= typename ids",
  97002. /* 51 */ "signed ::= plus_num",
  97003. /* 52 */ "signed ::= minus_num",
  97004. /* 53 */ "carglist ::= carglist ccons",
  97005. /* 54 */ "carglist ::=",
  97006. /* 55 */ "ccons ::= CONSTRAINT nm",
  97007. /* 56 */ "ccons ::= DEFAULT term",
  97008. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  97009. /* 58 */ "ccons ::= DEFAULT PLUS term",
  97010. /* 59 */ "ccons ::= DEFAULT MINUS term",
  97011. /* 60 */ "ccons ::= DEFAULT id",
  97012. /* 61 */ "ccons ::= NULL onconf",
  97013. /* 62 */ "ccons ::= NOT NULL onconf",
  97014. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  97015. /* 64 */ "ccons ::= UNIQUE onconf",
  97016. /* 65 */ "ccons ::= CHECK LP expr RP",
  97017. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  97018. /* 67 */ "ccons ::= defer_subclause",
  97019. /* 68 */ "ccons ::= COLLATE ids",
  97020. /* 69 */ "autoinc ::=",
  97021. /* 70 */ "autoinc ::= AUTOINCR",
  97022. /* 71 */ "refargs ::=",
  97023. /* 72 */ "refargs ::= refargs refarg",
  97024. /* 73 */ "refarg ::= MATCH nm",
  97025. /* 74 */ "refarg ::= ON INSERT refact",
  97026. /* 75 */ "refarg ::= ON DELETE refact",
  97027. /* 76 */ "refarg ::= ON UPDATE refact",
  97028. /* 77 */ "refact ::= SET NULL",
  97029. /* 78 */ "refact ::= SET DEFAULT",
  97030. /* 79 */ "refact ::= CASCADE",
  97031. /* 80 */ "refact ::= RESTRICT",
  97032. /* 81 */ "refact ::= NO ACTION",
  97033. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  97034. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  97035. /* 84 */ "init_deferred_pred_opt ::=",
  97036. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  97037. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  97038. /* 87 */ "conslist_opt ::=",
  97039. /* 88 */ "conslist_opt ::= COMMA conslist",
  97040. /* 89 */ "conslist ::= conslist tconscomma tcons",
  97041. /* 90 */ "conslist ::= tcons",
  97042. /* 91 */ "tconscomma ::= COMMA",
  97043. /* 92 */ "tconscomma ::=",
  97044. /* 93 */ "tcons ::= CONSTRAINT nm",
  97045. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  97046. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  97047. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  97048. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  97049. /* 98 */ "defer_subclause_opt ::=",
  97050. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  97051. /* 100 */ "onconf ::=",
  97052. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  97053. /* 102 */ "orconf ::=",
  97054. /* 103 */ "orconf ::= OR resolvetype",
  97055. /* 104 */ "resolvetype ::= raisetype",
  97056. /* 105 */ "resolvetype ::= IGNORE",
  97057. /* 106 */ "resolvetype ::= REPLACE",
  97058. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  97059. /* 108 */ "ifexists ::= IF EXISTS",
  97060. /* 109 */ "ifexists ::=",
  97061. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  97062. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  97063. /* 112 */ "cmd ::= select",
  97064. /* 113 */ "select ::= oneselect",
  97065. /* 114 */ "select ::= select multiselect_op oneselect",
  97066. /* 115 */ "multiselect_op ::= UNION",
  97067. /* 116 */ "multiselect_op ::= UNION ALL",
  97068. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  97069. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  97070. /* 119 */ "distinct ::= DISTINCT",
  97071. /* 120 */ "distinct ::= ALL",
  97072. /* 121 */ "distinct ::=",
  97073. /* 122 */ "sclp ::= selcollist COMMA",
  97074. /* 123 */ "sclp ::=",
  97075. /* 124 */ "selcollist ::= sclp expr as",
  97076. /* 125 */ "selcollist ::= sclp STAR",
  97077. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  97078. /* 127 */ "as ::= AS nm",
  97079. /* 128 */ "as ::= ids",
  97080. /* 129 */ "as ::=",
  97081. /* 130 */ "from ::=",
  97082. /* 131 */ "from ::= FROM seltablist",
  97083. /* 132 */ "stl_prefix ::= seltablist joinop",
  97084. /* 133 */ "stl_prefix ::=",
  97085. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  97086. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  97087. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  97088. /* 137 */ "dbnm ::=",
  97089. /* 138 */ "dbnm ::= DOT nm",
  97090. /* 139 */ "fullname ::= nm dbnm",
  97091. /* 140 */ "joinop ::= COMMA|JOIN",
  97092. /* 141 */ "joinop ::= JOIN_KW JOIN",
  97093. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  97094. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  97095. /* 144 */ "on_opt ::= ON expr",
  97096. /* 145 */ "on_opt ::=",
  97097. /* 146 */ "indexed_opt ::=",
  97098. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  97099. /* 148 */ "indexed_opt ::= NOT INDEXED",
  97100. /* 149 */ "using_opt ::= USING LP inscollist RP",
  97101. /* 150 */ "using_opt ::=",
  97102. /* 151 */ "orderby_opt ::=",
  97103. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  97104. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  97105. /* 154 */ "sortlist ::= expr sortorder",
  97106. /* 155 */ "sortorder ::= ASC",
  97107. /* 156 */ "sortorder ::= DESC",
  97108. /* 157 */ "sortorder ::=",
  97109. /* 158 */ "groupby_opt ::=",
  97110. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  97111. /* 160 */ "having_opt ::=",
  97112. /* 161 */ "having_opt ::= HAVING expr",
  97113. /* 162 */ "limit_opt ::=",
  97114. /* 163 */ "limit_opt ::= LIMIT expr",
  97115. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  97116. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  97117. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  97118. /* 167 */ "where_opt ::=",
  97119. /* 168 */ "where_opt ::= WHERE expr",
  97120. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  97121. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  97122. /* 171 */ "setlist ::= nm EQ expr",
  97123. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  97124. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  97125. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  97126. /* 175 */ "insert_cmd ::= INSERT orconf",
  97127. /* 176 */ "insert_cmd ::= REPLACE",
  97128. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  97129. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  97130. /* 179 */ "inscollist_opt ::=",
  97131. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  97132. /* 181 */ "inscollist ::= inscollist COMMA nm",
  97133. /* 182 */ "inscollist ::= nm",
  97134. /* 183 */ "expr ::= term",
  97135. /* 184 */ "expr ::= LP expr RP",
  97136. /* 185 */ "term ::= NULL",
  97137. /* 186 */ "expr ::= id",
  97138. /* 187 */ "expr ::= JOIN_KW",
  97139. /* 188 */ "expr ::= nm DOT nm",
  97140. /* 189 */ "expr ::= nm DOT nm DOT nm",
  97141. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  97142. /* 191 */ "term ::= STRING",
  97143. /* 192 */ "expr ::= REGISTER",
  97144. /* 193 */ "expr ::= VARIABLE",
  97145. /* 194 */ "expr ::= expr COLLATE ids",
  97146. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  97147. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  97148. /* 197 */ "expr ::= ID LP STAR RP",
  97149. /* 198 */ "term ::= CTIME_KW",
  97150. /* 199 */ "expr ::= expr AND expr",
  97151. /* 200 */ "expr ::= expr OR expr",
  97152. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  97153. /* 202 */ "expr ::= expr EQ|NE expr",
  97154. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  97155. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  97156. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  97157. /* 206 */ "expr ::= expr CONCAT expr",
  97158. /* 207 */ "likeop ::= LIKE_KW",
  97159. /* 208 */ "likeop ::= NOT LIKE_KW",
  97160. /* 209 */ "likeop ::= MATCH",
  97161. /* 210 */ "likeop ::= NOT MATCH",
  97162. /* 211 */ "expr ::= expr likeop expr",
  97163. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  97164. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  97165. /* 214 */ "expr ::= expr NOT NULL",
  97166. /* 215 */ "expr ::= expr IS expr",
  97167. /* 216 */ "expr ::= expr IS NOT expr",
  97168. /* 217 */ "expr ::= NOT expr",
  97169. /* 218 */ "expr ::= BITNOT expr",
  97170. /* 219 */ "expr ::= MINUS expr",
  97171. /* 220 */ "expr ::= PLUS expr",
  97172. /* 221 */ "between_op ::= BETWEEN",
  97173. /* 222 */ "between_op ::= NOT BETWEEN",
  97174. /* 223 */ "expr ::= expr between_op expr AND expr",
  97175. /* 224 */ "in_op ::= IN",
  97176. /* 225 */ "in_op ::= NOT IN",
  97177. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  97178. /* 227 */ "expr ::= LP select RP",
  97179. /* 228 */ "expr ::= expr in_op LP select RP",
  97180. /* 229 */ "expr ::= expr in_op nm dbnm",
  97181. /* 230 */ "expr ::= EXISTS LP select RP",
  97182. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  97183. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  97184. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  97185. /* 234 */ "case_else ::= ELSE expr",
  97186. /* 235 */ "case_else ::=",
  97187. /* 236 */ "case_operand ::= expr",
  97188. /* 237 */ "case_operand ::=",
  97189. /* 238 */ "exprlist ::= nexprlist",
  97190. /* 239 */ "exprlist ::=",
  97191. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  97192. /* 241 */ "nexprlist ::= expr",
  97193. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  97194. /* 243 */ "uniqueflag ::= UNIQUE",
  97195. /* 244 */ "uniqueflag ::=",
  97196. /* 245 */ "idxlist_opt ::=",
  97197. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  97198. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  97199. /* 248 */ "idxlist ::= nm collate sortorder",
  97200. /* 249 */ "collate ::=",
  97201. /* 250 */ "collate ::= COLLATE ids",
  97202. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  97203. /* 252 */ "cmd ::= VACUUM",
  97204. /* 253 */ "cmd ::= VACUUM nm",
  97205. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  97206. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  97207. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  97208. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  97209. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  97210. /* 259 */ "nmnum ::= plus_num",
  97211. /* 260 */ "nmnum ::= nm",
  97212. /* 261 */ "nmnum ::= ON",
  97213. /* 262 */ "nmnum ::= DELETE",
  97214. /* 263 */ "nmnum ::= DEFAULT",
  97215. /* 264 */ "plus_num ::= PLUS number",
  97216. /* 265 */ "plus_num ::= number",
  97217. /* 266 */ "minus_num ::= MINUS number",
  97218. /* 267 */ "number ::= INTEGER|FLOAT",
  97219. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  97220. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  97221. /* 270 */ "trigger_time ::= BEFORE",
  97222. /* 271 */ "trigger_time ::= AFTER",
  97223. /* 272 */ "trigger_time ::= INSTEAD OF",
  97224. /* 273 */ "trigger_time ::=",
  97225. /* 274 */ "trigger_event ::= DELETE|INSERT",
  97226. /* 275 */ "trigger_event ::= UPDATE",
  97227. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  97228. /* 277 */ "foreach_clause ::=",
  97229. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  97230. /* 279 */ "when_clause ::=",
  97231. /* 280 */ "when_clause ::= WHEN expr",
  97232. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  97233. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  97234. /* 283 */ "trnm ::= nm",
  97235. /* 284 */ "trnm ::= nm DOT nm",
  97236. /* 285 */ "tridxby ::=",
  97237. /* 286 */ "tridxby ::= INDEXED BY nm",
  97238. /* 287 */ "tridxby ::= NOT INDEXED",
  97239. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  97240. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  97241. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  97242. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  97243. /* 292 */ "trigger_cmd ::= select",
  97244. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  97245. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  97246. /* 295 */ "raisetype ::= ROLLBACK",
  97247. /* 296 */ "raisetype ::= ABORT",
  97248. /* 297 */ "raisetype ::= FAIL",
  97249. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  97250. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  97251. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  97252. /* 301 */ "key_opt ::=",
  97253. /* 302 */ "key_opt ::= KEY expr",
  97254. /* 303 */ "database_kw_opt ::= DATABASE",
  97255. /* 304 */ "database_kw_opt ::=",
  97256. /* 305 */ "cmd ::= REINDEX",
  97257. /* 306 */ "cmd ::= REINDEX nm dbnm",
  97258. /* 307 */ "cmd ::= ANALYZE",
  97259. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  97260. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  97261. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  97262. /* 311 */ "add_column_fullname ::= fullname",
  97263. /* 312 */ "kwcolumn_opt ::=",
  97264. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  97265. /* 314 */ "cmd ::= create_vtab",
  97266. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  97267. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  97268. /* 317 */ "vtabarglist ::= vtabarg",
  97269. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  97270. /* 319 */ "vtabarg ::=",
  97271. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  97272. /* 321 */ "vtabargtoken ::= ANY",
  97273. /* 322 */ "vtabargtoken ::= lp anylist RP",
  97274. /* 323 */ "lp ::= LP",
  97275. /* 324 */ "anylist ::=",
  97276. /* 325 */ "anylist ::= anylist LP anylist RP",
  97277. /* 326 */ "anylist ::= anylist ANY",
  97278. };
  97279. #endif /* NDEBUG */
  97280. #if YYSTACKDEPTH<=0
  97281. /*
  97282. ** Try to increase the size of the parser stack.
  97283. */
  97284. static void yyGrowStack(yyParser *p){
  97285. int newSize;
  97286. yyStackEntry *pNew;
  97287. newSize = p->yystksz*2 + 100;
  97288. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  97289. if( pNew ){
  97290. p->yystack = pNew;
  97291. p->yystksz = newSize;
  97292. #ifndef NDEBUG
  97293. if( yyTraceFILE ){
  97294. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  97295. yyTracePrompt, p->yystksz);
  97296. }
  97297. #endif
  97298. }
  97299. }
  97300. #endif
  97301. /*
  97302. ** This function allocates a new parser.
  97303. ** The only argument is a pointer to a function which works like
  97304. ** malloc.
  97305. **
  97306. ** Inputs:
  97307. ** A pointer to the function used to allocate memory.
  97308. **
  97309. ** Outputs:
  97310. ** A pointer to a parser. This pointer is used in subsequent calls
  97311. ** to sqlite3Parser and sqlite3ParserFree.
  97312. */
  97313. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  97314. yyParser *pParser;
  97315. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  97316. if( pParser ){
  97317. pParser->yyidx = -1;
  97318. #ifdef YYTRACKMAXSTACKDEPTH
  97319. pParser->yyidxMax = 0;
  97320. #endif
  97321. #if YYSTACKDEPTH<=0
  97322. pParser->yystack = NULL;
  97323. pParser->yystksz = 0;
  97324. yyGrowStack(pParser);
  97325. #endif
  97326. }
  97327. return pParser;
  97328. }
  97329. /* The following function deletes the value associated with a
  97330. ** symbol. The symbol can be either a terminal or nonterminal.
  97331. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  97332. ** the value.
  97333. */
  97334. static void yy_destructor(
  97335. yyParser *yypParser, /* The parser */
  97336. YYCODETYPE yymajor, /* Type code for object to destroy */
  97337. YYMINORTYPE *yypminor /* The object to be destroyed */
  97338. ){
  97339. sqlite3ParserARG_FETCH;
  97340. switch( yymajor ){
  97341. /* Here is inserted the actions which take place when a
  97342. ** terminal or non-terminal is destroyed. This can happen
  97343. ** when the symbol is popped from the stack during a
  97344. ** reduce or during error processing or when a parser is
  97345. ** being destroyed before it is finished parsing.
  97346. **
  97347. ** Note: during a reduce, the only symbols destroyed are those
  97348. ** which appear on the RHS of the rule, but which are not used
  97349. ** inside the C code.
  97350. */
  97351. case 160: /* select */
  97352. case 194: /* oneselect */
  97353. {
  97354. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  97355. }
  97356. break;
  97357. case 173: /* term */
  97358. case 174: /* expr */
  97359. {
  97360. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  97361. }
  97362. break;
  97363. case 178: /* idxlist_opt */
  97364. case 187: /* idxlist */
  97365. case 197: /* selcollist */
  97366. case 200: /* groupby_opt */
  97367. case 202: /* orderby_opt */
  97368. case 204: /* sclp */
  97369. case 214: /* sortlist */
  97370. case 215: /* nexprlist */
  97371. case 216: /* setlist */
  97372. case 220: /* exprlist */
  97373. case 225: /* case_exprlist */
  97374. {
  97375. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  97376. }
  97377. break;
  97378. case 193: /* fullname */
  97379. case 198: /* from */
  97380. case 206: /* seltablist */
  97381. case 207: /* stl_prefix */
  97382. {
  97383. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  97384. }
  97385. break;
  97386. case 199: /* where_opt */
  97387. case 201: /* having_opt */
  97388. case 210: /* on_opt */
  97389. case 224: /* case_operand */
  97390. case 226: /* case_else */
  97391. case 236: /* when_clause */
  97392. case 241: /* key_opt */
  97393. {
  97394. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  97395. }
  97396. break;
  97397. case 211: /* using_opt */
  97398. case 213: /* inscollist */
  97399. case 218: /* inscollist_opt */
  97400. {
  97401. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  97402. }
  97403. break;
  97404. case 219: /* valuelist */
  97405. {
  97406. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  97407. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  97408. }
  97409. break;
  97410. case 232: /* trigger_cmd_list */
  97411. case 237: /* trigger_cmd */
  97412. {
  97413. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  97414. }
  97415. break;
  97416. case 234: /* trigger_event */
  97417. {
  97418. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  97419. }
  97420. break;
  97421. default: break; /* If no destructor action specified: do nothing */
  97422. }
  97423. }
  97424. /*
  97425. ** Pop the parser's stack once.
  97426. **
  97427. ** If there is a destructor routine associated with the token which
  97428. ** is popped from the stack, then call it.
  97429. **
  97430. ** Return the major token number for the symbol popped.
  97431. */
  97432. static int yy_pop_parser_stack(yyParser *pParser){
  97433. YYCODETYPE yymajor;
  97434. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  97435. /* There is no mechanism by which the parser stack can be popped below
  97436. ** empty in SQLite. */
  97437. if( NEVER(pParser->yyidx<0) ) return 0;
  97438. #ifndef NDEBUG
  97439. if( yyTraceFILE && pParser->yyidx>=0 ){
  97440. fprintf(yyTraceFILE,"%sPopping %s\n",
  97441. yyTracePrompt,
  97442. yyTokenName[yytos->major]);
  97443. }
  97444. #endif
  97445. yymajor = yytos->major;
  97446. yy_destructor(pParser, yymajor, &yytos->minor);
  97447. pParser->yyidx--;
  97448. return yymajor;
  97449. }
  97450. /*
  97451. ** Deallocate and destroy a parser. Destructors are all called for
  97452. ** all stack elements before shutting the parser down.
  97453. **
  97454. ** Inputs:
  97455. ** <ul>
  97456. ** <li> A pointer to the parser. This should be a pointer
  97457. ** obtained from sqlite3ParserAlloc.
  97458. ** <li> A pointer to a function used to reclaim memory obtained
  97459. ** from malloc.
  97460. ** </ul>
  97461. */
  97462. SQLITE_PRIVATE void sqlite3ParserFree(
  97463. void *p, /* The parser to be deleted */
  97464. void (*freeProc)(void*) /* Function used to reclaim memory */
  97465. ){
  97466. yyParser *pParser = (yyParser*)p;
  97467. /* In SQLite, we never try to destroy a parser that was not successfully
  97468. ** created in the first place. */
  97469. if( NEVER(pParser==0) ) return;
  97470. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  97471. #if YYSTACKDEPTH<=0
  97472. free(pParser->yystack);
  97473. #endif
  97474. (*freeProc)((void*)pParser);
  97475. }
  97476. /*
  97477. ** Return the peak depth of the stack for a parser.
  97478. */
  97479. #ifdef YYTRACKMAXSTACKDEPTH
  97480. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  97481. yyParser *pParser = (yyParser*)p;
  97482. return pParser->yyidxMax;
  97483. }
  97484. #endif
  97485. /*
  97486. ** Find the appropriate action for a parser given the terminal
  97487. ** look-ahead token iLookAhead.
  97488. **
  97489. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97490. ** independent of the look-ahead. If it is, return the action, otherwise
  97491. ** return YY_NO_ACTION.
  97492. */
  97493. static int yy_find_shift_action(
  97494. yyParser *pParser, /* The parser */
  97495. YYCODETYPE iLookAhead /* The look-ahead token */
  97496. ){
  97497. int i;
  97498. int stateno = pParser->yystack[pParser->yyidx].stateno;
  97499. if( stateno>YY_SHIFT_COUNT
  97500. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  97501. return yy_default[stateno];
  97502. }
  97503. assert( iLookAhead!=YYNOCODE );
  97504. i += iLookAhead;
  97505. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97506. if( iLookAhead>0 ){
  97507. #ifdef YYFALLBACK
  97508. YYCODETYPE iFallback; /* Fallback token */
  97509. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  97510. && (iFallback = yyFallback[iLookAhead])!=0 ){
  97511. #ifndef NDEBUG
  97512. if( yyTraceFILE ){
  97513. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  97514. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  97515. }
  97516. #endif
  97517. return yy_find_shift_action(pParser, iFallback);
  97518. }
  97519. #endif
  97520. #ifdef YYWILDCARD
  97521. {
  97522. int j = i - iLookAhead + YYWILDCARD;
  97523. if(
  97524. #if YY_SHIFT_MIN+YYWILDCARD<0
  97525. j>=0 &&
  97526. #endif
  97527. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  97528. j<YY_ACTTAB_COUNT &&
  97529. #endif
  97530. yy_lookahead[j]==YYWILDCARD
  97531. ){
  97532. #ifndef NDEBUG
  97533. if( yyTraceFILE ){
  97534. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  97535. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  97536. }
  97537. #endif /* NDEBUG */
  97538. return yy_action[j];
  97539. }
  97540. }
  97541. #endif /* YYWILDCARD */
  97542. }
  97543. return yy_default[stateno];
  97544. }else{
  97545. return yy_action[i];
  97546. }
  97547. }
  97548. /*
  97549. ** Find the appropriate action for a parser given the non-terminal
  97550. ** look-ahead token iLookAhead.
  97551. **
  97552. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97553. ** independent of the look-ahead. If it is, return the action, otherwise
  97554. ** return YY_NO_ACTION.
  97555. */
  97556. static int yy_find_reduce_action(
  97557. int stateno, /* Current state number */
  97558. YYCODETYPE iLookAhead /* The look-ahead token */
  97559. ){
  97560. int i;
  97561. #ifdef YYERRORSYMBOL
  97562. if( stateno>YY_REDUCE_COUNT ){
  97563. return yy_default[stateno];
  97564. }
  97565. #else
  97566. assert( stateno<=YY_REDUCE_COUNT );
  97567. #endif
  97568. i = yy_reduce_ofst[stateno];
  97569. assert( i!=YY_REDUCE_USE_DFLT );
  97570. assert( iLookAhead!=YYNOCODE );
  97571. i += iLookAhead;
  97572. #ifdef YYERRORSYMBOL
  97573. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97574. return yy_default[stateno];
  97575. }
  97576. #else
  97577. assert( i>=0 && i<YY_ACTTAB_COUNT );
  97578. assert( yy_lookahead[i]==iLookAhead );
  97579. #endif
  97580. return yy_action[i];
  97581. }
  97582. /*
  97583. ** The following routine is called if the stack overflows.
  97584. */
  97585. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  97586. sqlite3ParserARG_FETCH;
  97587. yypParser->yyidx--;
  97588. #ifndef NDEBUG
  97589. if( yyTraceFILE ){
  97590. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  97591. }
  97592. #endif
  97593. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  97594. /* Here code is inserted which will execute if the parser
  97595. ** stack every overflows */
  97596. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  97597. sqlite3ErrorMsg(pParse, "parser stack overflow");
  97598. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  97599. }
  97600. /*
  97601. ** Perform a shift action.
  97602. */
  97603. static void yy_shift(
  97604. yyParser *yypParser, /* The parser to be shifted */
  97605. int yyNewState, /* The new state to shift in */
  97606. int yyMajor, /* The major token to shift in */
  97607. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  97608. ){
  97609. yyStackEntry *yytos;
  97610. yypParser->yyidx++;
  97611. #ifdef YYTRACKMAXSTACKDEPTH
  97612. if( yypParser->yyidx>yypParser->yyidxMax ){
  97613. yypParser->yyidxMax = yypParser->yyidx;
  97614. }
  97615. #endif
  97616. #if YYSTACKDEPTH>0
  97617. if( yypParser->yyidx>=YYSTACKDEPTH ){
  97618. yyStackOverflow(yypParser, yypMinor);
  97619. return;
  97620. }
  97621. #else
  97622. if( yypParser->yyidx>=yypParser->yystksz ){
  97623. yyGrowStack(yypParser);
  97624. if( yypParser->yyidx>=yypParser->yystksz ){
  97625. yyStackOverflow(yypParser, yypMinor);
  97626. return;
  97627. }
  97628. }
  97629. #endif
  97630. yytos = &yypParser->yystack[yypParser->yyidx];
  97631. yytos->stateno = (YYACTIONTYPE)yyNewState;
  97632. yytos->major = (YYCODETYPE)yyMajor;
  97633. yytos->minor = *yypMinor;
  97634. #ifndef NDEBUG
  97635. if( yyTraceFILE && yypParser->yyidx>0 ){
  97636. int i;
  97637. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  97638. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  97639. for(i=1; i<=yypParser->yyidx; i++)
  97640. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  97641. fprintf(yyTraceFILE,"\n");
  97642. }
  97643. #endif
  97644. }
  97645. /* The following table contains information about every rule that
  97646. ** is used during the reduce.
  97647. */
  97648. static const struct {
  97649. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  97650. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  97651. } yyRuleInfo[] = {
  97652. { 142, 1 },
  97653. { 143, 2 },
  97654. { 143, 1 },
  97655. { 144, 1 },
  97656. { 144, 3 },
  97657. { 145, 0 },
  97658. { 145, 1 },
  97659. { 145, 3 },
  97660. { 146, 1 },
  97661. { 147, 3 },
  97662. { 149, 0 },
  97663. { 149, 1 },
  97664. { 149, 2 },
  97665. { 148, 0 },
  97666. { 148, 1 },
  97667. { 148, 1 },
  97668. { 148, 1 },
  97669. { 147, 2 },
  97670. { 147, 2 },
  97671. { 147, 2 },
  97672. { 151, 1 },
  97673. { 151, 0 },
  97674. { 147, 2 },
  97675. { 147, 3 },
  97676. { 147, 5 },
  97677. { 147, 2 },
  97678. { 152, 6 },
  97679. { 154, 1 },
  97680. { 156, 0 },
  97681. { 156, 3 },
  97682. { 155, 1 },
  97683. { 155, 0 },
  97684. { 153, 4 },
  97685. { 153, 2 },
  97686. { 158, 3 },
  97687. { 158, 1 },
  97688. { 161, 3 },
  97689. { 162, 1 },
  97690. { 165, 1 },
  97691. { 165, 1 },
  97692. { 166, 1 },
  97693. { 150, 1 },
  97694. { 150, 1 },
  97695. { 150, 1 },
  97696. { 163, 0 },
  97697. { 163, 1 },
  97698. { 167, 1 },
  97699. { 167, 4 },
  97700. { 167, 6 },
  97701. { 168, 1 },
  97702. { 168, 2 },
  97703. { 169, 1 },
  97704. { 169, 1 },
  97705. { 164, 2 },
  97706. { 164, 0 },
  97707. { 172, 2 },
  97708. { 172, 2 },
  97709. { 172, 4 },
  97710. { 172, 3 },
  97711. { 172, 3 },
  97712. { 172, 2 },
  97713. { 172, 2 },
  97714. { 172, 3 },
  97715. { 172, 5 },
  97716. { 172, 2 },
  97717. { 172, 4 },
  97718. { 172, 4 },
  97719. { 172, 1 },
  97720. { 172, 2 },
  97721. { 177, 0 },
  97722. { 177, 1 },
  97723. { 179, 0 },
  97724. { 179, 2 },
  97725. { 181, 2 },
  97726. { 181, 3 },
  97727. { 181, 3 },
  97728. { 181, 3 },
  97729. { 182, 2 },
  97730. { 182, 2 },
  97731. { 182, 1 },
  97732. { 182, 1 },
  97733. { 182, 2 },
  97734. { 180, 3 },
  97735. { 180, 2 },
  97736. { 183, 0 },
  97737. { 183, 2 },
  97738. { 183, 2 },
  97739. { 159, 0 },
  97740. { 159, 2 },
  97741. { 184, 3 },
  97742. { 184, 1 },
  97743. { 185, 1 },
  97744. { 185, 0 },
  97745. { 186, 2 },
  97746. { 186, 7 },
  97747. { 186, 5 },
  97748. { 186, 5 },
  97749. { 186, 10 },
  97750. { 188, 0 },
  97751. { 188, 1 },
  97752. { 175, 0 },
  97753. { 175, 3 },
  97754. { 189, 0 },
  97755. { 189, 2 },
  97756. { 190, 1 },
  97757. { 190, 1 },
  97758. { 190, 1 },
  97759. { 147, 4 },
  97760. { 192, 2 },
  97761. { 192, 0 },
  97762. { 147, 8 },
  97763. { 147, 4 },
  97764. { 147, 1 },
  97765. { 160, 1 },
  97766. { 160, 3 },
  97767. { 195, 1 },
  97768. { 195, 2 },
  97769. { 195, 1 },
  97770. { 194, 9 },
  97771. { 196, 1 },
  97772. { 196, 1 },
  97773. { 196, 0 },
  97774. { 204, 2 },
  97775. { 204, 0 },
  97776. { 197, 3 },
  97777. { 197, 2 },
  97778. { 197, 4 },
  97779. { 205, 2 },
  97780. { 205, 1 },
  97781. { 205, 0 },
  97782. { 198, 0 },
  97783. { 198, 2 },
  97784. { 207, 2 },
  97785. { 207, 0 },
  97786. { 206, 7 },
  97787. { 206, 7 },
  97788. { 206, 7 },
  97789. { 157, 0 },
  97790. { 157, 2 },
  97791. { 193, 2 },
  97792. { 208, 1 },
  97793. { 208, 2 },
  97794. { 208, 3 },
  97795. { 208, 4 },
  97796. { 210, 2 },
  97797. { 210, 0 },
  97798. { 209, 0 },
  97799. { 209, 3 },
  97800. { 209, 2 },
  97801. { 211, 4 },
  97802. { 211, 0 },
  97803. { 202, 0 },
  97804. { 202, 3 },
  97805. { 214, 4 },
  97806. { 214, 2 },
  97807. { 176, 1 },
  97808. { 176, 1 },
  97809. { 176, 0 },
  97810. { 200, 0 },
  97811. { 200, 3 },
  97812. { 201, 0 },
  97813. { 201, 2 },
  97814. { 203, 0 },
  97815. { 203, 2 },
  97816. { 203, 4 },
  97817. { 203, 4 },
  97818. { 147, 5 },
  97819. { 199, 0 },
  97820. { 199, 2 },
  97821. { 147, 7 },
  97822. { 216, 5 },
  97823. { 216, 3 },
  97824. { 147, 5 },
  97825. { 147, 5 },
  97826. { 147, 6 },
  97827. { 217, 2 },
  97828. { 217, 1 },
  97829. { 219, 4 },
  97830. { 219, 5 },
  97831. { 218, 0 },
  97832. { 218, 3 },
  97833. { 213, 3 },
  97834. { 213, 1 },
  97835. { 174, 1 },
  97836. { 174, 3 },
  97837. { 173, 1 },
  97838. { 174, 1 },
  97839. { 174, 1 },
  97840. { 174, 3 },
  97841. { 174, 5 },
  97842. { 173, 1 },
  97843. { 173, 1 },
  97844. { 174, 1 },
  97845. { 174, 1 },
  97846. { 174, 3 },
  97847. { 174, 6 },
  97848. { 174, 5 },
  97849. { 174, 4 },
  97850. { 173, 1 },
  97851. { 174, 3 },
  97852. { 174, 3 },
  97853. { 174, 3 },
  97854. { 174, 3 },
  97855. { 174, 3 },
  97856. { 174, 3 },
  97857. { 174, 3 },
  97858. { 174, 3 },
  97859. { 221, 1 },
  97860. { 221, 2 },
  97861. { 221, 1 },
  97862. { 221, 2 },
  97863. { 174, 3 },
  97864. { 174, 5 },
  97865. { 174, 2 },
  97866. { 174, 3 },
  97867. { 174, 3 },
  97868. { 174, 4 },
  97869. { 174, 2 },
  97870. { 174, 2 },
  97871. { 174, 2 },
  97872. { 174, 2 },
  97873. { 222, 1 },
  97874. { 222, 2 },
  97875. { 174, 5 },
  97876. { 223, 1 },
  97877. { 223, 2 },
  97878. { 174, 5 },
  97879. { 174, 3 },
  97880. { 174, 5 },
  97881. { 174, 4 },
  97882. { 174, 4 },
  97883. { 174, 5 },
  97884. { 225, 5 },
  97885. { 225, 4 },
  97886. { 226, 2 },
  97887. { 226, 0 },
  97888. { 224, 1 },
  97889. { 224, 0 },
  97890. { 220, 1 },
  97891. { 220, 0 },
  97892. { 215, 3 },
  97893. { 215, 1 },
  97894. { 147, 12 },
  97895. { 227, 1 },
  97896. { 227, 0 },
  97897. { 178, 0 },
  97898. { 178, 3 },
  97899. { 187, 5 },
  97900. { 187, 3 },
  97901. { 228, 0 },
  97902. { 228, 2 },
  97903. { 147, 4 },
  97904. { 147, 1 },
  97905. { 147, 2 },
  97906. { 147, 3 },
  97907. { 147, 5 },
  97908. { 147, 6 },
  97909. { 147, 5 },
  97910. { 147, 6 },
  97911. { 229, 1 },
  97912. { 229, 1 },
  97913. { 229, 1 },
  97914. { 229, 1 },
  97915. { 229, 1 },
  97916. { 170, 2 },
  97917. { 170, 1 },
  97918. { 171, 2 },
  97919. { 230, 1 },
  97920. { 147, 5 },
  97921. { 231, 11 },
  97922. { 233, 1 },
  97923. { 233, 1 },
  97924. { 233, 2 },
  97925. { 233, 0 },
  97926. { 234, 1 },
  97927. { 234, 1 },
  97928. { 234, 3 },
  97929. { 235, 0 },
  97930. { 235, 3 },
  97931. { 236, 0 },
  97932. { 236, 2 },
  97933. { 232, 3 },
  97934. { 232, 2 },
  97935. { 238, 1 },
  97936. { 238, 3 },
  97937. { 239, 0 },
  97938. { 239, 3 },
  97939. { 239, 2 },
  97940. { 237, 7 },
  97941. { 237, 5 },
  97942. { 237, 5 },
  97943. { 237, 5 },
  97944. { 237, 1 },
  97945. { 174, 4 },
  97946. { 174, 6 },
  97947. { 191, 1 },
  97948. { 191, 1 },
  97949. { 191, 1 },
  97950. { 147, 4 },
  97951. { 147, 6 },
  97952. { 147, 3 },
  97953. { 241, 0 },
  97954. { 241, 2 },
  97955. { 240, 1 },
  97956. { 240, 0 },
  97957. { 147, 1 },
  97958. { 147, 3 },
  97959. { 147, 1 },
  97960. { 147, 3 },
  97961. { 147, 6 },
  97962. { 147, 6 },
  97963. { 242, 1 },
  97964. { 243, 0 },
  97965. { 243, 1 },
  97966. { 147, 1 },
  97967. { 147, 4 },
  97968. { 244, 8 },
  97969. { 245, 1 },
  97970. { 245, 3 },
  97971. { 246, 0 },
  97972. { 246, 2 },
  97973. { 247, 1 },
  97974. { 247, 3 },
  97975. { 248, 1 },
  97976. { 249, 0 },
  97977. { 249, 4 },
  97978. { 249, 2 },
  97979. };
  97980. static void yy_accept(yyParser*); /* Forward Declaration */
  97981. /*
  97982. ** Perform a reduce action and the shift that must immediately
  97983. ** follow the reduce.
  97984. */
  97985. static void yy_reduce(
  97986. yyParser *yypParser, /* The parser */
  97987. int yyruleno /* Number of the rule by which to reduce */
  97988. ){
  97989. int yygoto; /* The next state */
  97990. int yyact; /* The next action */
  97991. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  97992. yyStackEntry *yymsp; /* The top of the parser's stack */
  97993. int yysize; /* Amount to pop the stack */
  97994. sqlite3ParserARG_FETCH;
  97995. yymsp = &yypParser->yystack[yypParser->yyidx];
  97996. #ifndef NDEBUG
  97997. if( yyTraceFILE && yyruleno>=0
  97998. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  97999. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  98000. yyRuleName[yyruleno]);
  98001. }
  98002. #endif /* NDEBUG */
  98003. /* Silence complaints from purify about yygotominor being uninitialized
  98004. ** in some cases when it is copied into the stack after the following
  98005. ** switch. yygotominor is uninitialized when a rule reduces that does
  98006. ** not set the value of its left-hand side nonterminal. Leaving the
  98007. ** value of the nonterminal uninitialized is utterly harmless as long
  98008. ** as the value is never used. So really the only thing this code
  98009. ** accomplishes is to quieten purify.
  98010. **
  98011. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  98012. ** without this code, their parser segfaults. I'm not sure what there
  98013. ** parser is doing to make this happen. This is the second bug report
  98014. ** from wireshark this week. Clearly they are stressing Lemon in ways
  98015. ** that it has not been previously stressed... (SQLite ticket #2172)
  98016. */
  98017. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  98018. yygotominor = yyzerominor;
  98019. switch( yyruleno ){
  98020. /* Beginning here are the reduction cases. A typical example
  98021. ** follows:
  98022. ** case 0:
  98023. ** #line <lineno> <grammarfile>
  98024. ** { ... } // User supplied code
  98025. ** #line <lineno> <thisfile>
  98026. ** break;
  98027. */
  98028. case 5: /* explain ::= */
  98029. { sqlite3BeginParse(pParse, 0); }
  98030. break;
  98031. case 6: /* explain ::= EXPLAIN */
  98032. { sqlite3BeginParse(pParse, 1); }
  98033. break;
  98034. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  98035. { sqlite3BeginParse(pParse, 2); }
  98036. break;
  98037. case 8: /* cmdx ::= cmd */
  98038. { sqlite3FinishCoding(pParse); }
  98039. break;
  98040. case 9: /* cmd ::= BEGIN transtype trans_opt */
  98041. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  98042. break;
  98043. case 13: /* transtype ::= */
  98044. {yygotominor.yy392 = TK_DEFERRED;}
  98045. break;
  98046. case 14: /* transtype ::= DEFERRED */
  98047. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  98048. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  98049. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  98050. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  98051. {yygotominor.yy392 = yymsp[0].major;}
  98052. break;
  98053. case 17: /* cmd ::= COMMIT trans_opt */
  98054. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  98055. {sqlite3CommitTransaction(pParse);}
  98056. break;
  98057. case 19: /* cmd ::= ROLLBACK trans_opt */
  98058. {sqlite3RollbackTransaction(pParse);}
  98059. break;
  98060. case 22: /* cmd ::= SAVEPOINT nm */
  98061. {
  98062. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  98063. }
  98064. break;
  98065. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  98066. {
  98067. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  98068. }
  98069. break;
  98070. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  98071. {
  98072. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  98073. }
  98074. break;
  98075. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  98076. {
  98077. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  98078. }
  98079. break;
  98080. case 27: /* createkw ::= CREATE */
  98081. {
  98082. pParse->db->lookaside.bEnabled = 0;
  98083. yygotominor.yy0 = yymsp[0].minor.yy0;
  98084. }
  98085. break;
  98086. case 28: /* ifnotexists ::= */
  98087. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  98088. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  98089. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  98090. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  98091. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  98092. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  98093. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  98094. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  98095. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  98096. {yygotominor.yy392 = 0;}
  98097. break;
  98098. case 29: /* ifnotexists ::= IF NOT EXISTS */
  98099. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  98100. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  98101. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  98102. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  98103. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  98104. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  98105. {yygotominor.yy392 = 1;}
  98106. break;
  98107. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  98108. {
  98109. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  98110. }
  98111. break;
  98112. case 33: /* create_table_args ::= AS select */
  98113. {
  98114. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  98115. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  98116. }
  98117. break;
  98118. case 36: /* column ::= columnid type carglist */
  98119. {
  98120. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  98121. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  98122. }
  98123. break;
  98124. case 37: /* columnid ::= nm */
  98125. {
  98126. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  98127. yygotominor.yy0 = yymsp[0].minor.yy0;
  98128. pParse->constraintName.n = 0;
  98129. }
  98130. break;
  98131. case 38: /* id ::= ID */
  98132. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  98133. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  98134. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  98135. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  98136. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  98137. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  98138. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  98139. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  98140. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  98141. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  98142. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  98143. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  98144. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  98145. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  98146. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  98147. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  98148. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  98149. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  98150. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  98151. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  98152. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  98153. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  98154. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  98155. break;
  98156. case 45: /* type ::= typetoken */
  98157. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  98158. break;
  98159. case 47: /* typetoken ::= typename LP signed RP */
  98160. {
  98161. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  98162. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  98163. }
  98164. break;
  98165. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  98166. {
  98167. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  98168. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  98169. }
  98170. break;
  98171. case 50: /* typename ::= typename ids */
  98172. {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  98173. break;
  98174. case 55: /* ccons ::= CONSTRAINT nm */
  98175. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  98176. {pParse->constraintName = yymsp[0].minor.yy0;}
  98177. break;
  98178. case 56: /* ccons ::= DEFAULT term */
  98179. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  98180. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  98181. break;
  98182. case 57: /* ccons ::= DEFAULT LP expr RP */
  98183. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  98184. break;
  98185. case 59: /* ccons ::= DEFAULT MINUS term */
  98186. {
  98187. ExprSpan v;
  98188. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  98189. v.zStart = yymsp[-1].minor.yy0.z;
  98190. v.zEnd = yymsp[0].minor.yy342.zEnd;
  98191. sqlite3AddDefaultValue(pParse,&v);
  98192. }
  98193. break;
  98194. case 60: /* ccons ::= DEFAULT id */
  98195. {
  98196. ExprSpan v;
  98197. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  98198. sqlite3AddDefaultValue(pParse,&v);
  98199. }
  98200. break;
  98201. case 62: /* ccons ::= NOT NULL onconf */
  98202. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  98203. break;
  98204. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  98205. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  98206. break;
  98207. case 64: /* ccons ::= UNIQUE onconf */
  98208. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  98209. break;
  98210. case 65: /* ccons ::= CHECK LP expr RP */
  98211. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  98212. break;
  98213. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  98214. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  98215. break;
  98216. case 67: /* ccons ::= defer_subclause */
  98217. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  98218. break;
  98219. case 68: /* ccons ::= COLLATE ids */
  98220. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  98221. break;
  98222. case 71: /* refargs ::= */
  98223. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  98224. break;
  98225. case 72: /* refargs ::= refargs refarg */
  98226. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  98227. break;
  98228. case 73: /* refarg ::= MATCH nm */
  98229. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  98230. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  98231. break;
  98232. case 75: /* refarg ::= ON DELETE refact */
  98233. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  98234. break;
  98235. case 76: /* refarg ::= ON UPDATE refact */
  98236. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  98237. break;
  98238. case 77: /* refact ::= SET NULL */
  98239. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  98240. break;
  98241. case 78: /* refact ::= SET DEFAULT */
  98242. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  98243. break;
  98244. case 79: /* refact ::= CASCADE */
  98245. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  98246. break;
  98247. case 80: /* refact ::= RESTRICT */
  98248. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  98249. break;
  98250. case 81: /* refact ::= NO ACTION */
  98251. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  98252. break;
  98253. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  98254. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  98255. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  98256. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  98257. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  98258. break;
  98259. case 87: /* conslist_opt ::= */
  98260. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  98261. break;
  98262. case 88: /* conslist_opt ::= COMMA conslist */
  98263. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  98264. break;
  98265. case 91: /* tconscomma ::= COMMA */
  98266. {pParse->constraintName.n = 0;}
  98267. break;
  98268. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  98269. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  98270. break;
  98271. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  98272. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  98273. break;
  98274. case 96: /* tcons ::= CHECK LP expr RP onconf */
  98275. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  98276. break;
  98277. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  98278. {
  98279. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  98280. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  98281. }
  98282. break;
  98283. case 100: /* onconf ::= */
  98284. {yygotominor.yy392 = OE_Default;}
  98285. break;
  98286. case 102: /* orconf ::= */
  98287. {yygotominor.yy258 = OE_Default;}
  98288. break;
  98289. case 103: /* orconf ::= OR resolvetype */
  98290. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  98291. break;
  98292. case 105: /* resolvetype ::= IGNORE */
  98293. {yygotominor.yy392 = OE_Ignore;}
  98294. break;
  98295. case 106: /* resolvetype ::= REPLACE */
  98296. {yygotominor.yy392 = OE_Replace;}
  98297. break;
  98298. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  98299. {
  98300. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  98301. }
  98302. break;
  98303. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  98304. {
  98305. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
  98306. }
  98307. break;
  98308. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  98309. {
  98310. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  98311. }
  98312. break;
  98313. case 112: /* cmd ::= select */
  98314. {
  98315. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  98316. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  98317. sqlite3ExplainBegin(pParse->pVdbe);
  98318. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  98319. sqlite3ExplainFinish(pParse->pVdbe);
  98320. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  98321. }
  98322. break;
  98323. case 113: /* select ::= oneselect */
  98324. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  98325. break;
  98326. case 114: /* select ::= select multiselect_op oneselect */
  98327. {
  98328. if( yymsp[0].minor.yy159 ){
  98329. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  98330. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  98331. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  98332. }else{
  98333. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  98334. }
  98335. yygotominor.yy159 = yymsp[0].minor.yy159;
  98336. }
  98337. break;
  98338. case 116: /* multiselect_op ::= UNION ALL */
  98339. {yygotominor.yy392 = TK_ALL;}
  98340. break;
  98341. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  98342. {
  98343. yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  98344. }
  98345. break;
  98346. case 119: /* distinct ::= DISTINCT */
  98347. {yygotominor.yy305 = SF_Distinct;}
  98348. break;
  98349. case 120: /* distinct ::= ALL */
  98350. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  98351. {yygotominor.yy305 = 0;}
  98352. break;
  98353. case 122: /* sclp ::= selcollist COMMA */
  98354. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  98355. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  98356. break;
  98357. case 123: /* sclp ::= */
  98358. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  98359. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  98360. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  98361. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  98362. {yygotominor.yy442 = 0;}
  98363. break;
  98364. case 124: /* selcollist ::= sclp expr as */
  98365. {
  98366. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  98367. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  98368. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  98369. }
  98370. break;
  98371. case 125: /* selcollist ::= sclp STAR */
  98372. {
  98373. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  98374. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  98375. }
  98376. break;
  98377. case 126: /* selcollist ::= sclp nm DOT STAR */
  98378. {
  98379. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  98380. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98381. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  98382. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  98383. }
  98384. break;
  98385. case 129: /* as ::= */
  98386. {yygotominor.yy0.n = 0;}
  98387. break;
  98388. case 130: /* from ::= */
  98389. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  98390. break;
  98391. case 131: /* from ::= FROM seltablist */
  98392. {
  98393. yygotominor.yy347 = yymsp[0].minor.yy347;
  98394. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  98395. }
  98396. break;
  98397. case 132: /* stl_prefix ::= seltablist joinop */
  98398. {
  98399. yygotominor.yy347 = yymsp[-1].minor.yy347;
  98400. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  98401. }
  98402. break;
  98403. case 133: /* stl_prefix ::= */
  98404. {yygotominor.yy347 = 0;}
  98405. break;
  98406. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  98407. {
  98408. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98409. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  98410. }
  98411. break;
  98412. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  98413. {
  98414. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98415. }
  98416. break;
  98417. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  98418. {
  98419. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  98420. yygotominor.yy347 = yymsp[-4].minor.yy347;
  98421. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  98422. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98423. if( yygotominor.yy347 ){
  98424. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  98425. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  98426. pNew->zName = pOld->zName;
  98427. pNew->zDatabase = pOld->zDatabase;
  98428. pNew->pSelect = pOld->pSelect;
  98429. pOld->zName = pOld->zDatabase = 0;
  98430. pOld->pSelect = 0;
  98431. }
  98432. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  98433. }else{
  98434. Select *pSubquery;
  98435. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  98436. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  98437. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  98438. }
  98439. }
  98440. break;
  98441. case 137: /* dbnm ::= */
  98442. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  98443. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  98444. break;
  98445. case 139: /* fullname ::= nm dbnm */
  98446. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  98447. break;
  98448. case 140: /* joinop ::= COMMA|JOIN */
  98449. { yygotominor.yy392 = JT_INNER; }
  98450. break;
  98451. case 141: /* joinop ::= JOIN_KW JOIN */
  98452. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  98453. break;
  98454. case 142: /* joinop ::= JOIN_KW nm JOIN */
  98455. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  98456. break;
  98457. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  98458. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  98459. break;
  98460. case 144: /* on_opt ::= ON expr */
  98461. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  98462. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  98463. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  98464. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  98465. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  98466. break;
  98467. case 145: /* on_opt ::= */
  98468. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  98469. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  98470. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  98471. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  98472. {yygotominor.yy122 = 0;}
  98473. break;
  98474. case 148: /* indexed_opt ::= NOT INDEXED */
  98475. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  98476. break;
  98477. case 149: /* using_opt ::= USING LP inscollist RP */
  98478. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  98479. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  98480. break;
  98481. case 150: /* using_opt ::= */
  98482. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  98483. {yygotominor.yy180 = 0;}
  98484. break;
  98485. case 152: /* orderby_opt ::= ORDER BY sortlist */
  98486. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  98487. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  98488. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  98489. break;
  98490. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  98491. {
  98492. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  98493. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98494. }
  98495. break;
  98496. case 154: /* sortlist ::= expr sortorder */
  98497. {
  98498. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  98499. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  98500. }
  98501. break;
  98502. case 155: /* sortorder ::= ASC */
  98503. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  98504. {yygotominor.yy392 = SQLITE_SO_ASC;}
  98505. break;
  98506. case 156: /* sortorder ::= DESC */
  98507. {yygotominor.yy392 = SQLITE_SO_DESC;}
  98508. break;
  98509. case 162: /* limit_opt ::= */
  98510. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  98511. break;
  98512. case 163: /* limit_opt ::= LIMIT expr */
  98513. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  98514. break;
  98515. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  98516. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  98517. break;
  98518. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  98519. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  98520. break;
  98521. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  98522. {
  98523. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  98524. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  98525. }
  98526. break;
  98527. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  98528. {
  98529. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  98530. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  98531. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  98532. }
  98533. break;
  98534. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  98535. {
  98536. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  98537. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98538. }
  98539. break;
  98540. case 171: /* setlist ::= nm EQ expr */
  98541. {
  98542. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  98543. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98544. }
  98545. break;
  98546. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  98547. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  98548. break;
  98549. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  98550. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  98551. break;
  98552. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  98553. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  98554. break;
  98555. case 175: /* insert_cmd ::= INSERT orconf */
  98556. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  98557. break;
  98558. case 176: /* insert_cmd ::= REPLACE */
  98559. {yygotominor.yy258 = OE_Replace;}
  98560. break;
  98561. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  98562. {
  98563. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  98564. yygotominor.yy487.pSelect = 0;
  98565. }
  98566. break;
  98567. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  98568. {
  98569. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  98570. if( yymsp[-4].minor.yy487.pList ){
  98571. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  98572. yymsp[-4].minor.yy487.pList = 0;
  98573. }
  98574. yygotominor.yy487.pList = 0;
  98575. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  98576. sqlite3SelectDelete(pParse->db, pRight);
  98577. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  98578. yygotominor.yy487.pSelect = 0;
  98579. }else{
  98580. pRight->op = TK_ALL;
  98581. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  98582. pRight->selFlags |= SF_Values;
  98583. pRight->pPrior->selFlags |= SF_Values;
  98584. yygotominor.yy487.pSelect = pRight;
  98585. }
  98586. }
  98587. break;
  98588. case 181: /* inscollist ::= inscollist COMMA nm */
  98589. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  98590. break;
  98591. case 182: /* inscollist ::= nm */
  98592. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  98593. break;
  98594. case 183: /* expr ::= term */
  98595. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  98596. break;
  98597. case 184: /* expr ::= LP expr RP */
  98598. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  98599. break;
  98600. case 185: /* term ::= NULL */
  98601. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  98602. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  98603. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  98604. break;
  98605. case 186: /* expr ::= id */
  98606. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  98607. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  98608. break;
  98609. case 188: /* expr ::= nm DOT nm */
  98610. {
  98611. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98612. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98613. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  98614. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  98615. }
  98616. break;
  98617. case 189: /* expr ::= nm DOT nm DOT nm */
  98618. {
  98619. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  98620. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98621. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98622. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  98623. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  98624. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98625. }
  98626. break;
  98627. case 192: /* expr ::= REGISTER */
  98628. {
  98629. /* When doing a nested parse, one can include terms in an expression
  98630. ** that look like this: #1 #2 ... These terms refer to registers
  98631. ** in the virtual machine. #N is the N-th register. */
  98632. if( pParse->nested==0 ){
  98633. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  98634. yygotominor.yy342.pExpr = 0;
  98635. }else{
  98636. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  98637. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  98638. }
  98639. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98640. }
  98641. break;
  98642. case 193: /* expr ::= VARIABLE */
  98643. {
  98644. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  98645. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  98646. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98647. }
  98648. break;
  98649. case 194: /* expr ::= expr COLLATE ids */
  98650. {
  98651. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  98652. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  98653. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98654. }
  98655. break;
  98656. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  98657. {
  98658. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  98659. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  98660. }
  98661. break;
  98662. case 196: /* expr ::= ID LP distinct exprlist RP */
  98663. {
  98664. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  98665. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  98666. }
  98667. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  98668. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98669. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  98670. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  98671. }
  98672. }
  98673. break;
  98674. case 197: /* expr ::= ID LP STAR RP */
  98675. {
  98676. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  98677. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  98678. }
  98679. break;
  98680. case 198: /* term ::= CTIME_KW */
  98681. {
  98682. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  98683. ** treated as functions that return constants */
  98684. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  98685. if( yygotominor.yy342.pExpr ){
  98686. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  98687. }
  98688. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98689. }
  98690. break;
  98691. case 199: /* expr ::= expr AND expr */
  98692. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  98693. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  98694. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  98695. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  98696. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  98697. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  98698. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  98699. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  98700. break;
  98701. case 207: /* likeop ::= LIKE_KW */
  98702. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  98703. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  98704. break;
  98705. case 208: /* likeop ::= NOT LIKE_KW */
  98706. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  98707. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  98708. break;
  98709. case 211: /* expr ::= expr likeop expr */
  98710. {
  98711. ExprList *pList;
  98712. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  98713. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  98714. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  98715. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98716. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  98717. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98718. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  98719. }
  98720. break;
  98721. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  98722. {
  98723. ExprList *pList;
  98724. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98725. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  98726. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  98727. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  98728. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98729. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98730. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98731. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  98732. }
  98733. break;
  98734. case 213: /* expr ::= expr ISNULL|NOTNULL */
  98735. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  98736. break;
  98737. case 214: /* expr ::= expr NOT NULL */
  98738. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  98739. break;
  98740. case 215: /* expr ::= expr IS expr */
  98741. {
  98742. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  98743. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  98744. }
  98745. break;
  98746. case 216: /* expr ::= expr IS NOT expr */
  98747. {
  98748. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  98749. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  98750. }
  98751. break;
  98752. case 217: /* expr ::= NOT expr */
  98753. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  98754. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98755. break;
  98756. case 219: /* expr ::= MINUS expr */
  98757. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98758. break;
  98759. case 220: /* expr ::= PLUS expr */
  98760. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  98761. break;
  98762. case 223: /* expr ::= expr between_op expr AND expr */
  98763. {
  98764. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98765. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  98766. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98767. if( yygotominor.yy342.pExpr ){
  98768. yygotominor.yy342.pExpr->x.pList = pList;
  98769. }else{
  98770. sqlite3ExprListDelete(pParse->db, pList);
  98771. }
  98772. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98773. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98774. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  98775. }
  98776. break;
  98777. case 226: /* expr ::= expr in_op LP exprlist RP */
  98778. {
  98779. if( yymsp[-1].minor.yy442==0 ){
  98780. /* Expressions of the form
  98781. **
  98782. ** expr1 IN ()
  98783. ** expr1 NOT IN ()
  98784. **
  98785. ** simplify to constants 0 (false) and 1 (true), respectively,
  98786. ** regardless of the value of expr1.
  98787. */
  98788. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  98789. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  98790. }else{
  98791. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98792. if( yygotominor.yy342.pExpr ){
  98793. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  98794. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98795. }else{
  98796. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  98797. }
  98798. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98799. }
  98800. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98801. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98802. }
  98803. break;
  98804. case 227: /* expr ::= LP select RP */
  98805. {
  98806. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  98807. if( yygotominor.yy342.pExpr ){
  98808. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  98809. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98810. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98811. }else{
  98812. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98813. }
  98814. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  98815. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98816. }
  98817. break;
  98818. case 228: /* expr ::= expr in_op LP select RP */
  98819. {
  98820. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  98821. if( yygotominor.yy342.pExpr ){
  98822. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  98823. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98824. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98825. }else{
  98826. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98827. }
  98828. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98829. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  98830. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98831. }
  98832. break;
  98833. case 229: /* expr ::= expr in_op nm dbnm */
  98834. {
  98835. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  98836. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  98837. if( yygotominor.yy342.pExpr ){
  98838. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  98839. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  98840. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98841. }else{
  98842. sqlite3SrcListDelete(pParse->db, pSrc);
  98843. }
  98844. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  98845. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  98846. yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  98847. }
  98848. break;
  98849. case 230: /* expr ::= EXISTS LP select RP */
  98850. {
  98851. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  98852. if( p ){
  98853. p->x.pSelect = yymsp[-1].minor.yy159;
  98854. ExprSetProperty(p, EP_xIsSelect);
  98855. sqlite3ExprSetHeight(pParse, p);
  98856. }else{
  98857. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  98858. }
  98859. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  98860. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98861. }
  98862. break;
  98863. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  98864. {
  98865. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  98866. if( yygotominor.yy342.pExpr ){
  98867. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  98868. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  98869. }else{
  98870. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  98871. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  98872. }
  98873. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  98874. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98875. }
  98876. break;
  98877. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  98878. {
  98879. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  98880. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  98881. }
  98882. break;
  98883. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  98884. {
  98885. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  98886. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  98887. }
  98888. break;
  98889. case 240: /* nexprlist ::= nexprlist COMMA expr */
  98890. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  98891. break;
  98892. case 241: /* nexprlist ::= expr */
  98893. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  98894. break;
  98895. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  98896. {
  98897. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  98898. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  98899. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  98900. }
  98901. break;
  98902. case 243: /* uniqueflag ::= UNIQUE */
  98903. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  98904. {yygotominor.yy392 = OE_Abort;}
  98905. break;
  98906. case 244: /* uniqueflag ::= */
  98907. {yygotominor.yy392 = OE_None;}
  98908. break;
  98909. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  98910. {
  98911. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  98912. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  98913. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  98914. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  98915. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98916. }
  98917. break;
  98918. case 248: /* idxlist ::= nm collate sortorder */
  98919. {
  98920. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  98921. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  98922. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  98923. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  98924. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  98925. }
  98926. break;
  98927. case 249: /* collate ::= */
  98928. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  98929. break;
  98930. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  98931. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  98932. break;
  98933. case 252: /* cmd ::= VACUUM */
  98934. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  98935. {sqlite3Vacuum(pParse);}
  98936. break;
  98937. case 254: /* cmd ::= PRAGMA nm dbnm */
  98938. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  98939. break;
  98940. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  98941. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  98942. break;
  98943. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  98944. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  98945. break;
  98946. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  98947. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  98948. break;
  98949. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  98950. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  98951. break;
  98952. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  98953. {
  98954. Token all;
  98955. all.z = yymsp[-3].minor.yy0.z;
  98956. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  98957. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  98958. }
  98959. break;
  98960. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  98961. {
  98962. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
  98963. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  98964. }
  98965. break;
  98966. case 270: /* trigger_time ::= BEFORE */
  98967. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  98968. { yygotominor.yy392 = TK_BEFORE; }
  98969. break;
  98970. case 271: /* trigger_time ::= AFTER */
  98971. { yygotominor.yy392 = TK_AFTER; }
  98972. break;
  98973. case 272: /* trigger_time ::= INSTEAD OF */
  98974. { yygotominor.yy392 = TK_INSTEAD;}
  98975. break;
  98976. case 274: /* trigger_event ::= DELETE|INSERT */
  98977. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  98978. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  98979. break;
  98980. case 276: /* trigger_event ::= UPDATE OF inscollist */
  98981. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  98982. break;
  98983. case 279: /* when_clause ::= */
  98984. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  98985. { yygotominor.yy122 = 0; }
  98986. break;
  98987. case 280: /* when_clause ::= WHEN expr */
  98988. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  98989. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  98990. break;
  98991. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  98992. {
  98993. assert( yymsp[-2].minor.yy327!=0 );
  98994. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  98995. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  98996. yygotominor.yy327 = yymsp[-2].minor.yy327;
  98997. }
  98998. break;
  98999. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  99000. {
  99001. assert( yymsp[-1].minor.yy327!=0 );
  99002. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  99003. yygotominor.yy327 = yymsp[-1].minor.yy327;
  99004. }
  99005. break;
  99006. case 284: /* trnm ::= nm DOT nm */
  99007. {
  99008. yygotominor.yy0 = yymsp[0].minor.yy0;
  99009. sqlite3ErrorMsg(pParse,
  99010. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  99011. "statements within triggers");
  99012. }
  99013. break;
  99014. case 286: /* tridxby ::= INDEXED BY nm */
  99015. {
  99016. sqlite3ErrorMsg(pParse,
  99017. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  99018. "within triggers");
  99019. }
  99020. break;
  99021. case 287: /* tridxby ::= NOT INDEXED */
  99022. {
  99023. sqlite3ErrorMsg(pParse,
  99024. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  99025. "within triggers");
  99026. }
  99027. break;
  99028. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  99029. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  99030. break;
  99031. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  99032. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
  99033. break;
  99034. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  99035. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  99036. break;
  99037. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  99038. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  99039. break;
  99040. case 292: /* trigger_cmd ::= select */
  99041. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  99042. break;
  99043. case 293: /* expr ::= RAISE LP IGNORE RP */
  99044. {
  99045. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  99046. if( yygotominor.yy342.pExpr ){
  99047. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  99048. }
  99049. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  99050. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  99051. }
  99052. break;
  99053. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  99054. {
  99055. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  99056. if( yygotominor.yy342.pExpr ) {
  99057. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  99058. }
  99059. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  99060. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  99061. }
  99062. break;
  99063. case 295: /* raisetype ::= ROLLBACK */
  99064. {yygotominor.yy392 = OE_Rollback;}
  99065. break;
  99066. case 297: /* raisetype ::= FAIL */
  99067. {yygotominor.yy392 = OE_Fail;}
  99068. break;
  99069. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  99070. {
  99071. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  99072. }
  99073. break;
  99074. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  99075. {
  99076. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  99077. }
  99078. break;
  99079. case 300: /* cmd ::= DETACH database_kw_opt expr */
  99080. {
  99081. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  99082. }
  99083. break;
  99084. case 305: /* cmd ::= REINDEX */
  99085. {sqlite3Reindex(pParse, 0, 0);}
  99086. break;
  99087. case 306: /* cmd ::= REINDEX nm dbnm */
  99088. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  99089. break;
  99090. case 307: /* cmd ::= ANALYZE */
  99091. {sqlite3Analyze(pParse, 0, 0);}
  99092. break;
  99093. case 308: /* cmd ::= ANALYZE nm dbnm */
  99094. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  99095. break;
  99096. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  99097. {
  99098. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  99099. }
  99100. break;
  99101. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  99102. {
  99103. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  99104. }
  99105. break;
  99106. case 311: /* add_column_fullname ::= fullname */
  99107. {
  99108. pParse->db->lookaside.bEnabled = 0;
  99109. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  99110. }
  99111. break;
  99112. case 314: /* cmd ::= create_vtab */
  99113. {sqlite3VtabFinishParse(pParse,0);}
  99114. break;
  99115. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  99116. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  99117. break;
  99118. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  99119. {
  99120. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  99121. }
  99122. break;
  99123. case 319: /* vtabarg ::= */
  99124. {sqlite3VtabArgInit(pParse);}
  99125. break;
  99126. case 321: /* vtabargtoken ::= ANY */
  99127. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  99128. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  99129. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  99130. break;
  99131. default:
  99132. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  99133. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  99134. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  99135. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  99136. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  99137. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  99138. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  99139. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  99140. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  99141. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  99142. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  99143. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  99144. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  99145. /* (44) type ::= */ yytestcase(yyruleno==44);
  99146. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  99147. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  99148. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  99149. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  99150. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  99151. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  99152. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  99153. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  99154. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  99155. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  99156. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  99157. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  99158. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  99159. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  99160. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  99161. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  99162. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  99163. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  99164. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  99165. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  99166. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  99167. break;
  99168. };
  99169. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  99170. yygoto = yyRuleInfo[yyruleno].lhs;
  99171. yysize = yyRuleInfo[yyruleno].nrhs;
  99172. yypParser->yyidx -= yysize;
  99173. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  99174. if( yyact < YYNSTATE ){
  99175. #ifdef NDEBUG
  99176. /* If we are not debugging and the reduce action popped at least
  99177. ** one element off the stack, then we can push the new element back
  99178. ** onto the stack here, and skip the stack overflow test in yy_shift().
  99179. ** That gives a significant speed improvement. */
  99180. if( yysize ){
  99181. yypParser->yyidx++;
  99182. yymsp -= yysize-1;
  99183. yymsp->stateno = (YYACTIONTYPE)yyact;
  99184. yymsp->major = (YYCODETYPE)yygoto;
  99185. yymsp->minor = yygotominor;
  99186. }else
  99187. #endif
  99188. {
  99189. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  99190. }
  99191. }else{
  99192. assert( yyact == YYNSTATE + YYNRULE + 1 );
  99193. yy_accept(yypParser);
  99194. }
  99195. }
  99196. /*
  99197. ** The following code executes when the parse fails
  99198. */
  99199. #ifndef YYNOERRORRECOVERY
  99200. static void yy_parse_failed(
  99201. yyParser *yypParser /* The parser */
  99202. ){
  99203. sqlite3ParserARG_FETCH;
  99204. #ifndef NDEBUG
  99205. if( yyTraceFILE ){
  99206. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  99207. }
  99208. #endif
  99209. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99210. /* Here code is inserted which will be executed whenever the
  99211. ** parser fails */
  99212. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99213. }
  99214. #endif /* YYNOERRORRECOVERY */
  99215. /*
  99216. ** The following code executes when a syntax error first occurs.
  99217. */
  99218. static void yy_syntax_error(
  99219. yyParser *yypParser, /* The parser */
  99220. int yymajor, /* The major type of the error token */
  99221. YYMINORTYPE yyminor /* The minor type of the error token */
  99222. ){
  99223. sqlite3ParserARG_FETCH;
  99224. #define TOKEN (yyminor.yy0)
  99225. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  99226. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  99227. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  99228. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99229. }
  99230. /*
  99231. ** The following is executed when the parser accepts
  99232. */
  99233. static void yy_accept(
  99234. yyParser *yypParser /* The parser */
  99235. ){
  99236. sqlite3ParserARG_FETCH;
  99237. #ifndef NDEBUG
  99238. if( yyTraceFILE ){
  99239. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  99240. }
  99241. #endif
  99242. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99243. /* Here code is inserted which will be executed whenever the
  99244. ** parser accepts */
  99245. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99246. }
  99247. /* The main parser program.
  99248. ** The first argument is a pointer to a structure obtained from
  99249. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  99250. ** The second argument is the major token number. The third is
  99251. ** the minor token. The fourth optional argument is whatever the
  99252. ** user wants (and specified in the grammar) and is available for
  99253. ** use by the action routines.
  99254. **
  99255. ** Inputs:
  99256. ** <ul>
  99257. ** <li> A pointer to the parser (an opaque structure.)
  99258. ** <li> The major token number.
  99259. ** <li> The minor token number.
  99260. ** <li> An option argument of a grammar-specified type.
  99261. ** </ul>
  99262. **
  99263. ** Outputs:
  99264. ** None.
  99265. */
  99266. SQLITE_PRIVATE void sqlite3Parser(
  99267. void *yyp, /* The parser */
  99268. int yymajor, /* The major token code number */
  99269. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  99270. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  99271. ){
  99272. YYMINORTYPE yyminorunion;
  99273. int yyact; /* The parser action. */
  99274. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  99275. int yyendofinput; /* True if we are at the end of input */
  99276. #endif
  99277. #ifdef YYERRORSYMBOL
  99278. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  99279. #endif
  99280. yyParser *yypParser; /* The parser */
  99281. /* (re)initialize the parser, if necessary */
  99282. yypParser = (yyParser*)yyp;
  99283. if( yypParser->yyidx<0 ){
  99284. #if YYSTACKDEPTH<=0
  99285. if( yypParser->yystksz <=0 ){
  99286. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  99287. yyminorunion = yyzerominor;
  99288. yyStackOverflow(yypParser, &yyminorunion);
  99289. return;
  99290. }
  99291. #endif
  99292. yypParser->yyidx = 0;
  99293. yypParser->yyerrcnt = -1;
  99294. yypParser->yystack[0].stateno = 0;
  99295. yypParser->yystack[0].major = 0;
  99296. }
  99297. yyminorunion.yy0 = yyminor;
  99298. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  99299. yyendofinput = (yymajor==0);
  99300. #endif
  99301. sqlite3ParserARG_STORE;
  99302. #ifndef NDEBUG
  99303. if( yyTraceFILE ){
  99304. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  99305. }
  99306. #endif
  99307. do{
  99308. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  99309. if( yyact<YYNSTATE ){
  99310. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  99311. yypParser->yyerrcnt--;
  99312. yymajor = YYNOCODE;
  99313. }else if( yyact < YYNSTATE + YYNRULE ){
  99314. yy_reduce(yypParser,yyact-YYNSTATE);
  99315. }else{
  99316. assert( yyact == YY_ERROR_ACTION );
  99317. #ifdef YYERRORSYMBOL
  99318. int yymx;
  99319. #endif
  99320. #ifndef NDEBUG
  99321. if( yyTraceFILE ){
  99322. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  99323. }
  99324. #endif
  99325. #ifdef YYERRORSYMBOL
  99326. /* A syntax error has occurred.
  99327. ** The response to an error depends upon whether or not the
  99328. ** grammar defines an error token "ERROR".
  99329. **
  99330. ** This is what we do if the grammar does define ERROR:
  99331. **
  99332. ** * Call the %syntax_error function.
  99333. **
  99334. ** * Begin popping the stack until we enter a state where
  99335. ** it is legal to shift the error symbol, then shift
  99336. ** the error symbol.
  99337. **
  99338. ** * Set the error count to three.
  99339. **
  99340. ** * Begin accepting and shifting new tokens. No new error
  99341. ** processing will occur until three tokens have been
  99342. ** shifted successfully.
  99343. **
  99344. */
  99345. if( yypParser->yyerrcnt<0 ){
  99346. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99347. }
  99348. yymx = yypParser->yystack[yypParser->yyidx].major;
  99349. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  99350. #ifndef NDEBUG
  99351. if( yyTraceFILE ){
  99352. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  99353. yyTracePrompt,yyTokenName[yymajor]);
  99354. }
  99355. #endif
  99356. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  99357. yymajor = YYNOCODE;
  99358. }else{
  99359. while(
  99360. yypParser->yyidx >= 0 &&
  99361. yymx != YYERRORSYMBOL &&
  99362. (yyact = yy_find_reduce_action(
  99363. yypParser->yystack[yypParser->yyidx].stateno,
  99364. YYERRORSYMBOL)) >= YYNSTATE
  99365. ){
  99366. yy_pop_parser_stack(yypParser);
  99367. }
  99368. if( yypParser->yyidx < 0 || yymajor==0 ){
  99369. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99370. yy_parse_failed(yypParser);
  99371. yymajor = YYNOCODE;
  99372. }else if( yymx!=YYERRORSYMBOL ){
  99373. YYMINORTYPE u2;
  99374. u2.YYERRSYMDT = 0;
  99375. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  99376. }
  99377. }
  99378. yypParser->yyerrcnt = 3;
  99379. yyerrorhit = 1;
  99380. #elif defined(YYNOERRORRECOVERY)
  99381. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  99382. ** do any kind of error recovery. Instead, simply invoke the syntax
  99383. ** error routine and continue going as if nothing had happened.
  99384. **
  99385. ** Applications can set this macro (for example inside %include) if
  99386. ** they intend to abandon the parse upon the first syntax error seen.
  99387. */
  99388. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99389. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99390. yymajor = YYNOCODE;
  99391. #else /* YYERRORSYMBOL is not defined */
  99392. /* This is what we do if the grammar does not define ERROR:
  99393. **
  99394. ** * Report an error message, and throw away the input token.
  99395. **
  99396. ** * If the input token is $, then fail the parse.
  99397. **
  99398. ** As before, subsequent error messages are suppressed until
  99399. ** three input tokens have been successfully shifted.
  99400. */
  99401. if( yypParser->yyerrcnt<=0 ){
  99402. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99403. }
  99404. yypParser->yyerrcnt = 3;
  99405. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99406. if( yyendofinput ){
  99407. yy_parse_failed(yypParser);
  99408. }
  99409. yymajor = YYNOCODE;
  99410. #endif
  99411. }
  99412. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  99413. return;
  99414. }
  99415. /************** End of parse.c ***********************************************/
  99416. /************** Begin file tokenize.c ****************************************/
  99417. /*
  99418. ** 2001 September 15
  99419. **
  99420. ** The author disclaims copyright to this source code. In place of
  99421. ** a legal notice, here is a blessing:
  99422. **
  99423. ** May you do good and not evil.
  99424. ** May you find forgiveness for yourself and forgive others.
  99425. ** May you share freely, never taking more than you give.
  99426. **
  99427. *************************************************************************
  99428. ** An tokenizer for SQL
  99429. **
  99430. ** This file contains C code that splits an SQL input string up into
  99431. ** individual tokens and sends those tokens one-by-one over to the
  99432. ** parser for analysis.
  99433. */
  99434. /* #include <stdlib.h> */
  99435. /*
  99436. ** The charMap() macro maps alphabetic characters into their
  99437. ** lower-case ASCII equivalent. On ASCII machines, this is just
  99438. ** an upper-to-lower case map. On EBCDIC machines we also need
  99439. ** to adjust the encoding. Only alphabetic characters and underscores
  99440. ** need to be translated.
  99441. */
  99442. #ifdef SQLITE_ASCII
  99443. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  99444. #endif
  99445. #ifdef SQLITE_EBCDIC
  99446. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  99447. const unsigned char ebcdicToAscii[] = {
  99448. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  99449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  99450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  99451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  99452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  99453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  99454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  99455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  99456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99457. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  99458. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  99459. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  99460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99461. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  99462. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  99463. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  99464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  99465. };
  99466. #endif
  99467. /*
  99468. ** The sqlite3KeywordCode function looks up an identifier to determine if
  99469. ** it is a keyword. If it is a keyword, the token code of that keyword is
  99470. ** returned. If the input is not a keyword, TK_ID is returned.
  99471. **
  99472. ** The implementation of this routine was generated by a program,
  99473. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  99474. ** The output of the mkkeywordhash.c program is written into a file
  99475. ** named keywordhash.h and then included into this source file by
  99476. ** the #include below.
  99477. */
  99478. /************** Include keywordhash.h in the middle of tokenize.c ************/
  99479. /************** Begin file keywordhash.h *************************************/
  99480. /***** This file contains automatically generated code ******
  99481. **
  99482. ** The code in this file has been automatically generated by
  99483. **
  99484. ** sqlite/tool/mkkeywordhash.c
  99485. **
  99486. ** The code in this file implements a function that determines whether
  99487. ** or not a given identifier is really an SQL keyword. The same thing
  99488. ** might be implemented more directly using a hand-written hash table.
  99489. ** But by using this automatically generated code, the size of the code
  99490. ** is substantially reduced. This is important for embedded applications
  99491. ** on platforms with limited memory.
  99492. */
  99493. /* Hash score: 175 */
  99494. static int keywordCode(const char *z, int n){
  99495. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  99496. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  99497. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  99498. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  99499. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  99500. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  99501. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  99502. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  99503. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  99504. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  99505. /* INITIALLY */
  99506. static const char zText[540] = {
  99507. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  99508. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  99509. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  99510. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  99511. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  99512. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  99513. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  99514. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  99515. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  99516. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  99517. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  99518. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  99519. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  99520. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  99521. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  99522. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  99523. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  99524. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  99525. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  99526. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  99527. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  99528. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  99529. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  99530. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  99531. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  99532. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  99533. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  99534. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  99535. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  99536. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  99537. };
  99538. static const unsigned char aHash[127] = {
  99539. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  99540. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  99541. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  99542. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  99543. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  99544. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  99545. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  99546. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  99547. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  99548. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  99549. };
  99550. static const unsigned char aNext[121] = {
  99551. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  99552. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  99553. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  99554. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  99555. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  99556. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  99557. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  99558. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  99559. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  99560. 35, 64, 0, 0,
  99561. };
  99562. static const unsigned char aLen[121] = {
  99563. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  99564. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  99565. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  99566. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  99567. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  99568. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  99569. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  99570. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  99571. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  99572. 6, 4, 9, 3,
  99573. };
  99574. static const unsigned short int aOffset[121] = {
  99575. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  99576. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  99577. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  99578. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  99579. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  99580. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  99581. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  99582. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  99583. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  99584. 521, 527, 531, 536,
  99585. };
  99586. static const unsigned char aCode[121] = {
  99587. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  99588. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  99589. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  99590. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  99591. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  99592. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  99593. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  99594. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  99595. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  99596. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  99597. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  99598. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  99599. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  99600. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  99601. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  99602. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  99603. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  99604. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  99605. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  99606. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  99607. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  99608. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  99609. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  99610. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  99611. TK_ALL,
  99612. };
  99613. int h, i;
  99614. if( n<2 ) return TK_ID;
  99615. h = ((charMap(z[0])*4) ^
  99616. (charMap(z[n-1])*3) ^
  99617. n) % 127;
  99618. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  99619. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  99620. testcase( i==0 ); /* REINDEX */
  99621. testcase( i==1 ); /* INDEXED */
  99622. testcase( i==2 ); /* INDEX */
  99623. testcase( i==3 ); /* DESC */
  99624. testcase( i==4 ); /* ESCAPE */
  99625. testcase( i==5 ); /* EACH */
  99626. testcase( i==6 ); /* CHECK */
  99627. testcase( i==7 ); /* KEY */
  99628. testcase( i==8 ); /* BEFORE */
  99629. testcase( i==9 ); /* FOREIGN */
  99630. testcase( i==10 ); /* FOR */
  99631. testcase( i==11 ); /* IGNORE */
  99632. testcase( i==12 ); /* REGEXP */
  99633. testcase( i==13 ); /* EXPLAIN */
  99634. testcase( i==14 ); /* INSTEAD */
  99635. testcase( i==15 ); /* ADD */
  99636. testcase( i==16 ); /* DATABASE */
  99637. testcase( i==17 ); /* AS */
  99638. testcase( i==18 ); /* SELECT */
  99639. testcase( i==19 ); /* TABLE */
  99640. testcase( i==20 ); /* LEFT */
  99641. testcase( i==21 ); /* THEN */
  99642. testcase( i==22 ); /* END */
  99643. testcase( i==23 ); /* DEFERRABLE */
  99644. testcase( i==24 ); /* ELSE */
  99645. testcase( i==25 ); /* EXCEPT */
  99646. testcase( i==26 ); /* TRANSACTION */
  99647. testcase( i==27 ); /* ACTION */
  99648. testcase( i==28 ); /* ON */
  99649. testcase( i==29 ); /* NATURAL */
  99650. testcase( i==30 ); /* ALTER */
  99651. testcase( i==31 ); /* RAISE */
  99652. testcase( i==32 ); /* EXCLUSIVE */
  99653. testcase( i==33 ); /* EXISTS */
  99654. testcase( i==34 ); /* SAVEPOINT */
  99655. testcase( i==35 ); /* INTERSECT */
  99656. testcase( i==36 ); /* TRIGGER */
  99657. testcase( i==37 ); /* REFERENCES */
  99658. testcase( i==38 ); /* CONSTRAINT */
  99659. testcase( i==39 ); /* INTO */
  99660. testcase( i==40 ); /* OFFSET */
  99661. testcase( i==41 ); /* OF */
  99662. testcase( i==42 ); /* SET */
  99663. testcase( i==43 ); /* TEMPORARY */
  99664. testcase( i==44 ); /* TEMP */
  99665. testcase( i==45 ); /* OR */
  99666. testcase( i==46 ); /* UNIQUE */
  99667. testcase( i==47 ); /* QUERY */
  99668. testcase( i==48 ); /* ATTACH */
  99669. testcase( i==49 ); /* HAVING */
  99670. testcase( i==50 ); /* GROUP */
  99671. testcase( i==51 ); /* UPDATE */
  99672. testcase( i==52 ); /* BEGIN */
  99673. testcase( i==53 ); /* INNER */
  99674. testcase( i==54 ); /* RELEASE */
  99675. testcase( i==55 ); /* BETWEEN */
  99676. testcase( i==56 ); /* NOTNULL */
  99677. testcase( i==57 ); /* NOT */
  99678. testcase( i==58 ); /* NO */
  99679. testcase( i==59 ); /* NULL */
  99680. testcase( i==60 ); /* LIKE */
  99681. testcase( i==61 ); /* CASCADE */
  99682. testcase( i==62 ); /* ASC */
  99683. testcase( i==63 ); /* DELETE */
  99684. testcase( i==64 ); /* CASE */
  99685. testcase( i==65 ); /* COLLATE */
  99686. testcase( i==66 ); /* CREATE */
  99687. testcase( i==67 ); /* CURRENT_DATE */
  99688. testcase( i==68 ); /* DETACH */
  99689. testcase( i==69 ); /* IMMEDIATE */
  99690. testcase( i==70 ); /* JOIN */
  99691. testcase( i==71 ); /* INSERT */
  99692. testcase( i==72 ); /* MATCH */
  99693. testcase( i==73 ); /* PLAN */
  99694. testcase( i==74 ); /* ANALYZE */
  99695. testcase( i==75 ); /* PRAGMA */
  99696. testcase( i==76 ); /* ABORT */
  99697. testcase( i==77 ); /* VALUES */
  99698. testcase( i==78 ); /* VIRTUAL */
  99699. testcase( i==79 ); /* LIMIT */
  99700. testcase( i==80 ); /* WHEN */
  99701. testcase( i==81 ); /* WHERE */
  99702. testcase( i==82 ); /* RENAME */
  99703. testcase( i==83 ); /* AFTER */
  99704. testcase( i==84 ); /* REPLACE */
  99705. testcase( i==85 ); /* AND */
  99706. testcase( i==86 ); /* DEFAULT */
  99707. testcase( i==87 ); /* AUTOINCREMENT */
  99708. testcase( i==88 ); /* TO */
  99709. testcase( i==89 ); /* IN */
  99710. testcase( i==90 ); /* CAST */
  99711. testcase( i==91 ); /* COLUMN */
  99712. testcase( i==92 ); /* COMMIT */
  99713. testcase( i==93 ); /* CONFLICT */
  99714. testcase( i==94 ); /* CROSS */
  99715. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  99716. testcase( i==96 ); /* CURRENT_TIME */
  99717. testcase( i==97 ); /* PRIMARY */
  99718. testcase( i==98 ); /* DEFERRED */
  99719. testcase( i==99 ); /* DISTINCT */
  99720. testcase( i==100 ); /* IS */
  99721. testcase( i==101 ); /* DROP */
  99722. testcase( i==102 ); /* FAIL */
  99723. testcase( i==103 ); /* FROM */
  99724. testcase( i==104 ); /* FULL */
  99725. testcase( i==105 ); /* GLOB */
  99726. testcase( i==106 ); /* BY */
  99727. testcase( i==107 ); /* IF */
  99728. testcase( i==108 ); /* ISNULL */
  99729. testcase( i==109 ); /* ORDER */
  99730. testcase( i==110 ); /* RESTRICT */
  99731. testcase( i==111 ); /* OUTER */
  99732. testcase( i==112 ); /* RIGHT */
  99733. testcase( i==113 ); /* ROLLBACK */
  99734. testcase( i==114 ); /* ROW */
  99735. testcase( i==115 ); /* UNION */
  99736. testcase( i==116 ); /* USING */
  99737. testcase( i==117 ); /* VACUUM */
  99738. testcase( i==118 ); /* VIEW */
  99739. testcase( i==119 ); /* INITIALLY */
  99740. testcase( i==120 ); /* ALL */
  99741. return aCode[i];
  99742. }
  99743. }
  99744. return TK_ID;
  99745. }
  99746. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  99747. return keywordCode((char*)z, n);
  99748. }
  99749. #define SQLITE_N_KEYWORD 121
  99750. /************** End of keywordhash.h *****************************************/
  99751. /************** Continuing where we left off in tokenize.c *******************/
  99752. /*
  99753. ** If X is a character that can be used in an identifier then
  99754. ** IdChar(X) will be true. Otherwise it is false.
  99755. **
  99756. ** For ASCII, any character with the high-order bit set is
  99757. ** allowed in an identifier. For 7-bit characters,
  99758. ** sqlite3IsIdChar[X] must be 1.
  99759. **
  99760. ** For EBCDIC, the rules are more complex but have the same
  99761. ** end result.
  99762. **
  99763. ** Ticket #1066. the SQL standard does not allow '$' in the
  99764. ** middle of identfiers. But many SQL implementations do.
  99765. ** SQLite will allow '$' in identifiers for compatibility.
  99766. ** But the feature is undocumented.
  99767. */
  99768. #ifdef SQLITE_ASCII
  99769. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  99770. #endif
  99771. #ifdef SQLITE_EBCDIC
  99772. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  99773. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  99774. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  99775. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  99776. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  99777. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99778. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  99779. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  99780. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  99781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99782. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  99783. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  99784. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  99785. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  99786. };
  99787. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  99788. #endif
  99789. /*
  99790. ** Return the length of the token that begins at z[0].
  99791. ** Store the token type in *tokenType before returning.
  99792. */
  99793. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  99794. int i, c;
  99795. switch( *z ){
  99796. case ' ': case '\t': case '\n': case '\f': case '\r': {
  99797. testcase( z[0]==' ' );
  99798. testcase( z[0]=='\t' );
  99799. testcase( z[0]=='\n' );
  99800. testcase( z[0]=='\f' );
  99801. testcase( z[0]=='\r' );
  99802. for(i=1; sqlite3Isspace(z[i]); i++){}
  99803. *tokenType = TK_SPACE;
  99804. return i;
  99805. }
  99806. case '-': {
  99807. if( z[1]=='-' ){
  99808. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  99809. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99810. return i;
  99811. }
  99812. *tokenType = TK_MINUS;
  99813. return 1;
  99814. }
  99815. case '(': {
  99816. *tokenType = TK_LP;
  99817. return 1;
  99818. }
  99819. case ')': {
  99820. *tokenType = TK_RP;
  99821. return 1;
  99822. }
  99823. case ';': {
  99824. *tokenType = TK_SEMI;
  99825. return 1;
  99826. }
  99827. case '+': {
  99828. *tokenType = TK_PLUS;
  99829. return 1;
  99830. }
  99831. case '*': {
  99832. *tokenType = TK_STAR;
  99833. return 1;
  99834. }
  99835. case '/': {
  99836. if( z[1]!='*' || z[2]==0 ){
  99837. *tokenType = TK_SLASH;
  99838. return 1;
  99839. }
  99840. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  99841. if( c ) i++;
  99842. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99843. return i;
  99844. }
  99845. case '%': {
  99846. *tokenType = TK_REM;
  99847. return 1;
  99848. }
  99849. case '=': {
  99850. *tokenType = TK_EQ;
  99851. return 1 + (z[1]=='=');
  99852. }
  99853. case '<': {
  99854. if( (c=z[1])=='=' ){
  99855. *tokenType = TK_LE;
  99856. return 2;
  99857. }else if( c=='>' ){
  99858. *tokenType = TK_NE;
  99859. return 2;
  99860. }else if( c=='<' ){
  99861. *tokenType = TK_LSHIFT;
  99862. return 2;
  99863. }else{
  99864. *tokenType = TK_LT;
  99865. return 1;
  99866. }
  99867. }
  99868. case '>': {
  99869. if( (c=z[1])=='=' ){
  99870. *tokenType = TK_GE;
  99871. return 2;
  99872. }else if( c=='>' ){
  99873. *tokenType = TK_RSHIFT;
  99874. return 2;
  99875. }else{
  99876. *tokenType = TK_GT;
  99877. return 1;
  99878. }
  99879. }
  99880. case '!': {
  99881. if( z[1]!='=' ){
  99882. *tokenType = TK_ILLEGAL;
  99883. return 2;
  99884. }else{
  99885. *tokenType = TK_NE;
  99886. return 2;
  99887. }
  99888. }
  99889. case '|': {
  99890. if( z[1]!='|' ){
  99891. *tokenType = TK_BITOR;
  99892. return 1;
  99893. }else{
  99894. *tokenType = TK_CONCAT;
  99895. return 2;
  99896. }
  99897. }
  99898. case ',': {
  99899. *tokenType = TK_COMMA;
  99900. return 1;
  99901. }
  99902. case '&': {
  99903. *tokenType = TK_BITAND;
  99904. return 1;
  99905. }
  99906. case '~': {
  99907. *tokenType = TK_BITNOT;
  99908. return 1;
  99909. }
  99910. case '`':
  99911. case '\'':
  99912. case '"': {
  99913. int delim = z[0];
  99914. testcase( delim=='`' );
  99915. testcase( delim=='\'' );
  99916. testcase( delim=='"' );
  99917. for(i=1; (c=z[i])!=0; i++){
  99918. if( c==delim ){
  99919. if( z[i+1]==delim ){
  99920. i++;
  99921. }else{
  99922. break;
  99923. }
  99924. }
  99925. }
  99926. if( c=='\'' ){
  99927. *tokenType = TK_STRING;
  99928. return i+1;
  99929. }else if( c!=0 ){
  99930. *tokenType = TK_ID;
  99931. return i+1;
  99932. }else{
  99933. *tokenType = TK_ILLEGAL;
  99934. return i;
  99935. }
  99936. }
  99937. case '.': {
  99938. #ifndef SQLITE_OMIT_FLOATING_POINT
  99939. if( !sqlite3Isdigit(z[1]) )
  99940. #endif
  99941. {
  99942. *tokenType = TK_DOT;
  99943. return 1;
  99944. }
  99945. /* If the next character is a digit, this is a floating point
  99946. ** number that begins with ".". Fall thru into the next case */
  99947. }
  99948. case '0': case '1': case '2': case '3': case '4':
  99949. case '5': case '6': case '7': case '8': case '9': {
  99950. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  99951. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  99952. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  99953. testcase( z[0]=='9' );
  99954. *tokenType = TK_INTEGER;
  99955. for(i=0; sqlite3Isdigit(z[i]); i++){}
  99956. #ifndef SQLITE_OMIT_FLOATING_POINT
  99957. if( z[i]=='.' ){
  99958. i++;
  99959. while( sqlite3Isdigit(z[i]) ){ i++; }
  99960. *tokenType = TK_FLOAT;
  99961. }
  99962. if( (z[i]=='e' || z[i]=='E') &&
  99963. ( sqlite3Isdigit(z[i+1])
  99964. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  99965. )
  99966. ){
  99967. i += 2;
  99968. while( sqlite3Isdigit(z[i]) ){ i++; }
  99969. *tokenType = TK_FLOAT;
  99970. }
  99971. #endif
  99972. while( IdChar(z[i]) ){
  99973. *tokenType = TK_ILLEGAL;
  99974. i++;
  99975. }
  99976. return i;
  99977. }
  99978. case '[': {
  99979. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  99980. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  99981. return i;
  99982. }
  99983. case '?': {
  99984. *tokenType = TK_VARIABLE;
  99985. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99986. return i;
  99987. }
  99988. case '#': {
  99989. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99990. if( i>1 ){
  99991. /* Parameters of the form #NNN (where NNN is a number) are used
  99992. ** internally by sqlite3NestedParse. */
  99993. *tokenType = TK_REGISTER;
  99994. return i;
  99995. }
  99996. /* Fall through into the next case if the '#' is not followed by
  99997. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  99998. }
  99999. #ifndef SQLITE_OMIT_TCL_VARIABLE
  100000. case '$':
  100001. #endif
  100002. case '@': /* For compatibility with MS SQL Server */
  100003. case ':': {
  100004. int n = 0;
  100005. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  100006. *tokenType = TK_VARIABLE;
  100007. for(i=1; (c=z[i])!=0; i++){
  100008. if( IdChar(c) ){
  100009. n++;
  100010. #ifndef SQLITE_OMIT_TCL_VARIABLE
  100011. }else if( c=='(' && n>0 ){
  100012. do{
  100013. i++;
  100014. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  100015. if( c==')' ){
  100016. i++;
  100017. }else{
  100018. *tokenType = TK_ILLEGAL;
  100019. }
  100020. break;
  100021. }else if( c==':' && z[i+1]==':' ){
  100022. i++;
  100023. #endif
  100024. }else{
  100025. break;
  100026. }
  100027. }
  100028. if( n==0 ) *tokenType = TK_ILLEGAL;
  100029. return i;
  100030. }
  100031. #ifndef SQLITE_OMIT_BLOB_LITERAL
  100032. case 'x': case 'X': {
  100033. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  100034. if( z[1]=='\'' ){
  100035. *tokenType = TK_BLOB;
  100036. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  100037. if( z[i]!='\'' || i%2 ){
  100038. *tokenType = TK_ILLEGAL;
  100039. while( z[i] && z[i]!='\'' ){ i++; }
  100040. }
  100041. if( z[i] ) i++;
  100042. return i;
  100043. }
  100044. /* Otherwise fall through to the next case */
  100045. }
  100046. #endif
  100047. default: {
  100048. if( !IdChar(*z) ){
  100049. break;
  100050. }
  100051. for(i=1; IdChar(z[i]); i++){}
  100052. *tokenType = keywordCode((char*)z, i);
  100053. return i;
  100054. }
  100055. }
  100056. *tokenType = TK_ILLEGAL;
  100057. return 1;
  100058. }
  100059. /*
  100060. ** Run the parser on the given SQL string. The parser structure is
  100061. ** passed in. An SQLITE_ status code is returned. If an error occurs
  100062. ** then an and attempt is made to write an error message into
  100063. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  100064. ** error message.
  100065. */
  100066. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  100067. int nErr = 0; /* Number of errors encountered */
  100068. int i; /* Loop counter */
  100069. void *pEngine; /* The LEMON-generated LALR(1) parser */
  100070. int tokenType; /* type of the next token */
  100071. int lastTokenParsed = -1; /* type of the previous token */
  100072. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  100073. sqlite3 *db = pParse->db; /* The database connection */
  100074. int mxSqlLen; /* Max length of an SQL string */
  100075. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  100076. if( db->nVdbeActive==0 ){
  100077. db->u1.isInterrupted = 0;
  100078. }
  100079. pParse->rc = SQLITE_OK;
  100080. pParse->zTail = zSql;
  100081. i = 0;
  100082. assert( pzErrMsg!=0 );
  100083. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  100084. if( pEngine==0 ){
  100085. db->mallocFailed = 1;
  100086. return SQLITE_NOMEM;
  100087. }
  100088. assert( pParse->pNewTable==0 );
  100089. assert( pParse->pNewTrigger==0 );
  100090. assert( pParse->nVar==0 );
  100091. assert( pParse->nzVar==0 );
  100092. assert( pParse->azVar==0 );
  100093. enableLookaside = db->lookaside.bEnabled;
  100094. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  100095. while( !db->mallocFailed && zSql[i]!=0 ){
  100096. assert( i>=0 );
  100097. pParse->sLastToken.z = &zSql[i];
  100098. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  100099. i += pParse->sLastToken.n;
  100100. if( i>mxSqlLen ){
  100101. pParse->rc = SQLITE_TOOBIG;
  100102. break;
  100103. }
  100104. switch( tokenType ){
  100105. case TK_SPACE: {
  100106. if( db->u1.isInterrupted ){
  100107. sqlite3ErrorMsg(pParse, "interrupt");
  100108. pParse->rc = SQLITE_INTERRUPT;
  100109. goto abort_parse;
  100110. }
  100111. break;
  100112. }
  100113. case TK_ILLEGAL: {
  100114. sqlite3DbFree(db, *pzErrMsg);
  100115. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  100116. &pParse->sLastToken);
  100117. nErr++;
  100118. goto abort_parse;
  100119. }
  100120. case TK_SEMI: {
  100121. pParse->zTail = &zSql[i];
  100122. /* Fall thru into the default case */
  100123. }
  100124. default: {
  100125. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  100126. lastTokenParsed = tokenType;
  100127. if( pParse->rc!=SQLITE_OK ){
  100128. goto abort_parse;
  100129. }
  100130. break;
  100131. }
  100132. }
  100133. }
  100134. abort_parse:
  100135. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  100136. if( lastTokenParsed!=TK_SEMI ){
  100137. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  100138. pParse->zTail = &zSql[i];
  100139. }
  100140. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  100141. }
  100142. #ifdef YYTRACKMAXSTACKDEPTH
  100143. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  100144. sqlite3ParserStackPeak(pEngine)
  100145. );
  100146. #endif /* YYDEBUG */
  100147. sqlite3ParserFree(pEngine, sqlite3_free);
  100148. db->lookaside.bEnabled = enableLookaside;
  100149. if( db->mallocFailed ){
  100150. pParse->rc = SQLITE_NOMEM;
  100151. }
  100152. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  100153. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  100154. }
  100155. assert( pzErrMsg!=0 );
  100156. if( pParse->zErrMsg ){
  100157. *pzErrMsg = pParse->zErrMsg;
  100158. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  100159. pParse->zErrMsg = 0;
  100160. nErr++;
  100161. }
  100162. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  100163. sqlite3VdbeDelete(pParse->pVdbe);
  100164. pParse->pVdbe = 0;
  100165. }
  100166. #ifndef SQLITE_OMIT_SHARED_CACHE
  100167. if( pParse->nested==0 ){
  100168. sqlite3DbFree(db, pParse->aTableLock);
  100169. pParse->aTableLock = 0;
  100170. pParse->nTableLock = 0;
  100171. }
  100172. #endif
  100173. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100174. sqlite3_free(pParse->apVtabLock);
  100175. #endif
  100176. if( !IN_DECLARE_VTAB ){
  100177. /* If the pParse->declareVtab flag is set, do not delete any table
  100178. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  100179. ** will take responsibility for freeing the Table structure.
  100180. */
  100181. sqlite3DeleteTable(db, pParse->pNewTable);
  100182. }
  100183. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  100184. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  100185. sqlite3DbFree(db, pParse->azVar);
  100186. sqlite3DbFree(db, pParse->aAlias);
  100187. while( pParse->pAinc ){
  100188. AutoincInfo *p = pParse->pAinc;
  100189. pParse->pAinc = p->pNext;
  100190. sqlite3DbFree(db, p);
  100191. }
  100192. while( pParse->pZombieTab ){
  100193. Table *p = pParse->pZombieTab;
  100194. pParse->pZombieTab = p->pNextZombie;
  100195. sqlite3DeleteTable(db, p);
  100196. }
  100197. if( nErr>0 && pParse->rc==SQLITE_OK ){
  100198. pParse->rc = SQLITE_ERROR;
  100199. }
  100200. return nErr;
  100201. }
  100202. /************** End of tokenize.c ********************************************/
  100203. /************** Begin file complete.c ****************************************/
  100204. /*
  100205. ** 2001 September 15
  100206. **
  100207. ** The author disclaims copyright to this source code. In place of
  100208. ** a legal notice, here is a blessing:
  100209. **
  100210. ** May you do good and not evil.
  100211. ** May you find forgiveness for yourself and forgive others.
  100212. ** May you share freely, never taking more than you give.
  100213. **
  100214. *************************************************************************
  100215. ** An tokenizer for SQL
  100216. **
  100217. ** This file contains C code that implements the sqlite3_complete() API.
  100218. ** This code used to be part of the tokenizer.c source file. But by
  100219. ** separating it out, the code will be automatically omitted from
  100220. ** static links that do not use it.
  100221. */
  100222. #ifndef SQLITE_OMIT_COMPLETE
  100223. /*
  100224. ** This is defined in tokenize.c. We just have to import the definition.
  100225. */
  100226. #ifndef SQLITE_AMALGAMATION
  100227. #ifdef SQLITE_ASCII
  100228. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  100229. #endif
  100230. #ifdef SQLITE_EBCDIC
  100231. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  100232. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  100233. #endif
  100234. #endif /* SQLITE_AMALGAMATION */
  100235. /*
  100236. ** Token types used by the sqlite3_complete() routine. See the header
  100237. ** comments on that procedure for additional information.
  100238. */
  100239. #define tkSEMI 0
  100240. #define tkWS 1
  100241. #define tkOTHER 2
  100242. #ifndef SQLITE_OMIT_TRIGGER
  100243. #define tkEXPLAIN 3
  100244. #define tkCREATE 4
  100245. #define tkTEMP 5
  100246. #define tkTRIGGER 6
  100247. #define tkEND 7
  100248. #endif
  100249. /*
  100250. ** Return TRUE if the given SQL string ends in a semicolon.
  100251. **
  100252. ** Special handling is require for CREATE TRIGGER statements.
  100253. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  100254. ** must end with ";END;".
  100255. **
  100256. ** This implementation uses a state machine with 8 states:
  100257. **
  100258. ** (0) INVALID We have not yet seen a non-whitespace character.
  100259. **
  100260. ** (1) START At the beginning or end of an SQL statement. This routine
  100261. ** returns 1 if it ends in the START state and 0 if it ends
  100262. ** in any other state.
  100263. **
  100264. ** (2) NORMAL We are in the middle of statement which ends with a single
  100265. ** semicolon.
  100266. **
  100267. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  100268. ** a statement.
  100269. **
  100270. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  100271. ** statement, possibly preceeded by EXPLAIN and/or followed by
  100272. ** TEMP or TEMPORARY
  100273. **
  100274. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  100275. ** ended by a semicolon, the keyword END, and another semicolon.
  100276. **
  100277. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  100278. ** the end of a trigger definition.
  100279. **
  100280. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  100281. ** of a trigger difinition.
  100282. **
  100283. ** Transitions between states above are determined by tokens extracted
  100284. ** from the input. The following tokens are significant:
  100285. **
  100286. ** (0) tkSEMI A semicolon.
  100287. ** (1) tkWS Whitespace.
  100288. ** (2) tkOTHER Any other SQL token.
  100289. ** (3) tkEXPLAIN The "explain" keyword.
  100290. ** (4) tkCREATE The "create" keyword.
  100291. ** (5) tkTEMP The "temp" or "temporary" keyword.
  100292. ** (6) tkTRIGGER The "trigger" keyword.
  100293. ** (7) tkEND The "end" keyword.
  100294. **
  100295. ** Whitespace never causes a state transition and is always ignored.
  100296. ** This means that a SQL string of all whitespace is invalid.
  100297. **
  100298. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  100299. ** to recognize the end of a trigger can be omitted. All we have to do
  100300. ** is look for a semicolon that is not part of an string or comment.
  100301. */
  100302. SQLITE_API int sqlite3_complete(const char *zSql){
  100303. u8 state = 0; /* Current state, using numbers defined in header comment */
  100304. u8 token; /* Value of the next token */
  100305. #ifndef SQLITE_OMIT_TRIGGER
  100306. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  100307. ** statement. This is the normal case.
  100308. */
  100309. static const u8 trans[8][8] = {
  100310. /* Token: */
  100311. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  100312. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  100313. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  100314. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  100315. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  100316. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  100317. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  100318. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  100319. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  100320. };
  100321. #else
  100322. /* If triggers are not supported by this compile then the statement machine
  100323. ** used to detect the end of a statement is much simplier
  100324. */
  100325. static const u8 trans[3][3] = {
  100326. /* Token: */
  100327. /* State: ** SEMI WS OTHER */
  100328. /* 0 INVALID: */ { 1, 0, 2, },
  100329. /* 1 START: */ { 1, 1, 2, },
  100330. /* 2 NORMAL: */ { 1, 2, 2, },
  100331. };
  100332. #endif /* SQLITE_OMIT_TRIGGER */
  100333. while( *zSql ){
  100334. switch( *zSql ){
  100335. case ';': { /* A semicolon */
  100336. token = tkSEMI;
  100337. break;
  100338. }
  100339. case ' ':
  100340. case '\r':
  100341. case '\t':
  100342. case '\n':
  100343. case '\f': { /* White space is ignored */
  100344. token = tkWS;
  100345. break;
  100346. }
  100347. case '/': { /* C-style comments */
  100348. if( zSql[1]!='*' ){
  100349. token = tkOTHER;
  100350. break;
  100351. }
  100352. zSql += 2;
  100353. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  100354. if( zSql[0]==0 ) return 0;
  100355. zSql++;
  100356. token = tkWS;
  100357. break;
  100358. }
  100359. case '-': { /* SQL-style comments from "--" to end of line */
  100360. if( zSql[1]!='-' ){
  100361. token = tkOTHER;
  100362. break;
  100363. }
  100364. while( *zSql && *zSql!='\n' ){ zSql++; }
  100365. if( *zSql==0 ) return state==1;
  100366. token = tkWS;
  100367. break;
  100368. }
  100369. case '[': { /* Microsoft-style identifiers in [...] */
  100370. zSql++;
  100371. while( *zSql && *zSql!=']' ){ zSql++; }
  100372. if( *zSql==0 ) return 0;
  100373. token = tkOTHER;
  100374. break;
  100375. }
  100376. case '`': /* Grave-accent quoted symbols used by MySQL */
  100377. case '"': /* single- and double-quoted strings */
  100378. case '\'': {
  100379. int c = *zSql;
  100380. zSql++;
  100381. while( *zSql && *zSql!=c ){ zSql++; }
  100382. if( *zSql==0 ) return 0;
  100383. token = tkOTHER;
  100384. break;
  100385. }
  100386. default: {
  100387. #ifdef SQLITE_EBCDIC
  100388. unsigned char c;
  100389. #endif
  100390. if( IdChar((u8)*zSql) ){
  100391. /* Keywords and unquoted identifiers */
  100392. int nId;
  100393. for(nId=1; IdChar(zSql[nId]); nId++){}
  100394. #ifdef SQLITE_OMIT_TRIGGER
  100395. token = tkOTHER;
  100396. #else
  100397. switch( *zSql ){
  100398. case 'c': case 'C': {
  100399. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  100400. token = tkCREATE;
  100401. }else{
  100402. token = tkOTHER;
  100403. }
  100404. break;
  100405. }
  100406. case 't': case 'T': {
  100407. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  100408. token = tkTRIGGER;
  100409. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  100410. token = tkTEMP;
  100411. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  100412. token = tkTEMP;
  100413. }else{
  100414. token = tkOTHER;
  100415. }
  100416. break;
  100417. }
  100418. case 'e': case 'E': {
  100419. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  100420. token = tkEND;
  100421. }else
  100422. #ifndef SQLITE_OMIT_EXPLAIN
  100423. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  100424. token = tkEXPLAIN;
  100425. }else
  100426. #endif
  100427. {
  100428. token = tkOTHER;
  100429. }
  100430. break;
  100431. }
  100432. default: {
  100433. token = tkOTHER;
  100434. break;
  100435. }
  100436. }
  100437. #endif /* SQLITE_OMIT_TRIGGER */
  100438. zSql += nId-1;
  100439. }else{
  100440. /* Operators and special symbols */
  100441. token = tkOTHER;
  100442. }
  100443. break;
  100444. }
  100445. }
  100446. state = trans[state][token];
  100447. zSql++;
  100448. }
  100449. return state==1;
  100450. }
  100451. #ifndef SQLITE_OMIT_UTF16
  100452. /*
  100453. ** This routine is the same as the sqlite3_complete() routine described
  100454. ** above, except that the parameter is required to be UTF-16 encoded, not
  100455. ** UTF-8.
  100456. */
  100457. SQLITE_API int sqlite3_complete16(const void *zSql){
  100458. sqlite3_value *pVal;
  100459. char const *zSql8;
  100460. int rc = SQLITE_NOMEM;
  100461. #ifndef SQLITE_OMIT_AUTOINIT
  100462. rc = sqlite3_initialize();
  100463. if( rc ) return rc;
  100464. #endif
  100465. pVal = sqlite3ValueNew(0);
  100466. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  100467. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  100468. if( zSql8 ){
  100469. rc = sqlite3_complete(zSql8);
  100470. }else{
  100471. rc = SQLITE_NOMEM;
  100472. }
  100473. sqlite3ValueFree(pVal);
  100474. return sqlite3ApiExit(0, rc);
  100475. }
  100476. #endif /* SQLITE_OMIT_UTF16 */
  100477. #endif /* SQLITE_OMIT_COMPLETE */
  100478. /************** End of complete.c ********************************************/
  100479. /************** Begin file main.c ********************************************/
  100480. /*
  100481. ** 2001 September 15
  100482. **
  100483. ** The author disclaims copyright to this source code. In place of
  100484. ** a legal notice, here is a blessing:
  100485. **
  100486. ** May you do good and not evil.
  100487. ** May you find forgiveness for yourself and forgive others.
  100488. ** May you share freely, never taking more than you give.
  100489. **
  100490. *************************************************************************
  100491. ** Main file for the SQLite library. The routines in this file
  100492. ** implement the programmer interface to the library. Routines in
  100493. ** other files are for internal use by SQLite and should not be
  100494. ** accessed by users of the library.
  100495. */
  100496. #ifdef SQLITE_ENABLE_FTS3
  100497. /************** Include fts3.h in the middle of main.c ***********************/
  100498. /************** Begin file fts3.h ********************************************/
  100499. /*
  100500. ** 2006 Oct 10
  100501. **
  100502. ** The author disclaims copyright to this source code. In place of
  100503. ** a legal notice, here is a blessing:
  100504. **
  100505. ** May you do good and not evil.
  100506. ** May you find forgiveness for yourself and forgive others.
  100507. ** May you share freely, never taking more than you give.
  100508. **
  100509. ******************************************************************************
  100510. **
  100511. ** This header file is used by programs that want to link against the
  100512. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  100513. */
  100514. #if 0
  100515. extern "C" {
  100516. #endif /* __cplusplus */
  100517. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  100518. #if 0
  100519. } /* extern "C" */
  100520. #endif /* __cplusplus */
  100521. /************** End of fts3.h ************************************************/
  100522. /************** Continuing where we left off in main.c ***********************/
  100523. #endif
  100524. #ifdef SQLITE_ENABLE_RTREE
  100525. /************** Include rtree.h in the middle of main.c **********************/
  100526. /************** Begin file rtree.h *******************************************/
  100527. /*
  100528. ** 2008 May 26
  100529. **
  100530. ** The author disclaims copyright to this source code. In place of
  100531. ** a legal notice, here is a blessing:
  100532. **
  100533. ** May you do good and not evil.
  100534. ** May you find forgiveness for yourself and forgive others.
  100535. ** May you share freely, never taking more than you give.
  100536. **
  100537. ******************************************************************************
  100538. **
  100539. ** This header file is used by programs that want to link against the
  100540. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  100541. */
  100542. #if 0
  100543. extern "C" {
  100544. #endif /* __cplusplus */
  100545. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  100546. #if 0
  100547. } /* extern "C" */
  100548. #endif /* __cplusplus */
  100549. /************** End of rtree.h ***********************************************/
  100550. /************** Continuing where we left off in main.c ***********************/
  100551. #endif
  100552. #ifdef SQLITE_ENABLE_ICU
  100553. /************** Include sqliteicu.h in the middle of main.c ******************/
  100554. /************** Begin file sqliteicu.h ***************************************/
  100555. /*
  100556. ** 2008 May 26
  100557. **
  100558. ** The author disclaims copyright to this source code. In place of
  100559. ** a legal notice, here is a blessing:
  100560. **
  100561. ** May you do good and not evil.
  100562. ** May you find forgiveness for yourself and forgive others.
  100563. ** May you share freely, never taking more than you give.
  100564. **
  100565. ******************************************************************************
  100566. **
  100567. ** This header file is used by programs that want to link against the
  100568. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  100569. */
  100570. #if 0
  100571. extern "C" {
  100572. #endif /* __cplusplus */
  100573. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  100574. #if 0
  100575. } /* extern "C" */
  100576. #endif /* __cplusplus */
  100577. /************** End of sqliteicu.h *******************************************/
  100578. /************** Continuing where we left off in main.c ***********************/
  100579. #endif
  100580. #ifndef SQLITE_AMALGAMATION
  100581. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  100582. ** contains the text of SQLITE_VERSION macro.
  100583. */
  100584. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  100585. #endif
  100586. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  100587. ** a pointer to the to the sqlite3_version[] string constant.
  100588. */
  100589. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  100590. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  100591. ** pointer to a string constant whose value is the same as the
  100592. ** SQLITE_SOURCE_ID C preprocessor macro.
  100593. */
  100594. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  100595. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  100596. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  100597. */
  100598. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  100599. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  100600. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  100601. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  100602. */
  100603. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  100604. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  100605. /*
  100606. ** If the following function pointer is not NULL and if
  100607. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  100608. ** I/O active are written using this function. These messages
  100609. ** are intended for debugging activity only.
  100610. */
  100611. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  100612. #endif
  100613. /*
  100614. ** If the following global variable points to a string which is the
  100615. ** name of a directory, then that directory will be used to store
  100616. ** temporary files.
  100617. **
  100618. ** See also the "PRAGMA temp_store_directory" SQL command.
  100619. */
  100620. SQLITE_API char *sqlite3_temp_directory = 0;
  100621. /*
  100622. ** If the following global variable points to a string which is the
  100623. ** name of a directory, then that directory will be used to store
  100624. ** all database files specified with a relative pathname.
  100625. **
  100626. ** See also the "PRAGMA data_store_directory" SQL command.
  100627. */
  100628. SQLITE_API char *sqlite3_data_directory = 0;
  100629. /*
  100630. ** Initialize SQLite.
  100631. **
  100632. ** This routine must be called to initialize the memory allocation,
  100633. ** VFS, and mutex subsystems prior to doing any serious work with
  100634. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  100635. ** this routine will be called automatically by key routines such as
  100636. ** sqlite3_open().
  100637. **
  100638. ** This routine is a no-op except on its very first call for the process,
  100639. ** or for the first call after a call to sqlite3_shutdown.
  100640. **
  100641. ** The first thread to call this routine runs the initialization to
  100642. ** completion. If subsequent threads call this routine before the first
  100643. ** thread has finished the initialization process, then the subsequent
  100644. ** threads must block until the first thread finishes with the initialization.
  100645. **
  100646. ** The first thread might call this routine recursively. Recursive
  100647. ** calls to this routine should not block, of course. Otherwise the
  100648. ** initialization process would never complete.
  100649. **
  100650. ** Let X be the first thread to enter this routine. Let Y be some other
  100651. ** thread. Then while the initial invocation of this routine by X is
  100652. ** incomplete, it is required that:
  100653. **
  100654. ** * Calls to this routine from Y must block until the outer-most
  100655. ** call by X completes.
  100656. **
  100657. ** * Recursive calls to this routine from thread X return immediately
  100658. ** without blocking.
  100659. */
  100660. SQLITE_API int sqlite3_initialize(void){
  100661. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  100662. int rc; /* Result code */
  100663. #ifdef SQLITE_EXTRA_INIT
  100664. int bRunExtraInit = 0; /* Extra initialization needed */
  100665. #endif
  100666. #ifdef SQLITE_OMIT_WSD
  100667. rc = sqlite3_wsd_init(4096, 24);
  100668. if( rc!=SQLITE_OK ){
  100669. return rc;
  100670. }
  100671. #endif
  100672. /* If SQLite is already completely initialized, then this call
  100673. ** to sqlite3_initialize() should be a no-op. But the initialization
  100674. ** must be complete. So isInit must not be set until the very end
  100675. ** of this routine.
  100676. */
  100677. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  100678. #ifdef SQLITE_ENABLE_SQLLOG
  100679. {
  100680. extern void sqlite3_init_sqllog(void);
  100681. sqlite3_init_sqllog();
  100682. }
  100683. #endif
  100684. /* Make sure the mutex subsystem is initialized. If unable to
  100685. ** initialize the mutex subsystem, return early with the error.
  100686. ** If the system is so sick that we are unable to allocate a mutex,
  100687. ** there is not much SQLite is going to be able to do.
  100688. **
  100689. ** The mutex subsystem must take care of serializing its own
  100690. ** initialization.
  100691. */
  100692. rc = sqlite3MutexInit();
  100693. if( rc ) return rc;
  100694. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  100695. ** This operation is protected by the STATIC_MASTER mutex. Note that
  100696. ** MutexAlloc() is called for a static mutex prior to initializing the
  100697. ** malloc subsystem - this implies that the allocation of a static
  100698. ** mutex must not require support from the malloc subsystem.
  100699. */
  100700. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  100701. sqlite3_mutex_enter(pMaster);
  100702. sqlite3GlobalConfig.isMutexInit = 1;
  100703. if( !sqlite3GlobalConfig.isMallocInit ){
  100704. rc = sqlite3MallocInit();
  100705. }
  100706. if( rc==SQLITE_OK ){
  100707. sqlite3GlobalConfig.isMallocInit = 1;
  100708. if( !sqlite3GlobalConfig.pInitMutex ){
  100709. sqlite3GlobalConfig.pInitMutex =
  100710. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  100711. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  100712. rc = SQLITE_NOMEM;
  100713. }
  100714. }
  100715. }
  100716. if( rc==SQLITE_OK ){
  100717. sqlite3GlobalConfig.nRefInitMutex++;
  100718. }
  100719. sqlite3_mutex_leave(pMaster);
  100720. /* If rc is not SQLITE_OK at this point, then either the malloc
  100721. ** subsystem could not be initialized or the system failed to allocate
  100722. ** the pInitMutex mutex. Return an error in either case. */
  100723. if( rc!=SQLITE_OK ){
  100724. return rc;
  100725. }
  100726. /* Do the rest of the initialization under the recursive mutex so
  100727. ** that we will be able to handle recursive calls into
  100728. ** sqlite3_initialize(). The recursive calls normally come through
  100729. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  100730. ** recursive calls might also be possible.
  100731. **
  100732. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  100733. ** to the xInit method, so the xInit method need not be threadsafe.
  100734. **
  100735. ** The following mutex is what serializes access to the appdef pcache xInit
  100736. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  100737. ** call to sqlite3PcacheInitialize().
  100738. */
  100739. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  100740. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  100741. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  100742. sqlite3GlobalConfig.inProgress = 1;
  100743. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  100744. sqlite3RegisterGlobalFunctions();
  100745. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  100746. rc = sqlite3PcacheInitialize();
  100747. }
  100748. if( rc==SQLITE_OK ){
  100749. sqlite3GlobalConfig.isPCacheInit = 1;
  100750. rc = sqlite3OsInit();
  100751. }
  100752. if( rc==SQLITE_OK ){
  100753. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  100754. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  100755. sqlite3GlobalConfig.isInit = 1;
  100756. #ifdef SQLITE_EXTRA_INIT
  100757. bRunExtraInit = 1;
  100758. #endif
  100759. }
  100760. sqlite3GlobalConfig.inProgress = 0;
  100761. }
  100762. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  100763. /* Go back under the static mutex and clean up the recursive
  100764. ** mutex to prevent a resource leak.
  100765. */
  100766. sqlite3_mutex_enter(pMaster);
  100767. sqlite3GlobalConfig.nRefInitMutex--;
  100768. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  100769. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  100770. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  100771. sqlite3GlobalConfig.pInitMutex = 0;
  100772. }
  100773. sqlite3_mutex_leave(pMaster);
  100774. /* The following is just a sanity check to make sure SQLite has
  100775. ** been compiled correctly. It is important to run this code, but
  100776. ** we don't want to run it too often and soak up CPU cycles for no
  100777. ** reason. So we run it once during initialization.
  100778. */
  100779. #ifndef NDEBUG
  100780. #ifndef SQLITE_OMIT_FLOATING_POINT
  100781. /* This section of code's only "output" is via assert() statements. */
  100782. if ( rc==SQLITE_OK ){
  100783. u64 x = (((u64)1)<<63)-1;
  100784. double y;
  100785. assert(sizeof(x)==8);
  100786. assert(sizeof(x)==sizeof(y));
  100787. memcpy(&y, &x, 8);
  100788. assert( sqlite3IsNaN(y) );
  100789. }
  100790. #endif
  100791. #endif
  100792. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  100793. ** compile-time option.
  100794. */
  100795. #ifdef SQLITE_EXTRA_INIT
  100796. if( bRunExtraInit ){
  100797. int SQLITE_EXTRA_INIT(const char*);
  100798. rc = SQLITE_EXTRA_INIT(0);
  100799. }
  100800. #endif
  100801. return rc;
  100802. }
  100803. /*
  100804. ** Undo the effects of sqlite3_initialize(). Must not be called while
  100805. ** there are outstanding database connections or memory allocations or
  100806. ** while any part of SQLite is otherwise in use in any thread. This
  100807. ** routine is not threadsafe. But it is safe to invoke this routine
  100808. ** on when SQLite is already shut down. If SQLite is already shut down
  100809. ** when this routine is invoked, then this routine is a harmless no-op.
  100810. */
  100811. SQLITE_API int sqlite3_shutdown(void){
  100812. if( sqlite3GlobalConfig.isInit ){
  100813. #ifdef SQLITE_EXTRA_SHUTDOWN
  100814. void SQLITE_EXTRA_SHUTDOWN(void);
  100815. SQLITE_EXTRA_SHUTDOWN();
  100816. #endif
  100817. sqlite3_os_end();
  100818. sqlite3_reset_auto_extension();
  100819. sqlite3GlobalConfig.isInit = 0;
  100820. }
  100821. if( sqlite3GlobalConfig.isPCacheInit ){
  100822. sqlite3PcacheShutdown();
  100823. sqlite3GlobalConfig.isPCacheInit = 0;
  100824. }
  100825. if( sqlite3GlobalConfig.isMallocInit ){
  100826. sqlite3MallocEnd();
  100827. sqlite3GlobalConfig.isMallocInit = 0;
  100828. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  100829. /* The heap subsystem has now been shutdown and these values are supposed
  100830. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  100831. ** which would rely on that heap subsystem; therefore, make sure these
  100832. ** values cannot refer to heap memory that was just invalidated when the
  100833. ** heap subsystem was shutdown. This is only done if the current call to
  100834. ** this function resulted in the heap subsystem actually being shutdown.
  100835. */
  100836. sqlite3_data_directory = 0;
  100837. sqlite3_temp_directory = 0;
  100838. #endif
  100839. }
  100840. if( sqlite3GlobalConfig.isMutexInit ){
  100841. sqlite3MutexEnd();
  100842. sqlite3GlobalConfig.isMutexInit = 0;
  100843. }
  100844. return SQLITE_OK;
  100845. }
  100846. /*
  100847. ** This API allows applications to modify the global configuration of
  100848. ** the SQLite library at run-time.
  100849. **
  100850. ** This routine should only be called when there are no outstanding
  100851. ** database connections or memory allocations. This routine is not
  100852. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  100853. ** behavior.
  100854. */
  100855. SQLITE_API int sqlite3_config(int op, ...){
  100856. va_list ap;
  100857. int rc = SQLITE_OK;
  100858. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  100859. ** the SQLite library is in use. */
  100860. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  100861. va_start(ap, op);
  100862. switch( op ){
  100863. /* Mutex configuration options are only available in a threadsafe
  100864. ** compile.
  100865. */
  100866. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  100867. case SQLITE_CONFIG_SINGLETHREAD: {
  100868. /* Disable all mutexing */
  100869. sqlite3GlobalConfig.bCoreMutex = 0;
  100870. sqlite3GlobalConfig.bFullMutex = 0;
  100871. break;
  100872. }
  100873. case SQLITE_CONFIG_MULTITHREAD: {
  100874. /* Disable mutexing of database connections */
  100875. /* Enable mutexing of core data structures */
  100876. sqlite3GlobalConfig.bCoreMutex = 1;
  100877. sqlite3GlobalConfig.bFullMutex = 0;
  100878. break;
  100879. }
  100880. case SQLITE_CONFIG_SERIALIZED: {
  100881. /* Enable all mutexing */
  100882. sqlite3GlobalConfig.bCoreMutex = 1;
  100883. sqlite3GlobalConfig.bFullMutex = 1;
  100884. break;
  100885. }
  100886. case SQLITE_CONFIG_MUTEX: {
  100887. /* Specify an alternative mutex implementation */
  100888. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  100889. break;
  100890. }
  100891. case SQLITE_CONFIG_GETMUTEX: {
  100892. /* Retrieve the current mutex implementation */
  100893. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  100894. break;
  100895. }
  100896. #endif
  100897. case SQLITE_CONFIG_MALLOC: {
  100898. /* Specify an alternative malloc implementation */
  100899. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  100900. break;
  100901. }
  100902. case SQLITE_CONFIG_GETMALLOC: {
  100903. /* Retrieve the current malloc() implementation */
  100904. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  100905. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  100906. break;
  100907. }
  100908. case SQLITE_CONFIG_MEMSTATUS: {
  100909. /* Enable or disable the malloc status collection */
  100910. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  100911. break;
  100912. }
  100913. case SQLITE_CONFIG_SCRATCH: {
  100914. /* Designate a buffer for scratch memory space */
  100915. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  100916. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  100917. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  100918. break;
  100919. }
  100920. case SQLITE_CONFIG_PAGECACHE: {
  100921. /* Designate a buffer for page cache memory space */
  100922. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  100923. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  100924. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  100925. break;
  100926. }
  100927. case SQLITE_CONFIG_PCACHE: {
  100928. /* no-op */
  100929. break;
  100930. }
  100931. case SQLITE_CONFIG_GETPCACHE: {
  100932. /* now an error */
  100933. rc = SQLITE_ERROR;
  100934. break;
  100935. }
  100936. case SQLITE_CONFIG_PCACHE2: {
  100937. /* Specify an alternative page cache implementation */
  100938. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  100939. break;
  100940. }
  100941. case SQLITE_CONFIG_GETPCACHE2: {
  100942. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  100943. sqlite3PCacheSetDefault();
  100944. }
  100945. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  100946. break;
  100947. }
  100948. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  100949. case SQLITE_CONFIG_HEAP: {
  100950. /* Designate a buffer for heap memory space */
  100951. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  100952. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  100953. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  100954. if( sqlite3GlobalConfig.mnReq<1 ){
  100955. sqlite3GlobalConfig.mnReq = 1;
  100956. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  100957. /* cap min request size at 2^12 */
  100958. sqlite3GlobalConfig.mnReq = (1<<12);
  100959. }
  100960. if( sqlite3GlobalConfig.pHeap==0 ){
  100961. /* If the heap pointer is NULL, then restore the malloc implementation
  100962. ** back to NULL pointers too. This will cause the malloc to go
  100963. ** back to its default implementation when sqlite3_initialize() is
  100964. ** run.
  100965. */
  100966. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  100967. }else{
  100968. /* The heap pointer is not NULL, then install one of the
  100969. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  100970. ** least one of these methods is currently enabled.
  100971. */
  100972. #ifdef SQLITE_ENABLE_MEMSYS3
  100973. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  100974. #endif
  100975. #ifdef SQLITE_ENABLE_MEMSYS5
  100976. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  100977. #endif
  100978. }
  100979. break;
  100980. }
  100981. #endif
  100982. case SQLITE_CONFIG_LOOKASIDE: {
  100983. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  100984. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  100985. break;
  100986. }
  100987. /* Record a pointer to the logger function and its first argument.
  100988. ** The default is NULL. Logging is disabled if the function pointer is
  100989. ** NULL.
  100990. */
  100991. case SQLITE_CONFIG_LOG: {
  100992. /* MSVC is picky about pulling func ptrs from va lists.
  100993. ** http://support.microsoft.com/kb/47961
  100994. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  100995. */
  100996. typedef void(*LOGFUNC_t)(void*,int,const char*);
  100997. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  100998. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  100999. break;
  101000. }
  101001. case SQLITE_CONFIG_URI: {
  101002. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  101003. break;
  101004. }
  101005. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  101006. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  101007. break;
  101008. }
  101009. #ifdef SQLITE_ENABLE_SQLLOG
  101010. case SQLITE_CONFIG_SQLLOG: {
  101011. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  101012. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  101013. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  101014. break;
  101015. }
  101016. #endif
  101017. case SQLITE_CONFIG_MMAP_SIZE: {
  101018. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  101019. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  101020. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  101021. mxMmap = SQLITE_MAX_MMAP_SIZE;
  101022. }
  101023. sqlite3GlobalConfig.mxMmap = mxMmap;
  101024. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  101025. if( szMmap>mxMmap) szMmap = mxMmap;
  101026. sqlite3GlobalConfig.szMmap = szMmap;
  101027. break;
  101028. }
  101029. default: {
  101030. rc = SQLITE_ERROR;
  101031. break;
  101032. }
  101033. }
  101034. va_end(ap);
  101035. return rc;
  101036. }
  101037. /*
  101038. ** Set up the lookaside buffers for a database connection.
  101039. ** Return SQLITE_OK on success.
  101040. ** If lookaside is already active, return SQLITE_BUSY.
  101041. **
  101042. ** The sz parameter is the number of bytes in each lookaside slot.
  101043. ** The cnt parameter is the number of slots. If pStart is NULL the
  101044. ** space for the lookaside memory is obtained from sqlite3_malloc().
  101045. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  101046. ** the lookaside memory.
  101047. */
  101048. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  101049. void *pStart;
  101050. if( db->lookaside.nOut ){
  101051. return SQLITE_BUSY;
  101052. }
  101053. /* Free any existing lookaside buffer for this handle before
  101054. ** allocating a new one so we don't have to have space for
  101055. ** both at the same time.
  101056. */
  101057. if( db->lookaside.bMalloced ){
  101058. sqlite3_free(db->lookaside.pStart);
  101059. }
  101060. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  101061. ** than a pointer to be useful.
  101062. */
  101063. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  101064. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  101065. if( cnt<0 ) cnt = 0;
  101066. if( sz==0 || cnt==0 ){
  101067. sz = 0;
  101068. pStart = 0;
  101069. }else if( pBuf==0 ){
  101070. sqlite3BeginBenignMalloc();
  101071. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  101072. sqlite3EndBenignMalloc();
  101073. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  101074. }else{
  101075. pStart = pBuf;
  101076. }
  101077. db->lookaside.pStart = pStart;
  101078. db->lookaside.pFree = 0;
  101079. db->lookaside.sz = (u16)sz;
  101080. if( pStart ){
  101081. int i;
  101082. LookasideSlot *p;
  101083. assert( sz > (int)sizeof(LookasideSlot*) );
  101084. p = (LookasideSlot*)pStart;
  101085. for(i=cnt-1; i>=0; i--){
  101086. p->pNext = db->lookaside.pFree;
  101087. db->lookaside.pFree = p;
  101088. p = (LookasideSlot*)&((u8*)p)[sz];
  101089. }
  101090. db->lookaside.pEnd = p;
  101091. db->lookaside.bEnabled = 1;
  101092. db->lookaside.bMalloced = pBuf==0 ?1:0;
  101093. }else{
  101094. db->lookaside.pEnd = 0;
  101095. db->lookaside.bEnabled = 0;
  101096. db->lookaside.bMalloced = 0;
  101097. }
  101098. return SQLITE_OK;
  101099. }
  101100. /*
  101101. ** Return the mutex associated with a database connection.
  101102. */
  101103. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  101104. return db->mutex;
  101105. }
  101106. /*
  101107. ** Free up as much memory as we can from the given database
  101108. ** connection.
  101109. */
  101110. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  101111. int i;
  101112. sqlite3_mutex_enter(db->mutex);
  101113. sqlite3BtreeEnterAll(db);
  101114. for(i=0; i<db->nDb; i++){
  101115. Btree *pBt = db->aDb[i].pBt;
  101116. if( pBt ){
  101117. Pager *pPager = sqlite3BtreePager(pBt);
  101118. sqlite3PagerShrink(pPager);
  101119. }
  101120. }
  101121. sqlite3BtreeLeaveAll(db);
  101122. sqlite3_mutex_leave(db->mutex);
  101123. return SQLITE_OK;
  101124. }
  101125. /*
  101126. ** Configuration settings for an individual database connection
  101127. */
  101128. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  101129. va_list ap;
  101130. int rc;
  101131. va_start(ap, op);
  101132. switch( op ){
  101133. case SQLITE_DBCONFIG_LOOKASIDE: {
  101134. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  101135. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  101136. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  101137. rc = setupLookaside(db, pBuf, sz, cnt);
  101138. break;
  101139. }
  101140. default: {
  101141. static const struct {
  101142. int op; /* The opcode */
  101143. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  101144. } aFlagOp[] = {
  101145. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  101146. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  101147. };
  101148. unsigned int i;
  101149. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  101150. for(i=0; i<ArraySize(aFlagOp); i++){
  101151. if( aFlagOp[i].op==op ){
  101152. int onoff = va_arg(ap, int);
  101153. int *pRes = va_arg(ap, int*);
  101154. int oldFlags = db->flags;
  101155. if( onoff>0 ){
  101156. db->flags |= aFlagOp[i].mask;
  101157. }else if( onoff==0 ){
  101158. db->flags &= ~aFlagOp[i].mask;
  101159. }
  101160. if( oldFlags!=db->flags ){
  101161. sqlite3ExpirePreparedStatements(db);
  101162. }
  101163. if( pRes ){
  101164. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  101165. }
  101166. rc = SQLITE_OK;
  101167. break;
  101168. }
  101169. }
  101170. break;
  101171. }
  101172. }
  101173. va_end(ap);
  101174. return rc;
  101175. }
  101176. /*
  101177. ** Return true if the buffer z[0..n-1] contains all spaces.
  101178. */
  101179. static int allSpaces(const char *z, int n){
  101180. while( n>0 && z[n-1]==' ' ){ n--; }
  101181. return n==0;
  101182. }
  101183. /*
  101184. ** This is the default collating function named "BINARY" which is always
  101185. ** available.
  101186. **
  101187. ** If the padFlag argument is not NULL then space padding at the end
  101188. ** of strings is ignored. This implements the RTRIM collation.
  101189. */
  101190. static int binCollFunc(
  101191. void *padFlag,
  101192. int nKey1, const void *pKey1,
  101193. int nKey2, const void *pKey2
  101194. ){
  101195. int rc, n;
  101196. n = nKey1<nKey2 ? nKey1 : nKey2;
  101197. rc = memcmp(pKey1, pKey2, n);
  101198. if( rc==0 ){
  101199. if( padFlag
  101200. && allSpaces(((char*)pKey1)+n, nKey1-n)
  101201. && allSpaces(((char*)pKey2)+n, nKey2-n)
  101202. ){
  101203. /* Leave rc unchanged at 0 */
  101204. }else{
  101205. rc = nKey1 - nKey2;
  101206. }
  101207. }
  101208. return rc;
  101209. }
  101210. /*
  101211. ** Another built-in collating sequence: NOCASE.
  101212. **
  101213. ** This collating sequence is intended to be used for "case independent
  101214. ** comparison". SQLite's knowledge of upper and lower case equivalents
  101215. ** extends only to the 26 characters used in the English language.
  101216. **
  101217. ** At the moment there is only a UTF-8 implementation.
  101218. */
  101219. static int nocaseCollatingFunc(
  101220. void *NotUsed,
  101221. int nKey1, const void *pKey1,
  101222. int nKey2, const void *pKey2
  101223. ){
  101224. int r = sqlite3StrNICmp(
  101225. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  101226. UNUSED_PARAMETER(NotUsed);
  101227. if( 0==r ){
  101228. r = nKey1-nKey2;
  101229. }
  101230. return r;
  101231. }
  101232. /*
  101233. ** Return the ROWID of the most recent insert
  101234. */
  101235. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  101236. return db->lastRowid;
  101237. }
  101238. /*
  101239. ** Return the number of changes in the most recent call to sqlite3_exec().
  101240. */
  101241. SQLITE_API int sqlite3_changes(sqlite3 *db){
  101242. return db->nChange;
  101243. }
  101244. /*
  101245. ** Return the number of changes since the database handle was opened.
  101246. */
  101247. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  101248. return db->nTotalChange;
  101249. }
  101250. /*
  101251. ** Close all open savepoints. This function only manipulates fields of the
  101252. ** database handle object, it does not close any savepoints that may be open
  101253. ** at the b-tree/pager level.
  101254. */
  101255. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  101256. while( db->pSavepoint ){
  101257. Savepoint *pTmp = db->pSavepoint;
  101258. db->pSavepoint = pTmp->pNext;
  101259. sqlite3DbFree(db, pTmp);
  101260. }
  101261. db->nSavepoint = 0;
  101262. db->nStatement = 0;
  101263. db->isTransactionSavepoint = 0;
  101264. }
  101265. /*
  101266. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  101267. ** if this is not the last copy of the function, do not invoke it. Multiple
  101268. ** copies of a single function are created when create_function() is called
  101269. ** with SQLITE_ANY as the encoding.
  101270. */
  101271. static void functionDestroy(sqlite3 *db, FuncDef *p){
  101272. FuncDestructor *pDestructor = p->pDestructor;
  101273. if( pDestructor ){
  101274. pDestructor->nRef--;
  101275. if( pDestructor->nRef==0 ){
  101276. pDestructor->xDestroy(pDestructor->pUserData);
  101277. sqlite3DbFree(db, pDestructor);
  101278. }
  101279. }
  101280. }
  101281. /*
  101282. ** Disconnect all sqlite3_vtab objects that belong to database connection
  101283. ** db. This is called when db is being closed.
  101284. */
  101285. static void disconnectAllVtab(sqlite3 *db){
  101286. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101287. int i;
  101288. sqlite3BtreeEnterAll(db);
  101289. for(i=0; i<db->nDb; i++){
  101290. Schema *pSchema = db->aDb[i].pSchema;
  101291. if( db->aDb[i].pSchema ){
  101292. HashElem *p;
  101293. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  101294. Table *pTab = (Table *)sqliteHashData(p);
  101295. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  101296. }
  101297. }
  101298. }
  101299. sqlite3BtreeLeaveAll(db);
  101300. #else
  101301. UNUSED_PARAMETER(db);
  101302. #endif
  101303. }
  101304. /*
  101305. ** Return TRUE if database connection db has unfinalized prepared
  101306. ** statements or unfinished sqlite3_backup objects.
  101307. */
  101308. static int connectionIsBusy(sqlite3 *db){
  101309. int j;
  101310. assert( sqlite3_mutex_held(db->mutex) );
  101311. if( db->pVdbe ) return 1;
  101312. for(j=0; j<db->nDb; j++){
  101313. Btree *pBt = db->aDb[j].pBt;
  101314. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  101315. }
  101316. return 0;
  101317. }
  101318. /*
  101319. ** Close an existing SQLite database
  101320. */
  101321. static int sqlite3Close(sqlite3 *db, int forceZombie){
  101322. if( !db ){
  101323. return SQLITE_OK;
  101324. }
  101325. if( !sqlite3SafetyCheckSickOrOk(db) ){
  101326. return SQLITE_MISUSE_BKPT;
  101327. }
  101328. sqlite3_mutex_enter(db->mutex);
  101329. /* Force xDisconnect calls on all virtual tables */
  101330. disconnectAllVtab(db);
  101331. /* If a transaction is open, the disconnectAllVtab() call above
  101332. ** will not have called the xDisconnect() method on any virtual
  101333. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  101334. ** call will do so. We need to do this before the check for active
  101335. ** SQL statements below, as the v-table implementation may be storing
  101336. ** some prepared statements internally.
  101337. */
  101338. sqlite3VtabRollback(db);
  101339. /* Legacy behavior (sqlite3_close() behavior) is to return
  101340. ** SQLITE_BUSY if the connection can not be closed immediately.
  101341. */
  101342. if( !forceZombie && connectionIsBusy(db) ){
  101343. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  101344. "statements or unfinished backups");
  101345. sqlite3_mutex_leave(db->mutex);
  101346. return SQLITE_BUSY;
  101347. }
  101348. #ifdef SQLITE_ENABLE_SQLLOG
  101349. if( sqlite3GlobalConfig.xSqllog ){
  101350. /* Closing the handle. Fourth parameter is passed the value 2. */
  101351. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  101352. }
  101353. #endif
  101354. /* Convert the connection into a zombie and then close it.
  101355. */
  101356. db->magic = SQLITE_MAGIC_ZOMBIE;
  101357. sqlite3LeaveMutexAndCloseZombie(db);
  101358. return SQLITE_OK;
  101359. }
  101360. /*
  101361. ** Two variations on the public interface for closing a database
  101362. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  101363. ** leaves the connection option if there are unfinalized prepared
  101364. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  101365. ** version forces the connection to become a zombie if there are
  101366. ** unclosed resources, and arranges for deallocation when the last
  101367. ** prepare statement or sqlite3_backup closes.
  101368. */
  101369. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  101370. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  101371. /*
  101372. ** Close the mutex on database connection db.
  101373. **
  101374. ** Furthermore, if database connection db is a zombie (meaning that there
  101375. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  101376. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  101377. ** finished, then free all resources.
  101378. */
  101379. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  101380. HashElem *i; /* Hash table iterator */
  101381. int j;
  101382. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  101383. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  101384. ** then just leave the mutex and return.
  101385. */
  101386. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  101387. sqlite3_mutex_leave(db->mutex);
  101388. return;
  101389. }
  101390. /* If we reach this point, it means that the database connection has
  101391. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  101392. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  101393. ** go ahead and free all resources.
  101394. */
  101395. /* If a transaction is open, roll it back. This also ensures that if
  101396. ** any database schemas have been modified by an uncommitted transaction
  101397. ** they are reset. And that the required b-tree mutex is held to make
  101398. ** the pager rollback and schema reset an atomic operation. */
  101399. sqlite3RollbackAll(db, SQLITE_OK);
  101400. /* Free any outstanding Savepoint structures. */
  101401. sqlite3CloseSavepoints(db);
  101402. /* Close all database connections */
  101403. for(j=0; j<db->nDb; j++){
  101404. struct Db *pDb = &db->aDb[j];
  101405. if( pDb->pBt ){
  101406. sqlite3BtreeClose(pDb->pBt);
  101407. pDb->pBt = 0;
  101408. if( j!=1 ){
  101409. pDb->pSchema = 0;
  101410. }
  101411. }
  101412. }
  101413. /* Clear the TEMP schema separately and last */
  101414. if( db->aDb[1].pSchema ){
  101415. sqlite3SchemaClear(db->aDb[1].pSchema);
  101416. }
  101417. sqlite3VtabUnlockList(db);
  101418. /* Free up the array of auxiliary databases */
  101419. sqlite3CollapseDatabaseArray(db);
  101420. assert( db->nDb<=2 );
  101421. assert( db->aDb==db->aDbStatic );
  101422. /* Tell the code in notify.c that the connection no longer holds any
  101423. ** locks and does not require any further unlock-notify callbacks.
  101424. */
  101425. sqlite3ConnectionClosed(db);
  101426. for(j=0; j<ArraySize(db->aFunc.a); j++){
  101427. FuncDef *pNext, *pHash, *p;
  101428. for(p=db->aFunc.a[j]; p; p=pHash){
  101429. pHash = p->pHash;
  101430. while( p ){
  101431. functionDestroy(db, p);
  101432. pNext = p->pNext;
  101433. sqlite3DbFree(db, p);
  101434. p = pNext;
  101435. }
  101436. }
  101437. }
  101438. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  101439. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  101440. /* Invoke any destructors registered for collation sequence user data. */
  101441. for(j=0; j<3; j++){
  101442. if( pColl[j].xDel ){
  101443. pColl[j].xDel(pColl[j].pUser);
  101444. }
  101445. }
  101446. sqlite3DbFree(db, pColl);
  101447. }
  101448. sqlite3HashClear(&db->aCollSeq);
  101449. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101450. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  101451. Module *pMod = (Module *)sqliteHashData(i);
  101452. if( pMod->xDestroy ){
  101453. pMod->xDestroy(pMod->pAux);
  101454. }
  101455. sqlite3DbFree(db, pMod);
  101456. }
  101457. sqlite3HashClear(&db->aModule);
  101458. #endif
  101459. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  101460. if( db->pErr ){
  101461. sqlite3ValueFree(db->pErr);
  101462. }
  101463. sqlite3CloseExtensions(db);
  101464. db->magic = SQLITE_MAGIC_ERROR;
  101465. /* The temp-database schema is allocated differently from the other schema
  101466. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  101467. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  101468. ** the same sqliteMalloc() as the one that allocates the database
  101469. ** structure?
  101470. */
  101471. sqlite3DbFree(db, db->aDb[1].pSchema);
  101472. sqlite3_mutex_leave(db->mutex);
  101473. db->magic = SQLITE_MAGIC_CLOSED;
  101474. sqlite3_mutex_free(db->mutex);
  101475. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  101476. if( db->lookaside.bMalloced ){
  101477. sqlite3_free(db->lookaside.pStart);
  101478. }
  101479. sqlite3_free(db);
  101480. }
  101481. /*
  101482. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  101483. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  101484. ** breaker") and made to return tripCode if there are any further
  101485. ** attempts to use that cursor.
  101486. */
  101487. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  101488. int i;
  101489. int inTrans = 0;
  101490. assert( sqlite3_mutex_held(db->mutex) );
  101491. sqlite3BeginBenignMalloc();
  101492. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  101493. ** This is important in case the transaction being rolled back has
  101494. ** modified the database schema. If the b-tree mutexes are not taken
  101495. ** here, then another shared-cache connection might sneak in between
  101496. ** the database rollback and schema reset, which can cause false
  101497. ** corruption reports in some cases. */
  101498. sqlite3BtreeEnterAll(db);
  101499. for(i=0; i<db->nDb; i++){
  101500. Btree *p = db->aDb[i].pBt;
  101501. if( p ){
  101502. if( sqlite3BtreeIsInTrans(p) ){
  101503. inTrans = 1;
  101504. }
  101505. sqlite3BtreeRollback(p, tripCode);
  101506. }
  101507. }
  101508. sqlite3VtabRollback(db);
  101509. sqlite3EndBenignMalloc();
  101510. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  101511. sqlite3ExpirePreparedStatements(db);
  101512. sqlite3ResetAllSchemasOfConnection(db);
  101513. }
  101514. sqlite3BtreeLeaveAll(db);
  101515. /* Any deferred constraint violations have now been resolved. */
  101516. db->nDeferredCons = 0;
  101517. db->nDeferredImmCons = 0;
  101518. db->flags &= ~SQLITE_DeferFKs;
  101519. /* If one has been configured, invoke the rollback-hook callback */
  101520. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  101521. db->xRollbackCallback(db->pRollbackArg);
  101522. }
  101523. }
  101524. /*
  101525. ** Return a static string containing the name corresponding to the error code
  101526. ** specified in the argument.
  101527. */
  101528. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  101529. defined(SQLITE_DEBUG_OS_TRACE)
  101530. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  101531. const char *zName = 0;
  101532. int i, origRc = rc;
  101533. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  101534. switch( rc ){
  101535. case SQLITE_OK: zName = "SQLITE_OK"; break;
  101536. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  101537. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  101538. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  101539. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  101540. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  101541. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  101542. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  101543. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  101544. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  101545. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  101546. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  101547. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  101548. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  101549. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  101550. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  101551. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  101552. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  101553. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  101554. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  101555. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  101556. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  101557. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  101558. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  101559. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  101560. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  101561. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  101562. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  101563. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  101564. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  101565. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  101566. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  101567. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  101568. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  101569. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  101570. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  101571. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  101572. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  101573. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  101574. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  101575. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  101576. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  101577. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  101578. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  101579. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  101580. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  101581. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  101582. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  101583. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  101584. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  101585. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  101586. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  101587. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  101588. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  101589. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  101590. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  101591. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  101592. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  101593. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  101594. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  101595. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  101596. case SQLITE_CONSTRAINT_FOREIGNKEY:
  101597. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  101598. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  101599. case SQLITE_CONSTRAINT_PRIMARYKEY:
  101600. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  101601. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  101602. case SQLITE_CONSTRAINT_COMMITHOOK:
  101603. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  101604. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  101605. case SQLITE_CONSTRAINT_FUNCTION:
  101606. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  101607. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  101608. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  101609. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  101610. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  101611. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  101612. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  101613. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  101614. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  101615. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  101616. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  101617. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  101618. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  101619. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  101620. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  101621. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  101622. }
  101623. }
  101624. if( zName==0 ){
  101625. static char zBuf[50];
  101626. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  101627. zName = zBuf;
  101628. }
  101629. return zName;
  101630. }
  101631. #endif
  101632. /*
  101633. ** Return a static string that describes the kind of error specified in the
  101634. ** argument.
  101635. */
  101636. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  101637. static const char* const aMsg[] = {
  101638. /* SQLITE_OK */ "not an error",
  101639. /* SQLITE_ERROR */ "SQL logic error or missing database",
  101640. /* SQLITE_INTERNAL */ 0,
  101641. /* SQLITE_PERM */ "access permission denied",
  101642. /* SQLITE_ABORT */ "callback requested query abort",
  101643. /* SQLITE_BUSY */ "database is locked",
  101644. /* SQLITE_LOCKED */ "database table is locked",
  101645. /* SQLITE_NOMEM */ "out of memory",
  101646. /* SQLITE_READONLY */ "attempt to write a readonly database",
  101647. /* SQLITE_INTERRUPT */ "interrupted",
  101648. /* SQLITE_IOERR */ "disk I/O error",
  101649. /* SQLITE_CORRUPT */ "database disk image is malformed",
  101650. /* SQLITE_NOTFOUND */ "unknown operation",
  101651. /* SQLITE_FULL */ "database or disk is full",
  101652. /* SQLITE_CANTOPEN */ "unable to open database file",
  101653. /* SQLITE_PROTOCOL */ "locking protocol",
  101654. /* SQLITE_EMPTY */ "table contains no data",
  101655. /* SQLITE_SCHEMA */ "database schema has changed",
  101656. /* SQLITE_TOOBIG */ "string or blob too big",
  101657. /* SQLITE_CONSTRAINT */ "constraint failed",
  101658. /* SQLITE_MISMATCH */ "datatype mismatch",
  101659. /* SQLITE_MISUSE */ "library routine called out of sequence",
  101660. /* SQLITE_NOLFS */ "large file support is disabled",
  101661. /* SQLITE_AUTH */ "authorization denied",
  101662. /* SQLITE_FORMAT */ "auxiliary database format error",
  101663. /* SQLITE_RANGE */ "bind or column index out of range",
  101664. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  101665. };
  101666. const char *zErr = "unknown error";
  101667. switch( rc ){
  101668. case SQLITE_ABORT_ROLLBACK: {
  101669. zErr = "abort due to ROLLBACK";
  101670. break;
  101671. }
  101672. default: {
  101673. rc &= 0xff;
  101674. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  101675. zErr = aMsg[rc];
  101676. }
  101677. break;
  101678. }
  101679. }
  101680. return zErr;
  101681. }
  101682. /*
  101683. ** This routine implements a busy callback that sleeps and tries
  101684. ** again until a timeout value is reached. The timeout value is
  101685. ** an integer number of milliseconds passed in as the first
  101686. ** argument.
  101687. */
  101688. static int sqliteDefaultBusyCallback(
  101689. void *ptr, /* Database connection */
  101690. int count /* Number of times table has been busy */
  101691. ){
  101692. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  101693. static const u8 delays[] =
  101694. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  101695. static const u8 totals[] =
  101696. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  101697. # define NDELAY ArraySize(delays)
  101698. sqlite3 *db = (sqlite3 *)ptr;
  101699. int timeout = db->busyTimeout;
  101700. int delay, prior;
  101701. assert( count>=0 );
  101702. if( count < NDELAY ){
  101703. delay = delays[count];
  101704. prior = totals[count];
  101705. }else{
  101706. delay = delays[NDELAY-1];
  101707. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  101708. }
  101709. if( prior + delay > timeout ){
  101710. delay = timeout - prior;
  101711. if( delay<=0 ) return 0;
  101712. }
  101713. sqlite3OsSleep(db->pVfs, delay*1000);
  101714. return 1;
  101715. #else
  101716. sqlite3 *db = (sqlite3 *)ptr;
  101717. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  101718. if( (count+1)*1000 > timeout ){
  101719. return 0;
  101720. }
  101721. sqlite3OsSleep(db->pVfs, 1000000);
  101722. return 1;
  101723. #endif
  101724. }
  101725. /*
  101726. ** Invoke the given busy handler.
  101727. **
  101728. ** This routine is called when an operation failed with a lock.
  101729. ** If this routine returns non-zero, the lock is retried. If it
  101730. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  101731. */
  101732. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  101733. int rc;
  101734. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  101735. rc = p->xFunc(p->pArg, p->nBusy);
  101736. if( rc==0 ){
  101737. p->nBusy = -1;
  101738. }else{
  101739. p->nBusy++;
  101740. }
  101741. return rc;
  101742. }
  101743. /*
  101744. ** This routine sets the busy callback for an Sqlite database to the
  101745. ** given callback function with the given argument.
  101746. */
  101747. SQLITE_API int sqlite3_busy_handler(
  101748. sqlite3 *db,
  101749. int (*xBusy)(void*,int),
  101750. void *pArg
  101751. ){
  101752. sqlite3_mutex_enter(db->mutex);
  101753. db->busyHandler.xFunc = xBusy;
  101754. db->busyHandler.pArg = pArg;
  101755. db->busyHandler.nBusy = 0;
  101756. db->busyTimeout = 0;
  101757. sqlite3_mutex_leave(db->mutex);
  101758. return SQLITE_OK;
  101759. }
  101760. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  101761. /*
  101762. ** This routine sets the progress callback for an Sqlite database to the
  101763. ** given callback function with the given argument. The progress callback will
  101764. ** be invoked every nOps opcodes.
  101765. */
  101766. SQLITE_API void sqlite3_progress_handler(
  101767. sqlite3 *db,
  101768. int nOps,
  101769. int (*xProgress)(void*),
  101770. void *pArg
  101771. ){
  101772. sqlite3_mutex_enter(db->mutex);
  101773. if( nOps>0 ){
  101774. db->xProgress = xProgress;
  101775. db->nProgressOps = (unsigned)nOps;
  101776. db->pProgressArg = pArg;
  101777. }else{
  101778. db->xProgress = 0;
  101779. db->nProgressOps = 0;
  101780. db->pProgressArg = 0;
  101781. }
  101782. sqlite3_mutex_leave(db->mutex);
  101783. }
  101784. #endif
  101785. /*
  101786. ** This routine installs a default busy handler that waits for the
  101787. ** specified number of milliseconds before returning 0.
  101788. */
  101789. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  101790. if( ms>0 ){
  101791. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  101792. db->busyTimeout = ms;
  101793. }else{
  101794. sqlite3_busy_handler(db, 0, 0);
  101795. }
  101796. return SQLITE_OK;
  101797. }
  101798. /*
  101799. ** Cause any pending operation to stop at its earliest opportunity.
  101800. */
  101801. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  101802. db->u1.isInterrupted = 1;
  101803. }
  101804. /*
  101805. ** This function is exactly the same as sqlite3_create_function(), except
  101806. ** that it is designed to be called by internal code. The difference is
  101807. ** that if a malloc() fails in sqlite3_create_function(), an error code
  101808. ** is returned and the mallocFailed flag cleared.
  101809. */
  101810. SQLITE_PRIVATE int sqlite3CreateFunc(
  101811. sqlite3 *db,
  101812. const char *zFunctionName,
  101813. int nArg,
  101814. int enc,
  101815. void *pUserData,
  101816. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101817. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101818. void (*xFinal)(sqlite3_context*),
  101819. FuncDestructor *pDestructor
  101820. ){
  101821. FuncDef *p;
  101822. int nName;
  101823. assert( sqlite3_mutex_held(db->mutex) );
  101824. if( zFunctionName==0 ||
  101825. (xFunc && (xFinal || xStep)) ||
  101826. (!xFunc && (xFinal && !xStep)) ||
  101827. (!xFunc && (!xFinal && xStep)) ||
  101828. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  101829. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  101830. return SQLITE_MISUSE_BKPT;
  101831. }
  101832. #ifndef SQLITE_OMIT_UTF16
  101833. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  101834. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  101835. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  101836. **
  101837. ** If SQLITE_ANY is specified, add three versions of the function
  101838. ** to the hash table.
  101839. */
  101840. if( enc==SQLITE_UTF16 ){
  101841. enc = SQLITE_UTF16NATIVE;
  101842. }else if( enc==SQLITE_ANY ){
  101843. int rc;
  101844. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  101845. pUserData, xFunc, xStep, xFinal, pDestructor);
  101846. if( rc==SQLITE_OK ){
  101847. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  101848. pUserData, xFunc, xStep, xFinal, pDestructor);
  101849. }
  101850. if( rc!=SQLITE_OK ){
  101851. return rc;
  101852. }
  101853. enc = SQLITE_UTF16BE;
  101854. }
  101855. #else
  101856. enc = SQLITE_UTF8;
  101857. #endif
  101858. /* Check if an existing function is being overridden or deleted. If so,
  101859. ** and there are active VMs, then return SQLITE_BUSY. If a function
  101860. ** is being overridden/deleted but there are no active VMs, allow the
  101861. ** operation to continue but invalidate all precompiled statements.
  101862. */
  101863. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  101864. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  101865. if( db->nVdbeActive ){
  101866. sqlite3Error(db, SQLITE_BUSY,
  101867. "unable to delete/modify user-function due to active statements");
  101868. assert( !db->mallocFailed );
  101869. return SQLITE_BUSY;
  101870. }else{
  101871. sqlite3ExpirePreparedStatements(db);
  101872. }
  101873. }
  101874. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  101875. assert(p || db->mallocFailed);
  101876. if( !p ){
  101877. return SQLITE_NOMEM;
  101878. }
  101879. /* If an older version of the function with a configured destructor is
  101880. ** being replaced invoke the destructor function here. */
  101881. functionDestroy(db, p);
  101882. if( pDestructor ){
  101883. pDestructor->nRef++;
  101884. }
  101885. p->pDestructor = pDestructor;
  101886. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  101887. p->xFunc = xFunc;
  101888. p->xStep = xStep;
  101889. p->xFinalize = xFinal;
  101890. p->pUserData = pUserData;
  101891. p->nArg = (u16)nArg;
  101892. return SQLITE_OK;
  101893. }
  101894. /*
  101895. ** Create new user functions.
  101896. */
  101897. SQLITE_API int sqlite3_create_function(
  101898. sqlite3 *db,
  101899. const char *zFunc,
  101900. int nArg,
  101901. int enc,
  101902. void *p,
  101903. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101904. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101905. void (*xFinal)(sqlite3_context*)
  101906. ){
  101907. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  101908. xFinal, 0);
  101909. }
  101910. SQLITE_API int sqlite3_create_function_v2(
  101911. sqlite3 *db,
  101912. const char *zFunc,
  101913. int nArg,
  101914. int enc,
  101915. void *p,
  101916. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101917. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101918. void (*xFinal)(sqlite3_context*),
  101919. void (*xDestroy)(void *)
  101920. ){
  101921. int rc = SQLITE_ERROR;
  101922. FuncDestructor *pArg = 0;
  101923. sqlite3_mutex_enter(db->mutex);
  101924. if( xDestroy ){
  101925. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  101926. if( !pArg ){
  101927. xDestroy(p);
  101928. goto out;
  101929. }
  101930. pArg->xDestroy = xDestroy;
  101931. pArg->pUserData = p;
  101932. }
  101933. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  101934. if( pArg && pArg->nRef==0 ){
  101935. assert( rc!=SQLITE_OK );
  101936. xDestroy(p);
  101937. sqlite3DbFree(db, pArg);
  101938. }
  101939. out:
  101940. rc = sqlite3ApiExit(db, rc);
  101941. sqlite3_mutex_leave(db->mutex);
  101942. return rc;
  101943. }
  101944. #ifndef SQLITE_OMIT_UTF16
  101945. SQLITE_API int sqlite3_create_function16(
  101946. sqlite3 *db,
  101947. const void *zFunctionName,
  101948. int nArg,
  101949. int eTextRep,
  101950. void *p,
  101951. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  101952. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  101953. void (*xFinal)(sqlite3_context*)
  101954. ){
  101955. int rc;
  101956. char *zFunc8;
  101957. sqlite3_mutex_enter(db->mutex);
  101958. assert( !db->mallocFailed );
  101959. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  101960. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  101961. sqlite3DbFree(db, zFunc8);
  101962. rc = sqlite3ApiExit(db, rc);
  101963. sqlite3_mutex_leave(db->mutex);
  101964. return rc;
  101965. }
  101966. #endif
  101967. /*
  101968. ** Declare that a function has been overloaded by a virtual table.
  101969. **
  101970. ** If the function already exists as a regular global function, then
  101971. ** this routine is a no-op. If the function does not exist, then create
  101972. ** a new one that always throws a run-time error.
  101973. **
  101974. ** When virtual tables intend to provide an overloaded function, they
  101975. ** should call this routine to make sure the global function exists.
  101976. ** A global function must exist in order for name resolution to work
  101977. ** properly.
  101978. */
  101979. SQLITE_API int sqlite3_overload_function(
  101980. sqlite3 *db,
  101981. const char *zName,
  101982. int nArg
  101983. ){
  101984. int nName = sqlite3Strlen30(zName);
  101985. int rc = SQLITE_OK;
  101986. sqlite3_mutex_enter(db->mutex);
  101987. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  101988. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  101989. 0, sqlite3InvalidFunction, 0, 0, 0);
  101990. }
  101991. rc = sqlite3ApiExit(db, rc);
  101992. sqlite3_mutex_leave(db->mutex);
  101993. return rc;
  101994. }
  101995. #ifndef SQLITE_OMIT_TRACE
  101996. /*
  101997. ** Register a trace function. The pArg from the previously registered trace
  101998. ** is returned.
  101999. **
  102000. ** A NULL trace function means that no tracing is executes. A non-NULL
  102001. ** trace is a pointer to a function that is invoked at the start of each
  102002. ** SQL statement.
  102003. */
  102004. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  102005. void *pOld;
  102006. sqlite3_mutex_enter(db->mutex);
  102007. pOld = db->pTraceArg;
  102008. db->xTrace = xTrace;
  102009. db->pTraceArg = pArg;
  102010. sqlite3_mutex_leave(db->mutex);
  102011. return pOld;
  102012. }
  102013. /*
  102014. ** Register a profile function. The pArg from the previously registered
  102015. ** profile function is returned.
  102016. **
  102017. ** A NULL profile function means that no profiling is executes. A non-NULL
  102018. ** profile is a pointer to a function that is invoked at the conclusion of
  102019. ** each SQL statement that is run.
  102020. */
  102021. SQLITE_API void *sqlite3_profile(
  102022. sqlite3 *db,
  102023. void (*xProfile)(void*,const char*,sqlite_uint64),
  102024. void *pArg
  102025. ){
  102026. void *pOld;
  102027. sqlite3_mutex_enter(db->mutex);
  102028. pOld = db->pProfileArg;
  102029. db->xProfile = xProfile;
  102030. db->pProfileArg = pArg;
  102031. sqlite3_mutex_leave(db->mutex);
  102032. return pOld;
  102033. }
  102034. #endif /* SQLITE_OMIT_TRACE */
  102035. /*
  102036. ** Register a function to be invoked when a transaction commits.
  102037. ** If the invoked function returns non-zero, then the commit becomes a
  102038. ** rollback.
  102039. */
  102040. SQLITE_API void *sqlite3_commit_hook(
  102041. sqlite3 *db, /* Attach the hook to this database */
  102042. int (*xCallback)(void*), /* Function to invoke on each commit */
  102043. void *pArg /* Argument to the function */
  102044. ){
  102045. void *pOld;
  102046. sqlite3_mutex_enter(db->mutex);
  102047. pOld = db->pCommitArg;
  102048. db->xCommitCallback = xCallback;
  102049. db->pCommitArg = pArg;
  102050. sqlite3_mutex_leave(db->mutex);
  102051. return pOld;
  102052. }
  102053. /*
  102054. ** Register a callback to be invoked each time a row is updated,
  102055. ** inserted or deleted using this database connection.
  102056. */
  102057. SQLITE_API void *sqlite3_update_hook(
  102058. sqlite3 *db, /* Attach the hook to this database */
  102059. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  102060. void *pArg /* Argument to the function */
  102061. ){
  102062. void *pRet;
  102063. sqlite3_mutex_enter(db->mutex);
  102064. pRet = db->pUpdateArg;
  102065. db->xUpdateCallback = xCallback;
  102066. db->pUpdateArg = pArg;
  102067. sqlite3_mutex_leave(db->mutex);
  102068. return pRet;
  102069. }
  102070. /*
  102071. ** Register a callback to be invoked each time a transaction is rolled
  102072. ** back by this database connection.
  102073. */
  102074. SQLITE_API void *sqlite3_rollback_hook(
  102075. sqlite3 *db, /* Attach the hook to this database */
  102076. void (*xCallback)(void*), /* Callback function */
  102077. void *pArg /* Argument to the function */
  102078. ){
  102079. void *pRet;
  102080. sqlite3_mutex_enter(db->mutex);
  102081. pRet = db->pRollbackArg;
  102082. db->xRollbackCallback = xCallback;
  102083. db->pRollbackArg = pArg;
  102084. sqlite3_mutex_leave(db->mutex);
  102085. return pRet;
  102086. }
  102087. #ifndef SQLITE_OMIT_WAL
  102088. /*
  102089. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  102090. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  102091. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  102092. ** wal_autocheckpoint()).
  102093. */
  102094. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  102095. void *pClientData, /* Argument */
  102096. sqlite3 *db, /* Connection */
  102097. const char *zDb, /* Database */
  102098. int nFrame /* Size of WAL */
  102099. ){
  102100. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  102101. sqlite3BeginBenignMalloc();
  102102. sqlite3_wal_checkpoint(db, zDb);
  102103. sqlite3EndBenignMalloc();
  102104. }
  102105. return SQLITE_OK;
  102106. }
  102107. #endif /* SQLITE_OMIT_WAL */
  102108. /*
  102109. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  102110. ** a database after committing a transaction if there are nFrame or
  102111. ** more frames in the log file. Passing zero or a negative value as the
  102112. ** nFrame parameter disables automatic checkpoints entirely.
  102113. **
  102114. ** The callback registered by this function replaces any existing callback
  102115. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  102116. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  102117. ** configured by this function.
  102118. */
  102119. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  102120. #ifdef SQLITE_OMIT_WAL
  102121. UNUSED_PARAMETER(db);
  102122. UNUSED_PARAMETER(nFrame);
  102123. #else
  102124. if( nFrame>0 ){
  102125. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  102126. }else{
  102127. sqlite3_wal_hook(db, 0, 0);
  102128. }
  102129. #endif
  102130. return SQLITE_OK;
  102131. }
  102132. /*
  102133. ** Register a callback to be invoked each time a transaction is written
  102134. ** into the write-ahead-log by this database connection.
  102135. */
  102136. SQLITE_API void *sqlite3_wal_hook(
  102137. sqlite3 *db, /* Attach the hook to this db handle */
  102138. int(*xCallback)(void *, sqlite3*, const char*, int),
  102139. void *pArg /* First argument passed to xCallback() */
  102140. ){
  102141. #ifndef SQLITE_OMIT_WAL
  102142. void *pRet;
  102143. sqlite3_mutex_enter(db->mutex);
  102144. pRet = db->pWalArg;
  102145. db->xWalCallback = xCallback;
  102146. db->pWalArg = pArg;
  102147. sqlite3_mutex_leave(db->mutex);
  102148. return pRet;
  102149. #else
  102150. return 0;
  102151. #endif
  102152. }
  102153. /*
  102154. ** Checkpoint database zDb.
  102155. */
  102156. SQLITE_API int sqlite3_wal_checkpoint_v2(
  102157. sqlite3 *db, /* Database handle */
  102158. const char *zDb, /* Name of attached database (or NULL) */
  102159. int eMode, /* SQLITE_CHECKPOINT_* value */
  102160. int *pnLog, /* OUT: Size of WAL log in frames */
  102161. int *pnCkpt /* OUT: Total number of frames checkpointed */
  102162. ){
  102163. #ifdef SQLITE_OMIT_WAL
  102164. return SQLITE_OK;
  102165. #else
  102166. int rc; /* Return code */
  102167. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  102168. /* Initialize the output variables to -1 in case an error occurs. */
  102169. if( pnLog ) *pnLog = -1;
  102170. if( pnCkpt ) *pnCkpt = -1;
  102171. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  102172. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  102173. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  102174. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  102175. return SQLITE_MISUSE;
  102176. }
  102177. sqlite3_mutex_enter(db->mutex);
  102178. if( zDb && zDb[0] ){
  102179. iDb = sqlite3FindDbName(db, zDb);
  102180. }
  102181. if( iDb<0 ){
  102182. rc = SQLITE_ERROR;
  102183. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  102184. }else{
  102185. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  102186. sqlite3Error(db, rc, 0);
  102187. }
  102188. rc = sqlite3ApiExit(db, rc);
  102189. sqlite3_mutex_leave(db->mutex);
  102190. return rc;
  102191. #endif
  102192. }
  102193. /*
  102194. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  102195. ** to contains a zero-length string, all attached databases are
  102196. ** checkpointed.
  102197. */
  102198. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  102199. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  102200. }
  102201. #ifndef SQLITE_OMIT_WAL
  102202. /*
  102203. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  102204. ** not currently open in WAL mode.
  102205. **
  102206. ** If a transaction is open on the database being checkpointed, this
  102207. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  102208. ** an error occurs while running the checkpoint, an SQLite error code is
  102209. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  102210. **
  102211. ** The mutex on database handle db should be held by the caller. The mutex
  102212. ** associated with the specific b-tree being checkpointed is taken by
  102213. ** this function while the checkpoint is running.
  102214. **
  102215. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  102216. ** checkpointed. If an error is encountered it is returned immediately -
  102217. ** no attempt is made to checkpoint any remaining databases.
  102218. **
  102219. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  102220. */
  102221. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  102222. int rc = SQLITE_OK; /* Return code */
  102223. int i; /* Used to iterate through attached dbs */
  102224. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  102225. assert( sqlite3_mutex_held(db->mutex) );
  102226. assert( !pnLog || *pnLog==-1 );
  102227. assert( !pnCkpt || *pnCkpt==-1 );
  102228. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  102229. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  102230. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  102231. pnLog = 0;
  102232. pnCkpt = 0;
  102233. if( rc==SQLITE_BUSY ){
  102234. bBusy = 1;
  102235. rc = SQLITE_OK;
  102236. }
  102237. }
  102238. }
  102239. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  102240. }
  102241. #endif /* SQLITE_OMIT_WAL */
  102242. /*
  102243. ** This function returns true if main-memory should be used instead of
  102244. ** a temporary file for transient pager files and statement journals.
  102245. ** The value returned depends on the value of db->temp_store (runtime
  102246. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  102247. ** following table describes the relationship between these two values
  102248. ** and this functions return value.
  102249. **
  102250. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  102251. ** ----------------- -------------- ------------------------------
  102252. ** 0 any file (return 0)
  102253. ** 1 1 file (return 0)
  102254. ** 1 2 memory (return 1)
  102255. ** 1 0 file (return 0)
  102256. ** 2 1 file (return 0)
  102257. ** 2 2 memory (return 1)
  102258. ** 2 0 memory (return 1)
  102259. ** 3 any memory (return 1)
  102260. */
  102261. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  102262. #if SQLITE_TEMP_STORE==1
  102263. return ( db->temp_store==2 );
  102264. #endif
  102265. #if SQLITE_TEMP_STORE==2
  102266. return ( db->temp_store!=1 );
  102267. #endif
  102268. #if SQLITE_TEMP_STORE==3
  102269. return 1;
  102270. #endif
  102271. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  102272. return 0;
  102273. #endif
  102274. }
  102275. /*
  102276. ** Return UTF-8 encoded English language explanation of the most recent
  102277. ** error.
  102278. */
  102279. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  102280. const char *z;
  102281. if( !db ){
  102282. return sqlite3ErrStr(SQLITE_NOMEM);
  102283. }
  102284. if( !sqlite3SafetyCheckSickOrOk(db) ){
  102285. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  102286. }
  102287. sqlite3_mutex_enter(db->mutex);
  102288. if( db->mallocFailed ){
  102289. z = sqlite3ErrStr(SQLITE_NOMEM);
  102290. }else{
  102291. z = (char*)sqlite3_value_text(db->pErr);
  102292. assert( !db->mallocFailed );
  102293. if( z==0 ){
  102294. z = sqlite3ErrStr(db->errCode);
  102295. }
  102296. }
  102297. sqlite3_mutex_leave(db->mutex);
  102298. return z;
  102299. }
  102300. #ifndef SQLITE_OMIT_UTF16
  102301. /*
  102302. ** Return UTF-16 encoded English language explanation of the most recent
  102303. ** error.
  102304. */
  102305. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  102306. static const u16 outOfMem[] = {
  102307. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  102308. };
  102309. static const u16 misuse[] = {
  102310. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  102311. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  102312. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  102313. 'o', 'u', 't', ' ',
  102314. 'o', 'f', ' ',
  102315. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  102316. };
  102317. const void *z;
  102318. if( !db ){
  102319. return (void *)outOfMem;
  102320. }
  102321. if( !sqlite3SafetyCheckSickOrOk(db) ){
  102322. return (void *)misuse;
  102323. }
  102324. sqlite3_mutex_enter(db->mutex);
  102325. if( db->mallocFailed ){
  102326. z = (void *)outOfMem;
  102327. }else{
  102328. z = sqlite3_value_text16(db->pErr);
  102329. if( z==0 ){
  102330. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  102331. SQLITE_UTF8, SQLITE_STATIC);
  102332. z = sqlite3_value_text16(db->pErr);
  102333. }
  102334. /* A malloc() may have failed within the call to sqlite3_value_text16()
  102335. ** above. If this is the case, then the db->mallocFailed flag needs to
  102336. ** be cleared before returning. Do this directly, instead of via
  102337. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  102338. */
  102339. db->mallocFailed = 0;
  102340. }
  102341. sqlite3_mutex_leave(db->mutex);
  102342. return z;
  102343. }
  102344. #endif /* SQLITE_OMIT_UTF16 */
  102345. /*
  102346. ** Return the most recent error code generated by an SQLite routine. If NULL is
  102347. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  102348. */
  102349. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  102350. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  102351. return SQLITE_MISUSE_BKPT;
  102352. }
  102353. if( !db || db->mallocFailed ){
  102354. return SQLITE_NOMEM;
  102355. }
  102356. return db->errCode & db->errMask;
  102357. }
  102358. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  102359. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  102360. return SQLITE_MISUSE_BKPT;
  102361. }
  102362. if( !db || db->mallocFailed ){
  102363. return SQLITE_NOMEM;
  102364. }
  102365. return db->errCode;
  102366. }
  102367. /*
  102368. ** Return a string that describes the kind of error specified in the
  102369. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  102370. ** function.
  102371. */
  102372. SQLITE_API const char *sqlite3_errstr(int rc){
  102373. return sqlite3ErrStr(rc);
  102374. }
  102375. /*
  102376. ** Create a new collating function for database "db". The name is zName
  102377. ** and the encoding is enc.
  102378. */
  102379. static int createCollation(
  102380. sqlite3* db,
  102381. const char *zName,
  102382. u8 enc,
  102383. void* pCtx,
  102384. int(*xCompare)(void*,int,const void*,int,const void*),
  102385. void(*xDel)(void*)
  102386. ){
  102387. CollSeq *pColl;
  102388. int enc2;
  102389. int nName = sqlite3Strlen30(zName);
  102390. assert( sqlite3_mutex_held(db->mutex) );
  102391. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  102392. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  102393. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  102394. */
  102395. enc2 = enc;
  102396. testcase( enc2==SQLITE_UTF16 );
  102397. testcase( enc2==SQLITE_UTF16_ALIGNED );
  102398. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  102399. enc2 = SQLITE_UTF16NATIVE;
  102400. }
  102401. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  102402. return SQLITE_MISUSE_BKPT;
  102403. }
  102404. /* Check if this call is removing or replacing an existing collation
  102405. ** sequence. If so, and there are active VMs, return busy. If there
  102406. ** are no active VMs, invalidate any pre-compiled statements.
  102407. */
  102408. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  102409. if( pColl && pColl->xCmp ){
  102410. if( db->nVdbeActive ){
  102411. sqlite3Error(db, SQLITE_BUSY,
  102412. "unable to delete/modify collation sequence due to active statements");
  102413. return SQLITE_BUSY;
  102414. }
  102415. sqlite3ExpirePreparedStatements(db);
  102416. /* If collation sequence pColl was created directly by a call to
  102417. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  102418. ** then any copies made by synthCollSeq() need to be invalidated.
  102419. ** Also, collation destructor - CollSeq.xDel() - function may need
  102420. ** to be called.
  102421. */
  102422. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  102423. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  102424. int j;
  102425. for(j=0; j<3; j++){
  102426. CollSeq *p = &aColl[j];
  102427. if( p->enc==pColl->enc ){
  102428. if( p->xDel ){
  102429. p->xDel(p->pUser);
  102430. }
  102431. p->xCmp = 0;
  102432. }
  102433. }
  102434. }
  102435. }
  102436. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  102437. if( pColl==0 ) return SQLITE_NOMEM;
  102438. pColl->xCmp = xCompare;
  102439. pColl->pUser = pCtx;
  102440. pColl->xDel = xDel;
  102441. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  102442. sqlite3Error(db, SQLITE_OK, 0);
  102443. return SQLITE_OK;
  102444. }
  102445. /*
  102446. ** This array defines hard upper bounds on limit values. The
  102447. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  102448. ** #defines in sqlite3.h.
  102449. */
  102450. static const int aHardLimit[] = {
  102451. SQLITE_MAX_LENGTH,
  102452. SQLITE_MAX_SQL_LENGTH,
  102453. SQLITE_MAX_COLUMN,
  102454. SQLITE_MAX_EXPR_DEPTH,
  102455. SQLITE_MAX_COMPOUND_SELECT,
  102456. SQLITE_MAX_VDBE_OP,
  102457. SQLITE_MAX_FUNCTION_ARG,
  102458. SQLITE_MAX_ATTACHED,
  102459. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  102460. SQLITE_MAX_VARIABLE_NUMBER,
  102461. SQLITE_MAX_TRIGGER_DEPTH,
  102462. };
  102463. /*
  102464. ** Make sure the hard limits are set to reasonable values
  102465. */
  102466. #if SQLITE_MAX_LENGTH<100
  102467. # error SQLITE_MAX_LENGTH must be at least 100
  102468. #endif
  102469. #if SQLITE_MAX_SQL_LENGTH<100
  102470. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  102471. #endif
  102472. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  102473. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  102474. #endif
  102475. #if SQLITE_MAX_COMPOUND_SELECT<2
  102476. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  102477. #endif
  102478. #if SQLITE_MAX_VDBE_OP<40
  102479. # error SQLITE_MAX_VDBE_OP must be at least 40
  102480. #endif
  102481. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  102482. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  102483. #endif
  102484. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  102485. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  102486. #endif
  102487. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  102488. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  102489. #endif
  102490. #if SQLITE_MAX_COLUMN>32767
  102491. # error SQLITE_MAX_COLUMN must not exceed 32767
  102492. #endif
  102493. #if SQLITE_MAX_TRIGGER_DEPTH<1
  102494. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  102495. #endif
  102496. /*
  102497. ** Change the value of a limit. Report the old value.
  102498. ** If an invalid limit index is supplied, report -1.
  102499. ** Make no changes but still report the old value if the
  102500. ** new limit is negative.
  102501. **
  102502. ** A new lower limit does not shrink existing constructs.
  102503. ** It merely prevents new constructs that exceed the limit
  102504. ** from forming.
  102505. */
  102506. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  102507. int oldLimit;
  102508. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  102509. ** there is a hard upper bound set at compile-time by a C preprocessor
  102510. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  102511. ** "_MAX_".)
  102512. */
  102513. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  102514. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  102515. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  102516. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  102517. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  102518. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  102519. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  102520. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  102521. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  102522. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  102523. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  102524. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  102525. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  102526. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  102527. return -1;
  102528. }
  102529. oldLimit = db->aLimit[limitId];
  102530. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  102531. if( newLimit>aHardLimit[limitId] ){
  102532. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  102533. }
  102534. db->aLimit[limitId] = newLimit;
  102535. }
  102536. return oldLimit; /* IMP: R-53341-35419 */
  102537. }
  102538. /*
  102539. ** This function is used to parse both URIs and non-URI filenames passed by the
  102540. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  102541. ** URIs specified as part of ATTACH statements.
  102542. **
  102543. ** The first argument to this function is the name of the VFS to use (or
  102544. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  102545. ** query parameter. The second argument contains the URI (or non-URI filename)
  102546. ** itself. When this function is called the *pFlags variable should contain
  102547. ** the default flags to open the database handle with. The value stored in
  102548. ** *pFlags may be updated before returning if the URI filename contains
  102549. ** "cache=xxx" or "mode=xxx" query parameters.
  102550. **
  102551. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  102552. ** the VFS that should be used to open the database file. *pzFile is set to
  102553. ** point to a buffer containing the name of the file to open. It is the
  102554. ** responsibility of the caller to eventually call sqlite3_free() to release
  102555. ** this buffer.
  102556. **
  102557. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  102558. ** may be set to point to a buffer containing an English language error
  102559. ** message. It is the responsibility of the caller to eventually release
  102560. ** this buffer by calling sqlite3_free().
  102561. */
  102562. SQLITE_PRIVATE int sqlite3ParseUri(
  102563. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  102564. const char *zUri, /* Nul-terminated URI to parse */
  102565. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  102566. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  102567. char **pzFile, /* OUT: Filename component of URI */
  102568. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  102569. ){
  102570. int rc = SQLITE_OK;
  102571. unsigned int flags = *pFlags;
  102572. const char *zVfs = zDefaultVfs;
  102573. char *zFile;
  102574. char c;
  102575. int nUri = sqlite3Strlen30(zUri);
  102576. assert( *pzErrMsg==0 );
  102577. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  102578. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  102579. ){
  102580. char *zOpt;
  102581. int eState; /* Parser state when parsing URI */
  102582. int iIn; /* Input character index */
  102583. int iOut = 0; /* Output character index */
  102584. int nByte = nUri+2; /* Bytes of space to allocate */
  102585. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  102586. ** method that there may be extra parameters following the file-name. */
  102587. flags |= SQLITE_OPEN_URI;
  102588. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  102589. zFile = sqlite3_malloc(nByte);
  102590. if( !zFile ) return SQLITE_NOMEM;
  102591. iIn = 5;
  102592. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  102593. /* Discard the scheme and authority segments of the URI. */
  102594. if( zUri[5]=='/' && zUri[6]=='/' ){
  102595. iIn = 7;
  102596. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  102597. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  102598. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  102599. iIn-7, &zUri[7]);
  102600. rc = SQLITE_ERROR;
  102601. goto parse_uri_out;
  102602. }
  102603. }
  102604. #endif
  102605. /* Copy the filename and any query parameters into the zFile buffer.
  102606. ** Decode %HH escape codes along the way.
  102607. **
  102608. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  102609. ** on the parsing context. As follows:
  102610. **
  102611. ** 0: Parsing file-name.
  102612. ** 1: Parsing name section of a name=value query parameter.
  102613. ** 2: Parsing value section of a name=value query parameter.
  102614. */
  102615. eState = 0;
  102616. while( (c = zUri[iIn])!=0 && c!='#' ){
  102617. iIn++;
  102618. if( c=='%'
  102619. && sqlite3Isxdigit(zUri[iIn])
  102620. && sqlite3Isxdigit(zUri[iIn+1])
  102621. ){
  102622. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  102623. octet += sqlite3HexToInt(zUri[iIn++]);
  102624. assert( octet>=0 && octet<256 );
  102625. if( octet==0 ){
  102626. /* This branch is taken when "%00" appears within the URI. In this
  102627. ** case we ignore all text in the remainder of the path, name or
  102628. ** value currently being parsed. So ignore the current character
  102629. ** and skip to the next "?", "=" or "&", as appropriate. */
  102630. while( (c = zUri[iIn])!=0 && c!='#'
  102631. && (eState!=0 || c!='?')
  102632. && (eState!=1 || (c!='=' && c!='&'))
  102633. && (eState!=2 || c!='&')
  102634. ){
  102635. iIn++;
  102636. }
  102637. continue;
  102638. }
  102639. c = octet;
  102640. }else if( eState==1 && (c=='&' || c=='=') ){
  102641. if( zFile[iOut-1]==0 ){
  102642. /* An empty option name. Ignore this option altogether. */
  102643. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  102644. continue;
  102645. }
  102646. if( c=='&' ){
  102647. zFile[iOut++] = '\0';
  102648. }else{
  102649. eState = 2;
  102650. }
  102651. c = 0;
  102652. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  102653. c = 0;
  102654. eState = 1;
  102655. }
  102656. zFile[iOut++] = c;
  102657. }
  102658. if( eState==1 ) zFile[iOut++] = '\0';
  102659. zFile[iOut++] = '\0';
  102660. zFile[iOut++] = '\0';
  102661. /* Check if there were any options specified that should be interpreted
  102662. ** here. Options that are interpreted here include "vfs" and those that
  102663. ** correspond to flags that may be passed to the sqlite3_open_v2()
  102664. ** method. */
  102665. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  102666. while( zOpt[0] ){
  102667. int nOpt = sqlite3Strlen30(zOpt);
  102668. char *zVal = &zOpt[nOpt+1];
  102669. int nVal = sqlite3Strlen30(zVal);
  102670. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  102671. zVfs = zVal;
  102672. }else{
  102673. struct OpenMode {
  102674. const char *z;
  102675. int mode;
  102676. } *aMode = 0;
  102677. char *zModeType = 0;
  102678. int mask = 0;
  102679. int limit = 0;
  102680. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  102681. static struct OpenMode aCacheMode[] = {
  102682. { "shared", SQLITE_OPEN_SHAREDCACHE },
  102683. { "private", SQLITE_OPEN_PRIVATECACHE },
  102684. { 0, 0 }
  102685. };
  102686. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  102687. aMode = aCacheMode;
  102688. limit = mask;
  102689. zModeType = "cache";
  102690. }
  102691. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  102692. static struct OpenMode aOpenMode[] = {
  102693. { "ro", SQLITE_OPEN_READONLY },
  102694. { "rw", SQLITE_OPEN_READWRITE },
  102695. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  102696. { "memory", SQLITE_OPEN_MEMORY },
  102697. { 0, 0 }
  102698. };
  102699. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  102700. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  102701. aMode = aOpenMode;
  102702. limit = mask & flags;
  102703. zModeType = "access";
  102704. }
  102705. if( aMode ){
  102706. int i;
  102707. int mode = 0;
  102708. for(i=0; aMode[i].z; i++){
  102709. const char *z = aMode[i].z;
  102710. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  102711. mode = aMode[i].mode;
  102712. break;
  102713. }
  102714. }
  102715. if( mode==0 ){
  102716. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  102717. rc = SQLITE_ERROR;
  102718. goto parse_uri_out;
  102719. }
  102720. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  102721. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  102722. zModeType, zVal);
  102723. rc = SQLITE_PERM;
  102724. goto parse_uri_out;
  102725. }
  102726. flags = (flags & ~mask) | mode;
  102727. }
  102728. }
  102729. zOpt = &zVal[nVal+1];
  102730. }
  102731. }else{
  102732. zFile = sqlite3_malloc(nUri+2);
  102733. if( !zFile ) return SQLITE_NOMEM;
  102734. memcpy(zFile, zUri, nUri);
  102735. zFile[nUri] = '\0';
  102736. zFile[nUri+1] = '\0';
  102737. flags &= ~SQLITE_OPEN_URI;
  102738. }
  102739. *ppVfs = sqlite3_vfs_find(zVfs);
  102740. if( *ppVfs==0 ){
  102741. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  102742. rc = SQLITE_ERROR;
  102743. }
  102744. parse_uri_out:
  102745. if( rc!=SQLITE_OK ){
  102746. sqlite3_free(zFile);
  102747. zFile = 0;
  102748. }
  102749. *pFlags = flags;
  102750. *pzFile = zFile;
  102751. return rc;
  102752. }
  102753. /*
  102754. ** This routine does the work of opening a database on behalf of
  102755. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  102756. ** is UTF-8 encoded.
  102757. */
  102758. static int openDatabase(
  102759. const char *zFilename, /* Database filename UTF-8 encoded */
  102760. sqlite3 **ppDb, /* OUT: Returned database handle */
  102761. unsigned int flags, /* Operational flags */
  102762. const char *zVfs /* Name of the VFS to use */
  102763. ){
  102764. sqlite3 *db; /* Store allocated handle here */
  102765. int rc; /* Return code */
  102766. int isThreadsafe; /* True for threadsafe connections */
  102767. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  102768. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  102769. *ppDb = 0;
  102770. #ifndef SQLITE_OMIT_AUTOINIT
  102771. rc = sqlite3_initialize();
  102772. if( rc ) return rc;
  102773. #endif
  102774. /* Only allow sensible combinations of bits in the flags argument.
  102775. ** Throw an error if any non-sense combination is used. If we
  102776. ** do not block illegal combinations here, it could trigger
  102777. ** assert() statements in deeper layers. Sensible combinations
  102778. ** are:
  102779. **
  102780. ** 1: SQLITE_OPEN_READONLY
  102781. ** 2: SQLITE_OPEN_READWRITE
  102782. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  102783. */
  102784. assert( SQLITE_OPEN_READONLY == 0x01 );
  102785. assert( SQLITE_OPEN_READWRITE == 0x02 );
  102786. assert( SQLITE_OPEN_CREATE == 0x04 );
  102787. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  102788. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  102789. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  102790. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  102791. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  102792. isThreadsafe = 0;
  102793. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  102794. isThreadsafe = 0;
  102795. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  102796. isThreadsafe = 1;
  102797. }else{
  102798. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  102799. }
  102800. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  102801. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  102802. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  102803. flags |= SQLITE_OPEN_SHAREDCACHE;
  102804. }
  102805. /* Remove harmful bits from the flags parameter
  102806. **
  102807. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  102808. ** dealt with in the previous code block. Besides these, the only
  102809. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  102810. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  102811. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  102812. ** off all other flags.
  102813. */
  102814. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  102815. SQLITE_OPEN_EXCLUSIVE |
  102816. SQLITE_OPEN_MAIN_DB |
  102817. SQLITE_OPEN_TEMP_DB |
  102818. SQLITE_OPEN_TRANSIENT_DB |
  102819. SQLITE_OPEN_MAIN_JOURNAL |
  102820. SQLITE_OPEN_TEMP_JOURNAL |
  102821. SQLITE_OPEN_SUBJOURNAL |
  102822. SQLITE_OPEN_MASTER_JOURNAL |
  102823. SQLITE_OPEN_NOMUTEX |
  102824. SQLITE_OPEN_FULLMUTEX |
  102825. SQLITE_OPEN_WAL
  102826. );
  102827. /* Allocate the sqlite data structure */
  102828. db = sqlite3MallocZero( sizeof(sqlite3) );
  102829. if( db==0 ) goto opendb_out;
  102830. if( isThreadsafe ){
  102831. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  102832. if( db->mutex==0 ){
  102833. sqlite3_free(db);
  102834. db = 0;
  102835. goto opendb_out;
  102836. }
  102837. }
  102838. sqlite3_mutex_enter(db->mutex);
  102839. db->errMask = 0xff;
  102840. db->nDb = 2;
  102841. db->magic = SQLITE_MAGIC_BUSY;
  102842. db->aDb = db->aDbStatic;
  102843. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  102844. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  102845. db->autoCommit = 1;
  102846. db->nextAutovac = -1;
  102847. db->szMmap = sqlite3GlobalConfig.szMmap;
  102848. db->nextPagesize = 0;
  102849. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  102850. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  102851. | SQLITE_AutoIndex
  102852. #endif
  102853. #if SQLITE_DEFAULT_FILE_FORMAT<4
  102854. | SQLITE_LegacyFileFmt
  102855. #endif
  102856. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  102857. | SQLITE_LoadExtension
  102858. #endif
  102859. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  102860. | SQLITE_RecTriggers
  102861. #endif
  102862. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  102863. | SQLITE_ForeignKeys
  102864. #endif
  102865. ;
  102866. sqlite3HashInit(&db->aCollSeq);
  102867. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102868. sqlite3HashInit(&db->aModule);
  102869. #endif
  102870. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  102871. ** and UTF-16, so add a version for each to avoid any unnecessary
  102872. ** conversions. The only error that can occur here is a malloc() failure.
  102873. */
  102874. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  102875. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  102876. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  102877. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  102878. if( db->mallocFailed ){
  102879. goto opendb_out;
  102880. }
  102881. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  102882. assert( db->pDfltColl!=0 );
  102883. /* Also add a UTF-8 case-insensitive collation sequence. */
  102884. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  102885. /* Parse the filename/URI argument. */
  102886. db->openFlags = flags;
  102887. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  102888. if( rc!=SQLITE_OK ){
  102889. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  102890. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  102891. sqlite3_free(zErrMsg);
  102892. goto opendb_out;
  102893. }
  102894. /* Open the backend database driver */
  102895. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  102896. flags | SQLITE_OPEN_MAIN_DB);
  102897. if( rc!=SQLITE_OK ){
  102898. if( rc==SQLITE_IOERR_NOMEM ){
  102899. rc = SQLITE_NOMEM;
  102900. }
  102901. sqlite3Error(db, rc, 0);
  102902. goto opendb_out;
  102903. }
  102904. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  102905. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  102906. /* The default safety_level for the main database is 'full'; for the temp
  102907. ** database it is 'NONE'. This matches the pager layer defaults.
  102908. */
  102909. db->aDb[0].zName = "main";
  102910. db->aDb[0].safety_level = 3;
  102911. db->aDb[1].zName = "temp";
  102912. db->aDb[1].safety_level = 1;
  102913. db->magic = SQLITE_MAGIC_OPEN;
  102914. if( db->mallocFailed ){
  102915. goto opendb_out;
  102916. }
  102917. /* Register all built-in functions, but do not attempt to read the
  102918. ** database schema yet. This is delayed until the first time the database
  102919. ** is accessed.
  102920. */
  102921. sqlite3Error(db, SQLITE_OK, 0);
  102922. sqlite3RegisterBuiltinFunctions(db);
  102923. /* Load automatic extensions - extensions that have been registered
  102924. ** using the sqlite3_automatic_extension() API.
  102925. */
  102926. rc = sqlite3_errcode(db);
  102927. if( rc==SQLITE_OK ){
  102928. sqlite3AutoLoadExtensions(db);
  102929. rc = sqlite3_errcode(db);
  102930. if( rc!=SQLITE_OK ){
  102931. goto opendb_out;
  102932. }
  102933. }
  102934. #ifdef SQLITE_ENABLE_FTS1
  102935. if( !db->mallocFailed ){
  102936. extern int sqlite3Fts1Init(sqlite3*);
  102937. rc = sqlite3Fts1Init(db);
  102938. }
  102939. #endif
  102940. #ifdef SQLITE_ENABLE_FTS2
  102941. if( !db->mallocFailed && rc==SQLITE_OK ){
  102942. extern int sqlite3Fts2Init(sqlite3*);
  102943. rc = sqlite3Fts2Init(db);
  102944. }
  102945. #endif
  102946. #ifdef SQLITE_ENABLE_FTS3
  102947. if( !db->mallocFailed && rc==SQLITE_OK ){
  102948. rc = sqlite3Fts3Init(db);
  102949. }
  102950. #endif
  102951. #ifdef SQLITE_ENABLE_ICU
  102952. if( !db->mallocFailed && rc==SQLITE_OK ){
  102953. rc = sqlite3IcuInit(db);
  102954. }
  102955. #endif
  102956. #ifdef SQLITE_ENABLE_RTREE
  102957. if( !db->mallocFailed && rc==SQLITE_OK){
  102958. rc = sqlite3RtreeInit(db);
  102959. }
  102960. #endif
  102961. sqlite3Error(db, rc, 0);
  102962. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  102963. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  102964. ** mode. Doing nothing at all also makes NORMAL the default.
  102965. */
  102966. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  102967. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  102968. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  102969. SQLITE_DEFAULT_LOCKING_MODE);
  102970. #endif
  102971. /* Enable the lookaside-malloc subsystem */
  102972. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  102973. sqlite3GlobalConfig.nLookaside);
  102974. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  102975. opendb_out:
  102976. sqlite3_free(zOpen);
  102977. if( db ){
  102978. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  102979. sqlite3_mutex_leave(db->mutex);
  102980. }
  102981. rc = sqlite3_errcode(db);
  102982. assert( db!=0 || rc==SQLITE_NOMEM );
  102983. if( rc==SQLITE_NOMEM ){
  102984. sqlite3_close(db);
  102985. db = 0;
  102986. }else if( rc!=SQLITE_OK ){
  102987. db->magic = SQLITE_MAGIC_SICK;
  102988. }
  102989. *ppDb = db;
  102990. #ifdef SQLITE_ENABLE_SQLLOG
  102991. if( sqlite3GlobalConfig.xSqllog ){
  102992. /* Opening a db handle. Fourth parameter is passed 0. */
  102993. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  102994. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  102995. }
  102996. #endif
  102997. return sqlite3ApiExit(0, rc);
  102998. }
  102999. /*
  103000. ** Open a new database handle.
  103001. */
  103002. SQLITE_API int sqlite3_open(
  103003. const char *zFilename,
  103004. sqlite3 **ppDb
  103005. ){
  103006. return openDatabase(zFilename, ppDb,
  103007. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  103008. }
  103009. SQLITE_API int sqlite3_open_v2(
  103010. const char *filename, /* Database filename (UTF-8) */
  103011. sqlite3 **ppDb, /* OUT: SQLite db handle */
  103012. int flags, /* Flags */
  103013. const char *zVfs /* Name of VFS module to use */
  103014. ){
  103015. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  103016. }
  103017. #ifndef SQLITE_OMIT_UTF16
  103018. /*
  103019. ** Open a new database handle.
  103020. */
  103021. SQLITE_API int sqlite3_open16(
  103022. const void *zFilename,
  103023. sqlite3 **ppDb
  103024. ){
  103025. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  103026. sqlite3_value *pVal;
  103027. int rc;
  103028. assert( zFilename );
  103029. assert( ppDb );
  103030. *ppDb = 0;
  103031. #ifndef SQLITE_OMIT_AUTOINIT
  103032. rc = sqlite3_initialize();
  103033. if( rc ) return rc;
  103034. #endif
  103035. pVal = sqlite3ValueNew(0);
  103036. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  103037. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  103038. if( zFilename8 ){
  103039. rc = openDatabase(zFilename8, ppDb,
  103040. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  103041. assert( *ppDb || rc==SQLITE_NOMEM );
  103042. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  103043. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  103044. }
  103045. }else{
  103046. rc = SQLITE_NOMEM;
  103047. }
  103048. sqlite3ValueFree(pVal);
  103049. return sqlite3ApiExit(0, rc);
  103050. }
  103051. #endif /* SQLITE_OMIT_UTF16 */
  103052. /*
  103053. ** Register a new collation sequence with the database handle db.
  103054. */
  103055. SQLITE_API int sqlite3_create_collation(
  103056. sqlite3* db,
  103057. const char *zName,
  103058. int enc,
  103059. void* pCtx,
  103060. int(*xCompare)(void*,int,const void*,int,const void*)
  103061. ){
  103062. int rc;
  103063. sqlite3_mutex_enter(db->mutex);
  103064. assert( !db->mallocFailed );
  103065. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  103066. rc = sqlite3ApiExit(db, rc);
  103067. sqlite3_mutex_leave(db->mutex);
  103068. return rc;
  103069. }
  103070. /*
  103071. ** Register a new collation sequence with the database handle db.
  103072. */
  103073. SQLITE_API int sqlite3_create_collation_v2(
  103074. sqlite3* db,
  103075. const char *zName,
  103076. int enc,
  103077. void* pCtx,
  103078. int(*xCompare)(void*,int,const void*,int,const void*),
  103079. void(*xDel)(void*)
  103080. ){
  103081. int rc;
  103082. sqlite3_mutex_enter(db->mutex);
  103083. assert( !db->mallocFailed );
  103084. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  103085. rc = sqlite3ApiExit(db, rc);
  103086. sqlite3_mutex_leave(db->mutex);
  103087. return rc;
  103088. }
  103089. #ifndef SQLITE_OMIT_UTF16
  103090. /*
  103091. ** Register a new collation sequence with the database handle db.
  103092. */
  103093. SQLITE_API int sqlite3_create_collation16(
  103094. sqlite3* db,
  103095. const void *zName,
  103096. int enc,
  103097. void* pCtx,
  103098. int(*xCompare)(void*,int,const void*,int,const void*)
  103099. ){
  103100. int rc = SQLITE_OK;
  103101. char *zName8;
  103102. sqlite3_mutex_enter(db->mutex);
  103103. assert( !db->mallocFailed );
  103104. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  103105. if( zName8 ){
  103106. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  103107. sqlite3DbFree(db, zName8);
  103108. }
  103109. rc = sqlite3ApiExit(db, rc);
  103110. sqlite3_mutex_leave(db->mutex);
  103111. return rc;
  103112. }
  103113. #endif /* SQLITE_OMIT_UTF16 */
  103114. /*
  103115. ** Register a collation sequence factory callback with the database handle
  103116. ** db. Replace any previously installed collation sequence factory.
  103117. */
  103118. SQLITE_API int sqlite3_collation_needed(
  103119. sqlite3 *db,
  103120. void *pCollNeededArg,
  103121. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  103122. ){
  103123. sqlite3_mutex_enter(db->mutex);
  103124. db->xCollNeeded = xCollNeeded;
  103125. db->xCollNeeded16 = 0;
  103126. db->pCollNeededArg = pCollNeededArg;
  103127. sqlite3_mutex_leave(db->mutex);
  103128. return SQLITE_OK;
  103129. }
  103130. #ifndef SQLITE_OMIT_UTF16
  103131. /*
  103132. ** Register a collation sequence factory callback with the database handle
  103133. ** db. Replace any previously installed collation sequence factory.
  103134. */
  103135. SQLITE_API int sqlite3_collation_needed16(
  103136. sqlite3 *db,
  103137. void *pCollNeededArg,
  103138. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  103139. ){
  103140. sqlite3_mutex_enter(db->mutex);
  103141. db->xCollNeeded = 0;
  103142. db->xCollNeeded16 = xCollNeeded16;
  103143. db->pCollNeededArg = pCollNeededArg;
  103144. sqlite3_mutex_leave(db->mutex);
  103145. return SQLITE_OK;
  103146. }
  103147. #endif /* SQLITE_OMIT_UTF16 */
  103148. #ifndef SQLITE_OMIT_DEPRECATED
  103149. /*
  103150. ** This function is now an anachronism. It used to be used to recover from a
  103151. ** malloc() failure, but SQLite now does this automatically.
  103152. */
  103153. SQLITE_API int sqlite3_global_recover(void){
  103154. return SQLITE_OK;
  103155. }
  103156. #endif
  103157. /*
  103158. ** Test to see whether or not the database connection is in autocommit
  103159. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  103160. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  103161. ** by the next COMMIT or ROLLBACK.
  103162. */
  103163. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  103164. return db->autoCommit;
  103165. }
  103166. /*
  103167. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  103168. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  103169. ** constants. They server two purposes:
  103170. **
  103171. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  103172. ** to detect when version error conditions occurs.
  103173. **
  103174. ** 2. Invoke sqlite3_log() to provide the source code location where
  103175. ** a low-level error is first detected.
  103176. */
  103177. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  103178. testcase( sqlite3GlobalConfig.xLog!=0 );
  103179. sqlite3_log(SQLITE_CORRUPT,
  103180. "database corruption at line %d of [%.10s]",
  103181. lineno, 20+sqlite3_sourceid());
  103182. return SQLITE_CORRUPT;
  103183. }
  103184. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  103185. testcase( sqlite3GlobalConfig.xLog!=0 );
  103186. sqlite3_log(SQLITE_MISUSE,
  103187. "misuse at line %d of [%.10s]",
  103188. lineno, 20+sqlite3_sourceid());
  103189. return SQLITE_MISUSE;
  103190. }
  103191. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  103192. testcase( sqlite3GlobalConfig.xLog!=0 );
  103193. sqlite3_log(SQLITE_CANTOPEN,
  103194. "cannot open file at line %d of [%.10s]",
  103195. lineno, 20+sqlite3_sourceid());
  103196. return SQLITE_CANTOPEN;
  103197. }
  103198. #ifndef SQLITE_OMIT_DEPRECATED
  103199. /*
  103200. ** This is a convenience routine that makes sure that all thread-specific
  103201. ** data for this thread has been deallocated.
  103202. **
  103203. ** SQLite no longer uses thread-specific data so this routine is now a
  103204. ** no-op. It is retained for historical compatibility.
  103205. */
  103206. SQLITE_API void sqlite3_thread_cleanup(void){
  103207. }
  103208. #endif
  103209. /*
  103210. ** Return meta information about a specific column of a database table.
  103211. ** See comment in sqlite3.h (sqlite.h.in) for details.
  103212. */
  103213. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103214. SQLITE_API int sqlite3_table_column_metadata(
  103215. sqlite3 *db, /* Connection handle */
  103216. const char *zDbName, /* Database name or NULL */
  103217. const char *zTableName, /* Table name */
  103218. const char *zColumnName, /* Column name */
  103219. char const **pzDataType, /* OUTPUT: Declared data type */
  103220. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  103221. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  103222. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  103223. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  103224. ){
  103225. int rc;
  103226. char *zErrMsg = 0;
  103227. Table *pTab = 0;
  103228. Column *pCol = 0;
  103229. int iCol;
  103230. char const *zDataType = 0;
  103231. char const *zCollSeq = 0;
  103232. int notnull = 0;
  103233. int primarykey = 0;
  103234. int autoinc = 0;
  103235. /* Ensure the database schema has been loaded */
  103236. sqlite3_mutex_enter(db->mutex);
  103237. sqlite3BtreeEnterAll(db);
  103238. rc = sqlite3Init(db, &zErrMsg);
  103239. if( SQLITE_OK!=rc ){
  103240. goto error_out;
  103241. }
  103242. /* Locate the table in question */
  103243. pTab = sqlite3FindTable(db, zTableName, zDbName);
  103244. if( !pTab || pTab->pSelect ){
  103245. pTab = 0;
  103246. goto error_out;
  103247. }
  103248. /* Find the column for which info is requested */
  103249. if( sqlite3IsRowid(zColumnName) ){
  103250. iCol = pTab->iPKey;
  103251. if( iCol>=0 ){
  103252. pCol = &pTab->aCol[iCol];
  103253. }
  103254. }else{
  103255. for(iCol=0; iCol<pTab->nCol; iCol++){
  103256. pCol = &pTab->aCol[iCol];
  103257. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  103258. break;
  103259. }
  103260. }
  103261. if( iCol==pTab->nCol ){
  103262. pTab = 0;
  103263. goto error_out;
  103264. }
  103265. }
  103266. /* The following block stores the meta information that will be returned
  103267. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  103268. ** and autoinc. At this point there are two possibilities:
  103269. **
  103270. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  103271. ** and there is no explicitly declared IPK column.
  103272. **
  103273. ** 2. The table is not a view and the column name identified an
  103274. ** explicitly declared column. Copy meta information from *pCol.
  103275. */
  103276. if( pCol ){
  103277. zDataType = pCol->zType;
  103278. zCollSeq = pCol->zColl;
  103279. notnull = pCol->notNull!=0;
  103280. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  103281. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  103282. }else{
  103283. zDataType = "INTEGER";
  103284. primarykey = 1;
  103285. }
  103286. if( !zCollSeq ){
  103287. zCollSeq = "BINARY";
  103288. }
  103289. error_out:
  103290. sqlite3BtreeLeaveAll(db);
  103291. /* Whether the function call succeeded or failed, set the output parameters
  103292. ** to whatever their local counterparts contain. If an error did occur,
  103293. ** this has the effect of zeroing all output parameters.
  103294. */
  103295. if( pzDataType ) *pzDataType = zDataType;
  103296. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  103297. if( pNotNull ) *pNotNull = notnull;
  103298. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  103299. if( pAutoinc ) *pAutoinc = autoinc;
  103300. if( SQLITE_OK==rc && !pTab ){
  103301. sqlite3DbFree(db, zErrMsg);
  103302. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  103303. zColumnName);
  103304. rc = SQLITE_ERROR;
  103305. }
  103306. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  103307. sqlite3DbFree(db, zErrMsg);
  103308. rc = sqlite3ApiExit(db, rc);
  103309. sqlite3_mutex_leave(db->mutex);
  103310. return rc;
  103311. }
  103312. #endif
  103313. /*
  103314. ** Sleep for a little while. Return the amount of time slept.
  103315. */
  103316. SQLITE_API int sqlite3_sleep(int ms){
  103317. sqlite3_vfs *pVfs;
  103318. int rc;
  103319. pVfs = sqlite3_vfs_find(0);
  103320. if( pVfs==0 ) return 0;
  103321. /* This function works in milliseconds, but the underlying OsSleep()
  103322. ** API uses microseconds. Hence the 1000's.
  103323. */
  103324. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  103325. return rc;
  103326. }
  103327. /*
  103328. ** Enable or disable the extended result codes.
  103329. */
  103330. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  103331. sqlite3_mutex_enter(db->mutex);
  103332. db->errMask = onoff ? 0xffffffff : 0xff;
  103333. sqlite3_mutex_leave(db->mutex);
  103334. return SQLITE_OK;
  103335. }
  103336. /*
  103337. ** Invoke the xFileControl method on a particular database.
  103338. */
  103339. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  103340. int rc = SQLITE_ERROR;
  103341. Btree *pBtree;
  103342. sqlite3_mutex_enter(db->mutex);
  103343. pBtree = sqlite3DbNameToBtree(db, zDbName);
  103344. if( pBtree ){
  103345. Pager *pPager;
  103346. sqlite3_file *fd;
  103347. sqlite3BtreeEnter(pBtree);
  103348. pPager = sqlite3BtreePager(pBtree);
  103349. assert( pPager!=0 );
  103350. fd = sqlite3PagerFile(pPager);
  103351. assert( fd!=0 );
  103352. if( op==SQLITE_FCNTL_FILE_POINTER ){
  103353. *(sqlite3_file**)pArg = fd;
  103354. rc = SQLITE_OK;
  103355. }else if( fd->pMethods ){
  103356. rc = sqlite3OsFileControl(fd, op, pArg);
  103357. }else{
  103358. rc = SQLITE_NOTFOUND;
  103359. }
  103360. sqlite3BtreeLeave(pBtree);
  103361. }
  103362. sqlite3_mutex_leave(db->mutex);
  103363. return rc;
  103364. }
  103365. /*
  103366. ** Interface to the testing logic.
  103367. */
  103368. SQLITE_API int sqlite3_test_control(int op, ...){
  103369. int rc = 0;
  103370. #ifndef SQLITE_OMIT_BUILTIN_TEST
  103371. va_list ap;
  103372. va_start(ap, op);
  103373. switch( op ){
  103374. /*
  103375. ** Save the current state of the PRNG.
  103376. */
  103377. case SQLITE_TESTCTRL_PRNG_SAVE: {
  103378. sqlite3PrngSaveState();
  103379. break;
  103380. }
  103381. /*
  103382. ** Restore the state of the PRNG to the last state saved using
  103383. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  103384. ** this verb acts like PRNG_RESET.
  103385. */
  103386. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  103387. sqlite3PrngRestoreState();
  103388. break;
  103389. }
  103390. /*
  103391. ** Reset the PRNG back to its uninitialized state. The next call
  103392. ** to sqlite3_randomness() will reseed the PRNG using a single call
  103393. ** to the xRandomness method of the default VFS.
  103394. */
  103395. case SQLITE_TESTCTRL_PRNG_RESET: {
  103396. sqlite3PrngResetState();
  103397. break;
  103398. }
  103399. /*
  103400. ** sqlite3_test_control(BITVEC_TEST, size, program)
  103401. **
  103402. ** Run a test against a Bitvec object of size. The program argument
  103403. ** is an array of integers that defines the test. Return -1 on a
  103404. ** memory allocation error, 0 on success, or non-zero for an error.
  103405. ** See the sqlite3BitvecBuiltinTest() for additional information.
  103406. */
  103407. case SQLITE_TESTCTRL_BITVEC_TEST: {
  103408. int sz = va_arg(ap, int);
  103409. int *aProg = va_arg(ap, int*);
  103410. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  103411. break;
  103412. }
  103413. /*
  103414. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  103415. **
  103416. ** Register hooks to call to indicate which malloc() failures
  103417. ** are benign.
  103418. */
  103419. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  103420. typedef void (*void_function)(void);
  103421. void_function xBenignBegin;
  103422. void_function xBenignEnd;
  103423. xBenignBegin = va_arg(ap, void_function);
  103424. xBenignEnd = va_arg(ap, void_function);
  103425. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  103426. break;
  103427. }
  103428. /*
  103429. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  103430. **
  103431. ** Set the PENDING byte to the value in the argument, if X>0.
  103432. ** Make no changes if X==0. Return the value of the pending byte
  103433. ** as it existing before this routine was called.
  103434. **
  103435. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  103436. ** an incompatible database file format. Changing the PENDING byte
  103437. ** while any database connection is open results in undefined and
  103438. ** dileterious behavior.
  103439. */
  103440. case SQLITE_TESTCTRL_PENDING_BYTE: {
  103441. rc = PENDING_BYTE;
  103442. #ifndef SQLITE_OMIT_WSD
  103443. {
  103444. unsigned int newVal = va_arg(ap, unsigned int);
  103445. if( newVal ) sqlite3PendingByte = newVal;
  103446. }
  103447. #endif
  103448. break;
  103449. }
  103450. /*
  103451. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  103452. **
  103453. ** This action provides a run-time test to see whether or not
  103454. ** assert() was enabled at compile-time. If X is true and assert()
  103455. ** is enabled, then the return value is true. If X is true and
  103456. ** assert() is disabled, then the return value is zero. If X is
  103457. ** false and assert() is enabled, then the assertion fires and the
  103458. ** process aborts. If X is false and assert() is disabled, then the
  103459. ** return value is zero.
  103460. */
  103461. case SQLITE_TESTCTRL_ASSERT: {
  103462. volatile int x = 0;
  103463. assert( (x = va_arg(ap,int))!=0 );
  103464. rc = x;
  103465. break;
  103466. }
  103467. /*
  103468. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  103469. **
  103470. ** This action provides a run-time test to see how the ALWAYS and
  103471. ** NEVER macros were defined at compile-time.
  103472. **
  103473. ** The return value is ALWAYS(X).
  103474. **
  103475. ** The recommended test is X==2. If the return value is 2, that means
  103476. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  103477. ** default setting. If the return value is 1, then ALWAYS() is either
  103478. ** hard-coded to true or else it asserts if its argument is false.
  103479. ** The first behavior (hard-coded to true) is the case if
  103480. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  103481. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  103482. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  103483. **
  103484. ** The run-time test procedure might look something like this:
  103485. **
  103486. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  103487. ** // ALWAYS() and NEVER() are no-op pass-through macros
  103488. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  103489. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  103490. ** }else{
  103491. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  103492. ** }
  103493. */
  103494. case SQLITE_TESTCTRL_ALWAYS: {
  103495. int x = va_arg(ap,int);
  103496. rc = ALWAYS(x);
  103497. break;
  103498. }
  103499. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  103500. **
  103501. ** Set the nReserve size to N for the main database on the database
  103502. ** connection db.
  103503. */
  103504. case SQLITE_TESTCTRL_RESERVE: {
  103505. sqlite3 *db = va_arg(ap, sqlite3*);
  103506. int x = va_arg(ap,int);
  103507. sqlite3_mutex_enter(db->mutex);
  103508. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  103509. sqlite3_mutex_leave(db->mutex);
  103510. break;
  103511. }
  103512. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  103513. **
  103514. ** Enable or disable various optimizations for testing purposes. The
  103515. ** argument N is a bitmask of optimizations to be disabled. For normal
  103516. ** operation N should be 0. The idea is that a test program (like the
  103517. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  103518. ** with various optimizations disabled to verify that the same answer
  103519. ** is obtained in every case.
  103520. */
  103521. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  103522. sqlite3 *db = va_arg(ap, sqlite3*);
  103523. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  103524. break;
  103525. }
  103526. #ifdef SQLITE_N_KEYWORD
  103527. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  103528. **
  103529. ** If zWord is a keyword recognized by the parser, then return the
  103530. ** number of keywords. Or if zWord is not a keyword, return 0.
  103531. **
  103532. ** This test feature is only available in the amalgamation since
  103533. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  103534. ** is built using separate source files.
  103535. */
  103536. case SQLITE_TESTCTRL_ISKEYWORD: {
  103537. const char *zWord = va_arg(ap, const char*);
  103538. int n = sqlite3Strlen30(zWord);
  103539. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  103540. break;
  103541. }
  103542. #endif
  103543. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  103544. **
  103545. ** Pass pFree into sqlite3ScratchFree().
  103546. ** If sz>0 then allocate a scratch buffer into pNew.
  103547. */
  103548. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  103549. void *pFree, **ppNew;
  103550. int sz;
  103551. sz = va_arg(ap, int);
  103552. ppNew = va_arg(ap, void**);
  103553. pFree = va_arg(ap, void*);
  103554. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  103555. sqlite3ScratchFree(pFree);
  103556. break;
  103557. }
  103558. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  103559. **
  103560. ** If parameter onoff is non-zero, configure the wrappers so that all
  103561. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  103562. ** undo this setting.
  103563. */
  103564. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  103565. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  103566. break;
  103567. }
  103568. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  103569. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  103570. ** sqlite3_stmt*,const char**);
  103571. **
  103572. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  103573. ** a string that describes the optimized parse tree. This test-control
  103574. ** returns a pointer to that string.
  103575. */
  103576. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  103577. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  103578. const char **pzRet = va_arg(ap, const char**);
  103579. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  103580. break;
  103581. }
  103582. #endif
  103583. }
  103584. va_end(ap);
  103585. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  103586. return rc;
  103587. }
  103588. /*
  103589. ** This is a utility routine, useful to VFS implementations, that checks
  103590. ** to see if a database file was a URI that contained a specific query
  103591. ** parameter, and if so obtains the value of the query parameter.
  103592. **
  103593. ** The zFilename argument is the filename pointer passed into the xOpen()
  103594. ** method of a VFS implementation. The zParam argument is the name of the
  103595. ** query parameter we seek. This routine returns the value of the zParam
  103596. ** parameter if it exists. If the parameter does not exist, this routine
  103597. ** returns a NULL pointer.
  103598. */
  103599. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  103600. if( zFilename==0 ) return 0;
  103601. zFilename += sqlite3Strlen30(zFilename) + 1;
  103602. while( zFilename[0] ){
  103603. int x = strcmp(zFilename, zParam);
  103604. zFilename += sqlite3Strlen30(zFilename) + 1;
  103605. if( x==0 ) return zFilename;
  103606. zFilename += sqlite3Strlen30(zFilename) + 1;
  103607. }
  103608. return 0;
  103609. }
  103610. /*
  103611. ** Return a boolean value for a query parameter.
  103612. */
  103613. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  103614. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  103615. bDflt = bDflt!=0;
  103616. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  103617. }
  103618. /*
  103619. ** Return a 64-bit integer value for a query parameter.
  103620. */
  103621. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  103622. const char *zFilename, /* Filename as passed to xOpen */
  103623. const char *zParam, /* URI parameter sought */
  103624. sqlite3_int64 bDflt /* return if parameter is missing */
  103625. ){
  103626. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  103627. sqlite3_int64 v;
  103628. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  103629. bDflt = v;
  103630. }
  103631. return bDflt;
  103632. }
  103633. /*
  103634. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  103635. */
  103636. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  103637. int i;
  103638. for(i=0; i<db->nDb; i++){
  103639. if( db->aDb[i].pBt
  103640. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  103641. ){
  103642. return db->aDb[i].pBt;
  103643. }
  103644. }
  103645. return 0;
  103646. }
  103647. /*
  103648. ** Return the filename of the database associated with a database
  103649. ** connection.
  103650. */
  103651. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  103652. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  103653. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  103654. }
  103655. /*
  103656. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  103657. ** no such database exists.
  103658. */
  103659. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  103660. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  103661. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  103662. }
  103663. /************** End of main.c ************************************************/
  103664. /************** Begin file notify.c ******************************************/
  103665. /*
  103666. ** 2009 March 3
  103667. **
  103668. ** The author disclaims copyright to this source code. In place of
  103669. ** a legal notice, here is a blessing:
  103670. **
  103671. ** May you do good and not evil.
  103672. ** May you find forgiveness for yourself and forgive others.
  103673. ** May you share freely, never taking more than you give.
  103674. **
  103675. *************************************************************************
  103676. **
  103677. ** This file contains the implementation of the sqlite3_unlock_notify()
  103678. ** API method and its associated functionality.
  103679. */
  103680. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  103681. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  103682. /*
  103683. ** Public interfaces:
  103684. **
  103685. ** sqlite3ConnectionBlocked()
  103686. ** sqlite3ConnectionUnlocked()
  103687. ** sqlite3ConnectionClosed()
  103688. ** sqlite3_unlock_notify()
  103689. */
  103690. #define assertMutexHeld() \
  103691. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  103692. /*
  103693. ** Head of a linked list of all sqlite3 objects created by this process
  103694. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  103695. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  103696. ** mutex is held.
  103697. */
  103698. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  103699. #ifndef NDEBUG
  103700. /*
  103701. ** This function is a complex assert() that verifies the following
  103702. ** properties of the blocked connections list:
  103703. **
  103704. ** 1) Each entry in the list has a non-NULL value for either
  103705. ** pUnlockConnection or pBlockingConnection, or both.
  103706. **
  103707. ** 2) All entries in the list that share a common value for
  103708. ** xUnlockNotify are grouped together.
  103709. **
  103710. ** 3) If the argument db is not NULL, then none of the entries in the
  103711. ** blocked connections list have pUnlockConnection or pBlockingConnection
  103712. ** set to db. This is used when closing connection db.
  103713. */
  103714. static void checkListProperties(sqlite3 *db){
  103715. sqlite3 *p;
  103716. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  103717. int seen = 0;
  103718. sqlite3 *p2;
  103719. /* Verify property (1) */
  103720. assert( p->pUnlockConnection || p->pBlockingConnection );
  103721. /* Verify property (2) */
  103722. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  103723. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  103724. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  103725. assert( db==0 || p->pUnlockConnection!=db );
  103726. assert( db==0 || p->pBlockingConnection!=db );
  103727. }
  103728. }
  103729. }
  103730. #else
  103731. # define checkListProperties(x)
  103732. #endif
  103733. /*
  103734. ** Remove connection db from the blocked connections list. If connection
  103735. ** db is not currently a part of the list, this function is a no-op.
  103736. */
  103737. static void removeFromBlockedList(sqlite3 *db){
  103738. sqlite3 **pp;
  103739. assertMutexHeld();
  103740. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  103741. if( *pp==db ){
  103742. *pp = (*pp)->pNextBlocked;
  103743. break;
  103744. }
  103745. }
  103746. }
  103747. /*
  103748. ** Add connection db to the blocked connections list. It is assumed
  103749. ** that it is not already a part of the list.
  103750. */
  103751. static void addToBlockedList(sqlite3 *db){
  103752. sqlite3 **pp;
  103753. assertMutexHeld();
  103754. for(
  103755. pp=&sqlite3BlockedList;
  103756. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  103757. pp=&(*pp)->pNextBlocked
  103758. );
  103759. db->pNextBlocked = *pp;
  103760. *pp = db;
  103761. }
  103762. /*
  103763. ** Obtain the STATIC_MASTER mutex.
  103764. */
  103765. static void enterMutex(void){
  103766. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  103767. checkListProperties(0);
  103768. }
  103769. /*
  103770. ** Release the STATIC_MASTER mutex.
  103771. */
  103772. static void leaveMutex(void){
  103773. assertMutexHeld();
  103774. checkListProperties(0);
  103775. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  103776. }
  103777. /*
  103778. ** Register an unlock-notify callback.
  103779. **
  103780. ** This is called after connection "db" has attempted some operation
  103781. ** but has received an SQLITE_LOCKED error because another connection
  103782. ** (call it pOther) in the same process was busy using the same shared
  103783. ** cache. pOther is found by looking at db->pBlockingConnection.
  103784. **
  103785. ** If there is no blocking connection, the callback is invoked immediately,
  103786. ** before this routine returns.
  103787. **
  103788. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  103789. ** a deadlock.
  103790. **
  103791. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  103792. ** its locks.
  103793. **
  103794. ** Each call to this routine overrides any prior callbacks registered
  103795. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  103796. ** cancelled.
  103797. */
  103798. SQLITE_API int sqlite3_unlock_notify(
  103799. sqlite3 *db,
  103800. void (*xNotify)(void **, int),
  103801. void *pArg
  103802. ){
  103803. int rc = SQLITE_OK;
  103804. sqlite3_mutex_enter(db->mutex);
  103805. enterMutex();
  103806. if( xNotify==0 ){
  103807. removeFromBlockedList(db);
  103808. db->pBlockingConnection = 0;
  103809. db->pUnlockConnection = 0;
  103810. db->xUnlockNotify = 0;
  103811. db->pUnlockArg = 0;
  103812. }else if( 0==db->pBlockingConnection ){
  103813. /* The blocking transaction has been concluded. Or there never was a
  103814. ** blocking transaction. In either case, invoke the notify callback
  103815. ** immediately.
  103816. */
  103817. xNotify(&pArg, 1);
  103818. }else{
  103819. sqlite3 *p;
  103820. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  103821. if( p ){
  103822. rc = SQLITE_LOCKED; /* Deadlock detected. */
  103823. }else{
  103824. db->pUnlockConnection = db->pBlockingConnection;
  103825. db->xUnlockNotify = xNotify;
  103826. db->pUnlockArg = pArg;
  103827. removeFromBlockedList(db);
  103828. addToBlockedList(db);
  103829. }
  103830. }
  103831. leaveMutex();
  103832. assert( !db->mallocFailed );
  103833. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  103834. sqlite3_mutex_leave(db->mutex);
  103835. return rc;
  103836. }
  103837. /*
  103838. ** This function is called while stepping or preparing a statement
  103839. ** associated with connection db. The operation will return SQLITE_LOCKED
  103840. ** to the user because it requires a lock that will not be available
  103841. ** until connection pBlocker concludes its current transaction.
  103842. */
  103843. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  103844. enterMutex();
  103845. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  103846. addToBlockedList(db);
  103847. }
  103848. db->pBlockingConnection = pBlocker;
  103849. leaveMutex();
  103850. }
  103851. /*
  103852. ** This function is called when
  103853. ** the transaction opened by database db has just finished. Locks held
  103854. ** by database connection db have been released.
  103855. **
  103856. ** This function loops through each entry in the blocked connections
  103857. ** list and does the following:
  103858. **
  103859. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  103860. ** set to db, then set pBlockingConnection=0.
  103861. **
  103862. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  103863. ** set to db, then invoke the configured unlock-notify callback and
  103864. ** set pUnlockConnection=0.
  103865. **
  103866. ** 3) If the two steps above mean that pBlockingConnection==0 and
  103867. ** pUnlockConnection==0, remove the entry from the blocked connections
  103868. ** list.
  103869. */
  103870. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  103871. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  103872. int nArg = 0; /* Number of entries in aArg[] */
  103873. sqlite3 **pp; /* Iterator variable */
  103874. void **aArg; /* Arguments to the unlock callback */
  103875. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  103876. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  103877. aArg = aStatic;
  103878. enterMutex(); /* Enter STATIC_MASTER mutex */
  103879. /* This loop runs once for each entry in the blocked-connections list. */
  103880. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  103881. sqlite3 *p = *pp;
  103882. /* Step 1. */
  103883. if( p->pBlockingConnection==db ){
  103884. p->pBlockingConnection = 0;
  103885. }
  103886. /* Step 2. */
  103887. if( p->pUnlockConnection==db ){
  103888. assert( p->xUnlockNotify );
  103889. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  103890. xUnlockNotify(aArg, nArg);
  103891. nArg = 0;
  103892. }
  103893. sqlite3BeginBenignMalloc();
  103894. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  103895. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  103896. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  103897. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  103898. ){
  103899. /* The aArg[] array needs to grow. */
  103900. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  103901. if( pNew ){
  103902. memcpy(pNew, aArg, nArg*sizeof(void *));
  103903. sqlite3_free(aDyn);
  103904. aDyn = aArg = pNew;
  103905. }else{
  103906. /* This occurs when the array of context pointers that need to
  103907. ** be passed to the unlock-notify callback is larger than the
  103908. ** aStatic[] array allocated on the stack and the attempt to
  103909. ** allocate a larger array from the heap has failed.
  103910. **
  103911. ** This is a difficult situation to handle. Returning an error
  103912. ** code to the caller is insufficient, as even if an error code
  103913. ** is returned the transaction on connection db will still be
  103914. ** closed and the unlock-notify callbacks on blocked connections
  103915. ** will go unissued. This might cause the application to wait
  103916. ** indefinitely for an unlock-notify callback that will never
  103917. ** arrive.
  103918. **
  103919. ** Instead, invoke the unlock-notify callback with the context
  103920. ** array already accumulated. We can then clear the array and
  103921. ** begin accumulating any further context pointers without
  103922. ** requiring any dynamic allocation. This is sub-optimal because
  103923. ** it means that instead of one callback with a large array of
  103924. ** context pointers the application will receive two or more
  103925. ** callbacks with smaller arrays of context pointers, which will
  103926. ** reduce the applications ability to prioritize multiple
  103927. ** connections. But it is the best that can be done under the
  103928. ** circumstances.
  103929. */
  103930. xUnlockNotify(aArg, nArg);
  103931. nArg = 0;
  103932. }
  103933. }
  103934. sqlite3EndBenignMalloc();
  103935. aArg[nArg++] = p->pUnlockArg;
  103936. xUnlockNotify = p->xUnlockNotify;
  103937. p->pUnlockConnection = 0;
  103938. p->xUnlockNotify = 0;
  103939. p->pUnlockArg = 0;
  103940. }
  103941. /* Step 3. */
  103942. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  103943. /* Remove connection p from the blocked connections list. */
  103944. *pp = p->pNextBlocked;
  103945. p->pNextBlocked = 0;
  103946. }else{
  103947. pp = &p->pNextBlocked;
  103948. }
  103949. }
  103950. if( nArg!=0 ){
  103951. xUnlockNotify(aArg, nArg);
  103952. }
  103953. sqlite3_free(aDyn);
  103954. leaveMutex(); /* Leave STATIC_MASTER mutex */
  103955. }
  103956. /*
  103957. ** This is called when the database connection passed as an argument is
  103958. ** being closed. The connection is removed from the blocked list.
  103959. */
  103960. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  103961. sqlite3ConnectionUnlocked(db);
  103962. enterMutex();
  103963. removeFromBlockedList(db);
  103964. checkListProperties(db);
  103965. leaveMutex();
  103966. }
  103967. #endif
  103968. /************** End of notify.c **********************************************/
  103969. /************** Begin file fts3.c ********************************************/
  103970. /*
  103971. ** 2006 Oct 10
  103972. **
  103973. ** The author disclaims copyright to this source code. In place of
  103974. ** a legal notice, here is a blessing:
  103975. **
  103976. ** May you do good and not evil.
  103977. ** May you find forgiveness for yourself and forgive others.
  103978. ** May you share freely, never taking more than you give.
  103979. **
  103980. ******************************************************************************
  103981. **
  103982. ** This is an SQLite module implementing full-text search.
  103983. */
  103984. /*
  103985. ** The code in this file is only compiled if:
  103986. **
  103987. ** * The FTS3 module is being built as an extension
  103988. ** (in which case SQLITE_CORE is not defined), or
  103989. **
  103990. ** * The FTS3 module is being built into the core of
  103991. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  103992. */
  103993. /* The full-text index is stored in a series of b+tree (-like)
  103994. ** structures called segments which map terms to doclists. The
  103995. ** structures are like b+trees in layout, but are constructed from the
  103996. ** bottom up in optimal fashion and are not updatable. Since trees
  103997. ** are built from the bottom up, things will be described from the
  103998. ** bottom up.
  103999. **
  104000. **
  104001. **** Varints ****
  104002. ** The basic unit of encoding is a variable-length integer called a
  104003. ** varint. We encode variable-length integers in little-endian order
  104004. ** using seven bits * per byte as follows:
  104005. **
  104006. ** KEY:
  104007. ** A = 0xxxxxxx 7 bits of data and one flag bit
  104008. ** B = 1xxxxxxx 7 bits of data and one flag bit
  104009. **
  104010. ** 7 bits - A
  104011. ** 14 bits - BA
  104012. ** 21 bits - BBA
  104013. ** and so on.
  104014. **
  104015. ** This is similar in concept to how sqlite encodes "varints" but
  104016. ** the encoding is not the same. SQLite varints are big-endian
  104017. ** are are limited to 9 bytes in length whereas FTS3 varints are
  104018. ** little-endian and can be up to 10 bytes in length (in theory).
  104019. **
  104020. ** Example encodings:
  104021. **
  104022. ** 1: 0x01
  104023. ** 127: 0x7f
  104024. ** 128: 0x81 0x00
  104025. **
  104026. **
  104027. **** Document lists ****
  104028. ** A doclist (document list) holds a docid-sorted list of hits for a
  104029. ** given term. Doclists hold docids and associated token positions.
  104030. ** A docid is the unique integer identifier for a single document.
  104031. ** A position is the index of a word within the document. The first
  104032. ** word of the document has a position of 0.
  104033. **
  104034. ** FTS3 used to optionally store character offsets using a compile-time
  104035. ** option. But that functionality is no longer supported.
  104036. **
  104037. ** A doclist is stored like this:
  104038. **
  104039. ** array {
  104040. ** varint docid; (delta from previous doclist)
  104041. ** array { (position list for column 0)
  104042. ** varint position; (2 more than the delta from previous position)
  104043. ** }
  104044. ** array {
  104045. ** varint POS_COLUMN; (marks start of position list for new column)
  104046. ** varint column; (index of new column)
  104047. ** array {
  104048. ** varint position; (2 more than the delta from previous position)
  104049. ** }
  104050. ** }
  104051. ** varint POS_END; (marks end of positions for this document.
  104052. ** }
  104053. **
  104054. ** Here, array { X } means zero or more occurrences of X, adjacent in
  104055. ** memory. A "position" is an index of a token in the token stream
  104056. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  104057. ** in the same logical place as the position element, and act as sentinals
  104058. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  104059. ** The positions numbers are not stored literally but rather as two more
  104060. ** than the difference from the prior position, or the just the position plus
  104061. ** 2 for the first position. Example:
  104062. **
  104063. ** label: A B C D E F G H I J K
  104064. ** value: 123 5 9 1 1 14 35 0 234 72 0
  104065. **
  104066. ** The 123 value is the first docid. For column zero in this document
  104067. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  104068. ** at D signals the start of a new column; the 1 at E indicates that the
  104069. ** new column is column number 1. There are two positions at 12 and 45
  104070. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  104071. ** 234 at I is the delta to next docid (357). It has one position 70
  104072. ** (72-2) and then terminates with the 0 at K.
  104073. **
  104074. ** A "position-list" is the list of positions for multiple columns for
  104075. ** a single docid. A "column-list" is the set of positions for a single
  104076. ** column. Hence, a position-list consists of one or more column-lists,
  104077. ** a document record consists of a docid followed by a position-list and
  104078. ** a doclist consists of one or more document records.
  104079. **
  104080. ** A bare doclist omits the position information, becoming an
  104081. ** array of varint-encoded docids.
  104082. **
  104083. **** Segment leaf nodes ****
  104084. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  104085. ** nodes are written using LeafWriter, and read using LeafReader (to
  104086. ** iterate through a single leaf node's data) and LeavesReader (to
  104087. ** iterate through a segment's entire leaf layer). Leaf nodes have
  104088. ** the format:
  104089. **
  104090. ** varint iHeight; (height from leaf level, always 0)
  104091. ** varint nTerm; (length of first term)
  104092. ** char pTerm[nTerm]; (content of first term)
  104093. ** varint nDoclist; (length of term's associated doclist)
  104094. ** char pDoclist[nDoclist]; (content of doclist)
  104095. ** array {
  104096. ** (further terms are delta-encoded)
  104097. ** varint nPrefix; (length of prefix shared with previous term)
  104098. ** varint nSuffix; (length of unshared suffix)
  104099. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  104100. ** varint nDoclist; (length of term's associated doclist)
  104101. ** char pDoclist[nDoclist]; (content of doclist)
  104102. ** }
  104103. **
  104104. ** Here, array { X } means zero or more occurrences of X, adjacent in
  104105. ** memory.
  104106. **
  104107. ** Leaf nodes are broken into blocks which are stored contiguously in
  104108. ** the %_segments table in sorted order. This means that when the end
  104109. ** of a node is reached, the next term is in the node with the next
  104110. ** greater node id.
  104111. **
  104112. ** New data is spilled to a new leaf node when the current node
  104113. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  104114. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  104115. ** node (a leaf node with a single term and doclist). The goal of
  104116. ** these settings is to pack together groups of small doclists while
  104117. ** making it efficient to directly access large doclists. The
  104118. ** assumption is that large doclists represent terms which are more
  104119. ** likely to be query targets.
  104120. **
  104121. ** TODO(shess) It may be useful for blocking decisions to be more
  104122. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  104123. ** node rather than splitting into 2k and .5k nodes. My intuition is
  104124. ** that this might extend through 2x or 4x the pagesize.
  104125. **
  104126. **
  104127. **** Segment interior nodes ****
  104128. ** Segment interior nodes store blockids for subtree nodes and terms
  104129. ** to describe what data is stored by the each subtree. Interior
  104130. ** nodes are written using InteriorWriter, and read using
  104131. ** InteriorReader. InteriorWriters are created as needed when
  104132. ** SegmentWriter creates new leaf nodes, or when an interior node
  104133. ** itself grows too big and must be split. The format of interior
  104134. ** nodes:
  104135. **
  104136. ** varint iHeight; (height from leaf level, always >0)
  104137. ** varint iBlockid; (block id of node's leftmost subtree)
  104138. ** optional {
  104139. ** varint nTerm; (length of first term)
  104140. ** char pTerm[nTerm]; (content of first term)
  104141. ** array {
  104142. ** (further terms are delta-encoded)
  104143. ** varint nPrefix; (length of shared prefix with previous term)
  104144. ** varint nSuffix; (length of unshared suffix)
  104145. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  104146. ** }
  104147. ** }
  104148. **
  104149. ** Here, optional { X } means an optional element, while array { X }
  104150. ** means zero or more occurrences of X, adjacent in memory.
  104151. **
  104152. ** An interior node encodes n terms separating n+1 subtrees. The
  104153. ** subtree blocks are contiguous, so only the first subtree's blockid
  104154. ** is encoded. The subtree at iBlockid will contain all terms less
  104155. ** than the first term encoded (or all terms if no term is encoded).
  104156. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  104157. ** than pTerm[i+1], the subtree for that term will be rooted at
  104158. ** iBlockid+i. Interior nodes only store enough term data to
  104159. ** distinguish adjacent children (if the rightmost term of the left
  104160. ** child is "something", and the leftmost term of the right child is
  104161. ** "wicked", only "w" is stored).
  104162. **
  104163. ** New data is spilled to a new interior node at the same height when
  104164. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  104165. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  104166. ** interior nodes and making the tree too skinny. The interior nodes
  104167. ** at a given height are naturally tracked by interior nodes at
  104168. ** height+1, and so on.
  104169. **
  104170. **
  104171. **** Segment directory ****
  104172. ** The segment directory in table %_segdir stores meta-information for
  104173. ** merging and deleting segments, and also the root node of the
  104174. ** segment's tree.
  104175. **
  104176. ** The root node is the top node of the segment's tree after encoding
  104177. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  104178. ** This could be either a leaf node or an interior node. If the top
  104179. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  104180. ** and a new root interior node is generated (which should always fit
  104181. ** within ROOT_MAX because it only needs space for 2 varints, the
  104182. ** height and the blockid of the previous root).
  104183. **
  104184. ** The meta-information in the segment directory is:
  104185. ** level - segment level (see below)
  104186. ** idx - index within level
  104187. ** - (level,idx uniquely identify a segment)
  104188. ** start_block - first leaf node
  104189. ** leaves_end_block - last leaf node
  104190. ** end_block - last block (including interior nodes)
  104191. ** root - contents of root node
  104192. **
  104193. ** If the root node is a leaf node, then start_block,
  104194. ** leaves_end_block, and end_block are all 0.
  104195. **
  104196. **
  104197. **** Segment merging ****
  104198. ** To amortize update costs, segments are grouped into levels and
  104199. ** merged in batches. Each increase in level represents exponentially
  104200. ** more documents.
  104201. **
  104202. ** New documents (actually, document updates) are tokenized and
  104203. ** written individually (using LeafWriter) to a level 0 segment, with
  104204. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  104205. ** level 0 segments are merged into a single level 1 segment. Level 1
  104206. ** is populated like level 0, and eventually MERGE_COUNT level 1
  104207. ** segments are merged to a single level 2 segment (representing
  104208. ** MERGE_COUNT^2 updates), and so on.
  104209. **
  104210. ** A segment merge traverses all segments at a given level in
  104211. ** parallel, performing a straightforward sorted merge. Since segment
  104212. ** leaf nodes are written in to the %_segments table in order, this
  104213. ** merge traverses the underlying sqlite disk structures efficiently.
  104214. ** After the merge, all segment blocks from the merged level are
  104215. ** deleted.
  104216. **
  104217. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  104218. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  104219. ** very similar performance numbers to 16 on insertion, though they're
  104220. ** a tiny bit slower (perhaps due to more overhead in merge-time
  104221. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  104222. ** 16, 2 about 66% slower than 16.
  104223. **
  104224. ** At query time, high MERGE_COUNT increases the number of segments
  104225. ** which need to be scanned and merged. For instance, with 100k docs
  104226. ** inserted:
  104227. **
  104228. ** MERGE_COUNT segments
  104229. ** 16 25
  104230. ** 8 12
  104231. ** 4 10
  104232. ** 2 6
  104233. **
  104234. ** This appears to have only a moderate impact on queries for very
  104235. ** frequent terms (which are somewhat dominated by segment merge
  104236. ** costs), and infrequent and non-existent terms still seem to be fast
  104237. ** even with many segments.
  104238. **
  104239. ** TODO(shess) That said, it would be nice to have a better query-side
  104240. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  104241. ** optimizations to things like doclist merging will swing the sweet
  104242. ** spot around.
  104243. **
  104244. **
  104245. **
  104246. **** Handling of deletions and updates ****
  104247. ** Since we're using a segmented structure, with no docid-oriented
  104248. ** index into the term index, we clearly cannot simply update the term
  104249. ** index when a document is deleted or updated. For deletions, we
  104250. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  104251. ** we simply write the new doclist. Segment merges overwrite older
  104252. ** data for a particular docid with newer data, so deletes or updates
  104253. ** will eventually overtake the earlier data and knock it out. The
  104254. ** query logic likewise merges doclists so that newer data knocks out
  104255. ** older data.
  104256. */
  104257. /************** Include fts3Int.h in the middle of fts3.c ********************/
  104258. /************** Begin file fts3Int.h *****************************************/
  104259. /*
  104260. ** 2009 Nov 12
  104261. **
  104262. ** The author disclaims copyright to this source code. In place of
  104263. ** a legal notice, here is a blessing:
  104264. **
  104265. ** May you do good and not evil.
  104266. ** May you find forgiveness for yourself and forgive others.
  104267. ** May you share freely, never taking more than you give.
  104268. **
  104269. ******************************************************************************
  104270. **
  104271. */
  104272. #ifndef _FTSINT_H
  104273. #define _FTSINT_H
  104274. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  104275. # define NDEBUG 1
  104276. #endif
  104277. /*
  104278. ** FTS4 is really an extension for FTS3. It is enabled using the
  104279. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  104280. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  104281. */
  104282. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  104283. # define SQLITE_ENABLE_FTS3
  104284. #endif
  104285. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  104286. /* If not building as part of the core, include sqlite3ext.h. */
  104287. #ifndef SQLITE_CORE
  104288. SQLITE_EXTENSION_INIT3
  104289. #endif
  104290. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  104291. /************** Begin file fts3_tokenizer.h **********************************/
  104292. /*
  104293. ** 2006 July 10
  104294. **
  104295. ** The author disclaims copyright to this source code.
  104296. **
  104297. *************************************************************************
  104298. ** Defines the interface to tokenizers used by fulltext-search. There
  104299. ** are three basic components:
  104300. **
  104301. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  104302. ** interface functions. This is essentially the class structure for
  104303. ** tokenizers.
  104304. **
  104305. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  104306. ** including customization information defined at creation time.
  104307. **
  104308. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  104309. ** tokens from a particular input.
  104310. */
  104311. #ifndef _FTS3_TOKENIZER_H_
  104312. #define _FTS3_TOKENIZER_H_
  104313. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  104314. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  104315. ** we will need a way to register the API consistently.
  104316. */
  104317. /*
  104318. ** Structures used by the tokenizer interface. When a new tokenizer
  104319. ** implementation is registered, the caller provides a pointer to
  104320. ** an sqlite3_tokenizer_module containing pointers to the callback
  104321. ** functions that make up an implementation.
  104322. **
  104323. ** When an fts3 table is created, it passes any arguments passed to
  104324. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  104325. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  104326. ** implementation. The xCreate() function in turn returns an
  104327. ** sqlite3_tokenizer structure representing the specific tokenizer to
  104328. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  104329. **
  104330. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  104331. ** method is called. It returns an sqlite3_tokenizer_cursor object
  104332. ** that may be used to tokenize a specific input buffer based on
  104333. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  104334. ** object.
  104335. */
  104336. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  104337. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  104338. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  104339. struct sqlite3_tokenizer_module {
  104340. /*
  104341. ** Structure version. Should always be set to 0 or 1.
  104342. */
  104343. int iVersion;
  104344. /*
  104345. ** Create a new tokenizer. The values in the argv[] array are the
  104346. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  104347. ** TABLE statement that created the fts3 table. For example, if
  104348. ** the following SQL is executed:
  104349. **
  104350. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  104351. **
  104352. ** then argc is set to 2, and the argv[] array contains pointers
  104353. ** to the strings "arg1" and "arg2".
  104354. **
  104355. ** This method should return either SQLITE_OK (0), or an SQLite error
  104356. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  104357. ** to point at the newly created tokenizer structure. The generic
  104358. ** sqlite3_tokenizer.pModule variable should not be initialized by
  104359. ** this callback. The caller will do so.
  104360. */
  104361. int (*xCreate)(
  104362. int argc, /* Size of argv array */
  104363. const char *const*argv, /* Tokenizer argument strings */
  104364. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  104365. );
  104366. /*
  104367. ** Destroy an existing tokenizer. The fts3 module calls this method
  104368. ** exactly once for each successful call to xCreate().
  104369. */
  104370. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  104371. /*
  104372. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  104373. ** is responsible for ensuring that the input buffer remains valid
  104374. ** until the cursor is closed (using the xClose() method).
  104375. */
  104376. int (*xOpen)(
  104377. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  104378. const char *pInput, int nBytes, /* Input buffer */
  104379. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  104380. );
  104381. /*
  104382. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  104383. ** method exactly once for each successful call to xOpen().
  104384. */
  104385. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  104386. /*
  104387. ** Retrieve the next token from the tokenizer cursor pCursor. This
  104388. ** method should either return SQLITE_OK and set the values of the
  104389. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  104390. ** the end of the buffer has been reached, or an SQLite error code.
  104391. **
  104392. ** *ppToken should be set to point at a buffer containing the
  104393. ** normalized version of the token (i.e. after any case-folding and/or
  104394. ** stemming has been performed). *pnBytes should be set to the length
  104395. ** of this buffer in bytes. The input text that generated the token is
  104396. ** identified by the byte offsets returned in *piStartOffset and
  104397. ** *piEndOffset. *piStartOffset should be set to the index of the first
  104398. ** byte of the token in the input buffer. *piEndOffset should be set
  104399. ** to the index of the first byte just past the end of the token in
  104400. ** the input buffer.
  104401. **
  104402. ** The buffer *ppToken is set to point at is managed by the tokenizer
  104403. ** implementation. It is only required to be valid until the next call
  104404. ** to xNext() or xClose().
  104405. */
  104406. /* TODO(shess) current implementation requires pInput to be
  104407. ** nul-terminated. This should either be fixed, or pInput/nBytes
  104408. ** should be converted to zInput.
  104409. */
  104410. int (*xNext)(
  104411. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  104412. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  104413. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  104414. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  104415. int *piPosition /* OUT: Number of tokens returned before this one */
  104416. );
  104417. /***********************************************************************
  104418. ** Methods below this point are only available if iVersion>=1.
  104419. */
  104420. /*
  104421. ** Configure the language id of a tokenizer cursor.
  104422. */
  104423. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  104424. };
  104425. struct sqlite3_tokenizer {
  104426. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  104427. /* Tokenizer implementations will typically add additional fields */
  104428. };
  104429. struct sqlite3_tokenizer_cursor {
  104430. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  104431. /* Tokenizer implementations will typically add additional fields */
  104432. };
  104433. int fts3_global_term_cnt(int iTerm, int iCol);
  104434. int fts3_term_cnt(int iTerm, int iCol);
  104435. #endif /* _FTS3_TOKENIZER_H_ */
  104436. /************** End of fts3_tokenizer.h **************************************/
  104437. /************** Continuing where we left off in fts3Int.h ********************/
  104438. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  104439. /************** Begin file fts3_hash.h ***************************************/
  104440. /*
  104441. ** 2001 September 22
  104442. **
  104443. ** The author disclaims copyright to this source code. In place of
  104444. ** a legal notice, here is a blessing:
  104445. **
  104446. ** May you do good and not evil.
  104447. ** May you find forgiveness for yourself and forgive others.
  104448. ** May you share freely, never taking more than you give.
  104449. **
  104450. *************************************************************************
  104451. ** This is the header file for the generic hash-table implementation
  104452. ** used in SQLite. We've modified it slightly to serve as a standalone
  104453. ** hash table implementation for the full-text indexing module.
  104454. **
  104455. */
  104456. #ifndef _FTS3_HASH_H_
  104457. #define _FTS3_HASH_H_
  104458. /* Forward declarations of structures. */
  104459. typedef struct Fts3Hash Fts3Hash;
  104460. typedef struct Fts3HashElem Fts3HashElem;
  104461. /* A complete hash table is an instance of the following structure.
  104462. ** The internals of this structure are intended to be opaque -- client
  104463. ** code should not attempt to access or modify the fields of this structure
  104464. ** directly. Change this structure only by using the routines below.
  104465. ** However, many of the "procedures" and "functions" for modifying and
  104466. ** accessing this structure are really macros, so we can't really make
  104467. ** this structure opaque.
  104468. */
  104469. struct Fts3Hash {
  104470. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  104471. char copyKey; /* True if copy of key made on insert */
  104472. int count; /* Number of entries in this table */
  104473. Fts3HashElem *first; /* The first element of the array */
  104474. int htsize; /* Number of buckets in the hash table */
  104475. struct _fts3ht { /* the hash table */
  104476. int count; /* Number of entries with this hash */
  104477. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  104478. } *ht;
  104479. };
  104480. /* Each element in the hash table is an instance of the following
  104481. ** structure. All elements are stored on a single doubly-linked list.
  104482. **
  104483. ** Again, this structure is intended to be opaque, but it can't really
  104484. ** be opaque because it is used by macros.
  104485. */
  104486. struct Fts3HashElem {
  104487. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  104488. void *data; /* Data associated with this element */
  104489. void *pKey; int nKey; /* Key associated with this element */
  104490. };
  104491. /*
  104492. ** There are 2 different modes of operation for a hash table:
  104493. **
  104494. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  104495. ** (including the null-terminator, if any). Case
  104496. ** is respected in comparisons.
  104497. **
  104498. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  104499. ** memcmp() is used to compare keys.
  104500. **
  104501. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  104502. */
  104503. #define FTS3_HASH_STRING 1
  104504. #define FTS3_HASH_BINARY 2
  104505. /*
  104506. ** Access routines. To delete, insert a NULL pointer.
  104507. */
  104508. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  104509. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  104510. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  104511. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  104512. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  104513. /*
  104514. ** Shorthand for the functions above
  104515. */
  104516. #define fts3HashInit sqlite3Fts3HashInit
  104517. #define fts3HashInsert sqlite3Fts3HashInsert
  104518. #define fts3HashFind sqlite3Fts3HashFind
  104519. #define fts3HashClear sqlite3Fts3HashClear
  104520. #define fts3HashFindElem sqlite3Fts3HashFindElem
  104521. /*
  104522. ** Macros for looping over all elements of a hash table. The idiom is
  104523. ** like this:
  104524. **
  104525. ** Fts3Hash h;
  104526. ** Fts3HashElem *p;
  104527. ** ...
  104528. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  104529. ** SomeStructure *pData = fts3HashData(p);
  104530. ** // do something with pData
  104531. ** }
  104532. */
  104533. #define fts3HashFirst(H) ((H)->first)
  104534. #define fts3HashNext(E) ((E)->next)
  104535. #define fts3HashData(E) ((E)->data)
  104536. #define fts3HashKey(E) ((E)->pKey)
  104537. #define fts3HashKeysize(E) ((E)->nKey)
  104538. /*
  104539. ** Number of entries in a hash table
  104540. */
  104541. #define fts3HashCount(H) ((H)->count)
  104542. #endif /* _FTS3_HASH_H_ */
  104543. /************** End of fts3_hash.h *******************************************/
  104544. /************** Continuing where we left off in fts3Int.h ********************/
  104545. /*
  104546. ** This constant determines the maximum depth of an FTS expression tree
  104547. ** that the library will create and use. FTS uses recursion to perform
  104548. ** various operations on the query tree, so the disadvantage of a large
  104549. ** limit is that it may allow very large queries to use large amounts
  104550. ** of stack space (perhaps causing a stack overflow).
  104551. */
  104552. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  104553. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  104554. #endif
  104555. /*
  104556. ** This constant controls how often segments are merged. Once there are
  104557. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  104558. ** segment of level N+1.
  104559. */
  104560. #define FTS3_MERGE_COUNT 16
  104561. /*
  104562. ** This is the maximum amount of data (in bytes) to store in the
  104563. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  104564. ** populated as documents are inserted/updated/deleted in a transaction
  104565. ** and used to create a new segment when the transaction is committed.
  104566. ** However if this limit is reached midway through a transaction, a new
  104567. ** segment is created and the hash table cleared immediately.
  104568. */
  104569. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  104570. /*
  104571. ** Macro to return the number of elements in an array. SQLite has a
  104572. ** similar macro called ArraySize(). Use a different name to avoid
  104573. ** a collision when building an amalgamation with built-in FTS3.
  104574. */
  104575. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  104576. #ifndef MIN
  104577. # define MIN(x,y) ((x)<(y)?(x):(y))
  104578. #endif
  104579. #ifndef MAX
  104580. # define MAX(x,y) ((x)>(y)?(x):(y))
  104581. #endif
  104582. /*
  104583. ** Maximum length of a varint encoded integer. The varint format is different
  104584. ** from that used by SQLite, so the maximum length is 10, not 9.
  104585. */
  104586. #define FTS3_VARINT_MAX 10
  104587. /*
  104588. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  104589. ** in the document set and zero or more prefix indexes. All indexes are stored
  104590. ** as one or more b+-trees in the %_segments and %_segdir tables.
  104591. **
  104592. ** It is possible to determine which index a b+-tree belongs to based on the
  104593. ** value stored in the "%_segdir.level" column. Given this value L, the index
  104594. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  104595. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  104596. ** between 1024 and 2047 to index 1, and so on.
  104597. **
  104598. ** It is considered impossible for an index to use more than 1024 levels. In
  104599. ** theory though this may happen, but only after at least
  104600. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  104601. */
  104602. #define FTS3_SEGDIR_MAXLEVEL 1024
  104603. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  104604. /*
  104605. ** The testcase() macro is only used by the amalgamation. If undefined,
  104606. ** make it a no-op.
  104607. */
  104608. #ifndef testcase
  104609. # define testcase(X)
  104610. #endif
  104611. /*
  104612. ** Terminator values for position-lists and column-lists.
  104613. */
  104614. #define POS_COLUMN (1) /* Column-list terminator */
  104615. #define POS_END (0) /* Position-list terminator */
  104616. /*
  104617. ** This section provides definitions to allow the
  104618. ** FTS3 extension to be compiled outside of the
  104619. ** amalgamation.
  104620. */
  104621. #ifndef SQLITE_AMALGAMATION
  104622. /*
  104623. ** Macros indicating that conditional expressions are always true or
  104624. ** false.
  104625. */
  104626. #ifdef SQLITE_COVERAGE_TEST
  104627. # define ALWAYS(x) (1)
  104628. # define NEVER(X) (0)
  104629. #else
  104630. # define ALWAYS(x) (x)
  104631. # define NEVER(x) (x)
  104632. #endif
  104633. /*
  104634. ** Internal types used by SQLite.
  104635. */
  104636. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  104637. typedef short int i16; /* 2-byte (or larger) signed integer */
  104638. typedef unsigned int u32; /* 4-byte unsigned integer */
  104639. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  104640. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  104641. /*
  104642. ** Macro used to suppress compiler warnings for unused parameters.
  104643. */
  104644. #define UNUSED_PARAMETER(x) (void)(x)
  104645. /*
  104646. ** Activate assert() only if SQLITE_TEST is enabled.
  104647. */
  104648. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  104649. # define NDEBUG 1
  104650. #endif
  104651. /*
  104652. ** The TESTONLY macro is used to enclose variable declarations or
  104653. ** other bits of code that are needed to support the arguments
  104654. ** within testcase() and assert() macros.
  104655. */
  104656. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  104657. # define TESTONLY(X) X
  104658. #else
  104659. # define TESTONLY(X)
  104660. #endif
  104661. #endif /* SQLITE_AMALGAMATION */
  104662. #ifdef SQLITE_DEBUG
  104663. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  104664. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  104665. #else
  104666. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  104667. #endif
  104668. typedef struct Fts3Table Fts3Table;
  104669. typedef struct Fts3Cursor Fts3Cursor;
  104670. typedef struct Fts3Expr Fts3Expr;
  104671. typedef struct Fts3Phrase Fts3Phrase;
  104672. typedef struct Fts3PhraseToken Fts3PhraseToken;
  104673. typedef struct Fts3Doclist Fts3Doclist;
  104674. typedef struct Fts3SegFilter Fts3SegFilter;
  104675. typedef struct Fts3DeferredToken Fts3DeferredToken;
  104676. typedef struct Fts3SegReader Fts3SegReader;
  104677. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  104678. /*
  104679. ** A connection to a fulltext index is an instance of the following
  104680. ** structure. The xCreate and xConnect methods create an instance
  104681. ** of this structure and xDestroy and xDisconnect free that instance.
  104682. ** All other methods receive a pointer to the structure as one of their
  104683. ** arguments.
  104684. */
  104685. struct Fts3Table {
  104686. sqlite3_vtab base; /* Base class used by SQLite core */
  104687. sqlite3 *db; /* The database connection */
  104688. const char *zDb; /* logical database name */
  104689. const char *zName; /* virtual table name */
  104690. int nColumn; /* number of named columns in virtual table */
  104691. char **azColumn; /* column names. malloced */
  104692. u8 *abNotindexed; /* True for 'notindexed' columns */
  104693. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  104694. char *zContentTbl; /* content=xxx option, or NULL */
  104695. char *zLanguageid; /* languageid=xxx option, or NULL */
  104696. u8 bAutoincrmerge; /* True if automerge=1 */
  104697. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  104698. /* Precompiled statements used by the implementation. Each of these
  104699. ** statements is run and reset within a single virtual table API call.
  104700. */
  104701. sqlite3_stmt *aStmt[37];
  104702. char *zReadExprlist;
  104703. char *zWriteExprlist;
  104704. int nNodeSize; /* Soft limit for node size */
  104705. u8 bFts4; /* True for FTS4, false for FTS3 */
  104706. u8 bHasStat; /* True if %_stat table exists */
  104707. u8 bHasDocsize; /* True if %_docsize table exists */
  104708. u8 bDescIdx; /* True if doclists are in reverse order */
  104709. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  104710. int nPgsz; /* Page size for host database */
  104711. char *zSegmentsTbl; /* Name of %_segments table */
  104712. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  104713. /*
  104714. ** The following array of hash tables is used to buffer pending index
  104715. ** updates during transactions. All pending updates buffered at any one
  104716. ** time must share a common language-id (see the FTS4 langid= feature).
  104717. ** The current language id is stored in variable iPrevLangid.
  104718. **
  104719. ** A single FTS4 table may have multiple full-text indexes. For each index
  104720. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  104721. ** terms that appear in the document set. Each subsequent index in aIndex[]
  104722. ** is an index of prefixes of a specific length.
  104723. **
  104724. ** Variable nPendingData contains an estimate the memory consumed by the
  104725. ** pending data structures, including hash table overhead, but not including
  104726. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  104727. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  104728. ** recently inserted record.
  104729. */
  104730. int nIndex; /* Size of aIndex[] */
  104731. struct Fts3Index {
  104732. int nPrefix; /* Prefix length (0 for main terms index) */
  104733. Fts3Hash hPending; /* Pending terms table for this index */
  104734. } *aIndex;
  104735. int nMaxPendingData; /* Max pending data before flush to disk */
  104736. int nPendingData; /* Current bytes of pending data */
  104737. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  104738. int iPrevLangid; /* Langid of recently inserted document */
  104739. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  104740. /* State variables used for validating that the transaction control
  104741. ** methods of the virtual table are called at appropriate times. These
  104742. ** values do not contribute to FTS functionality; they are used for
  104743. ** verifying the operation of the SQLite core.
  104744. */
  104745. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  104746. int mxSavepoint; /* Largest valid xSavepoint integer */
  104747. #endif
  104748. #ifdef SQLITE_TEST
  104749. /* True to disable the incremental doclist optimization. This is controled
  104750. ** by special insert command 'test-no-incr-doclist'. */
  104751. int bNoIncrDoclist;
  104752. #endif
  104753. };
  104754. /*
  104755. ** When the core wants to read from the virtual table, it creates a
  104756. ** virtual table cursor (an instance of the following structure) using
  104757. ** the xOpen method. Cursors are destroyed using the xClose method.
  104758. */
  104759. struct Fts3Cursor {
  104760. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  104761. i16 eSearch; /* Search strategy (see below) */
  104762. u8 isEof; /* True if at End Of Results */
  104763. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  104764. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  104765. Fts3Expr *pExpr; /* Parsed MATCH query string */
  104766. int iLangid; /* Language being queried for */
  104767. int nPhrase; /* Number of matchable phrases in query */
  104768. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  104769. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  104770. char *pNextId; /* Pointer into the body of aDoclist */
  104771. char *aDoclist; /* List of docids for full-text queries */
  104772. int nDoclist; /* Size of buffer at aDoclist */
  104773. u8 bDesc; /* True to sort in descending order */
  104774. int eEvalmode; /* An FTS3_EVAL_XX constant */
  104775. int nRowAvg; /* Average size of database rows, in pages */
  104776. sqlite3_int64 nDoc; /* Documents in table */
  104777. i64 iMinDocid; /* Minimum docid to return */
  104778. i64 iMaxDocid; /* Maximum docid to return */
  104779. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  104780. u32 *aMatchinfo; /* Information about most recent match */
  104781. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  104782. char *zMatchinfo; /* Matchinfo specification */
  104783. };
  104784. #define FTS3_EVAL_FILTER 0
  104785. #define FTS3_EVAL_NEXT 1
  104786. #define FTS3_EVAL_MATCHINFO 2
  104787. /*
  104788. ** The Fts3Cursor.eSearch member is always set to one of the following.
  104789. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  104790. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  104791. ** of the column to be searched. For example, in
  104792. **
  104793. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  104794. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  104795. **
  104796. ** Because the LHS of the MATCH operator is 2nd column "b",
  104797. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  104798. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  104799. ** indicating that all columns should be searched,
  104800. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  104801. */
  104802. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  104803. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  104804. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  104805. /*
  104806. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  104807. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  104808. ** above. The upper 16-bits contain a combination of the following
  104809. ** bits, used to describe extra constraints on full-text searches.
  104810. */
  104811. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  104812. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  104813. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  104814. struct Fts3Doclist {
  104815. char *aAll; /* Array containing doclist (or NULL) */
  104816. int nAll; /* Size of a[] in bytes */
  104817. char *pNextDocid; /* Pointer to next docid */
  104818. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  104819. int bFreeList; /* True if pList should be sqlite3_free()d */
  104820. char *pList; /* Pointer to position list following iDocid */
  104821. int nList; /* Length of position list */
  104822. };
  104823. /*
  104824. ** A "phrase" is a sequence of one or more tokens that must match in
  104825. ** sequence. A single token is the base case and the most common case.
  104826. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  104827. ** nToken will be the number of tokens in the string.
  104828. */
  104829. struct Fts3PhraseToken {
  104830. char *z; /* Text of the token */
  104831. int n; /* Number of bytes in buffer z */
  104832. int isPrefix; /* True if token ends with a "*" character */
  104833. int bFirst; /* True if token must appear at position 0 */
  104834. /* Variables above this point are populated when the expression is
  104835. ** parsed (by code in fts3_expr.c). Below this point the variables are
  104836. ** used when evaluating the expression. */
  104837. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  104838. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  104839. };
  104840. struct Fts3Phrase {
  104841. /* Cache of doclist for this phrase. */
  104842. Fts3Doclist doclist;
  104843. int bIncr; /* True if doclist is loaded incrementally */
  104844. int iDoclistToken;
  104845. /* Variables below this point are populated by fts3_expr.c when parsing
  104846. ** a MATCH expression. Everything above is part of the evaluation phase.
  104847. */
  104848. int nToken; /* Number of tokens in the phrase */
  104849. int iColumn; /* Index of column this phrase must match */
  104850. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  104851. };
  104852. /*
  104853. ** A tree of these objects forms the RHS of a MATCH operator.
  104854. **
  104855. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  104856. ** points to a malloced buffer, size nDoclist bytes, containing the results
  104857. ** of this phrase query in FTS3 doclist format. As usual, the initial
  104858. ** "Length" field found in doclists stored on disk is omitted from this
  104859. ** buffer.
  104860. **
  104861. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  104862. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  104863. ** where nCol is the number of columns in the queried FTS table. The array
  104864. ** is populated as follows:
  104865. **
  104866. ** aMI[iCol*3 + 0] = Undefined
  104867. ** aMI[iCol*3 + 1] = Number of occurrences
  104868. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  104869. **
  104870. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  104871. ** when the expression node is.
  104872. */
  104873. struct Fts3Expr {
  104874. int eType; /* One of the FTSQUERY_XXX values defined below */
  104875. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  104876. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  104877. Fts3Expr *pLeft; /* Left operand */
  104878. Fts3Expr *pRight; /* Right operand */
  104879. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  104880. /* The following are used by the fts3_eval.c module. */
  104881. sqlite3_int64 iDocid; /* Current docid */
  104882. u8 bEof; /* True this expression is at EOF already */
  104883. u8 bStart; /* True if iDocid is valid */
  104884. u8 bDeferred; /* True if this expression is entirely deferred */
  104885. u32 *aMI;
  104886. };
  104887. /*
  104888. ** Candidate values for Fts3Query.eType. Note that the order of the first
  104889. ** four values is in order of precedence when parsing expressions. For
  104890. ** example, the following:
  104891. **
  104892. ** "a OR b AND c NOT d NEAR e"
  104893. **
  104894. ** is equivalent to:
  104895. **
  104896. ** "a OR (b AND (c NOT (d NEAR e)))"
  104897. */
  104898. #define FTSQUERY_NEAR 1
  104899. #define FTSQUERY_NOT 2
  104900. #define FTSQUERY_AND 3
  104901. #define FTSQUERY_OR 4
  104902. #define FTSQUERY_PHRASE 5
  104903. /* fts3_write.c */
  104904. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  104905. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  104906. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  104907. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  104908. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  104909. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  104910. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  104911. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  104912. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  104913. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  104914. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  104915. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  104916. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  104917. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  104918. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  104919. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  104920. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  104921. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  104922. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  104923. #else
  104924. # define sqlite3Fts3FreeDeferredTokens(x)
  104925. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  104926. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  104927. # define sqlite3Fts3FreeDeferredDoclists(x)
  104928. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  104929. #endif
  104930. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  104931. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  104932. /* Special values interpreted by sqlite3SegReaderCursor() */
  104933. #define FTS3_SEGCURSOR_PENDING -1
  104934. #define FTS3_SEGCURSOR_ALL -2
  104935. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  104936. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  104937. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  104938. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  104939. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  104940. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  104941. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  104942. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  104943. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  104944. #define FTS3_SEGMENT_PREFIX 0x00000008
  104945. #define FTS3_SEGMENT_SCAN 0x00000010
  104946. #define FTS3_SEGMENT_FIRST 0x00000020
  104947. /* Type passed as 4th argument to SegmentReaderIterate() */
  104948. struct Fts3SegFilter {
  104949. const char *zTerm;
  104950. int nTerm;
  104951. int iCol;
  104952. int flags;
  104953. };
  104954. struct Fts3MultiSegReader {
  104955. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  104956. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  104957. int nSegment; /* Size of apSegment array */
  104958. int nAdvance; /* How many seg-readers to advance */
  104959. Fts3SegFilter *pFilter; /* Pointer to filter object */
  104960. char *aBuffer; /* Buffer to merge doclists in */
  104961. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  104962. int iColFilter; /* If >=0, filter for this column */
  104963. int bRestart;
  104964. /* Used by fts3.c only. */
  104965. int nCost; /* Cost of running iterator */
  104966. int bLookup; /* True if a lookup of a single entry. */
  104967. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  104968. char *zTerm; /* Pointer to term buffer */
  104969. int nTerm; /* Size of zTerm in bytes */
  104970. char *aDoclist; /* Pointer to doclist buffer */
  104971. int nDoclist; /* Size of aDoclist[] in bytes */
  104972. };
  104973. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  104974. /* fts3.c */
  104975. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  104976. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  104977. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  104978. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  104979. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  104980. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  104981. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  104982. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  104983. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  104984. /* fts3_tokenizer.c */
  104985. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  104986. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  104987. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  104988. sqlite3_tokenizer **, char **
  104989. );
  104990. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  104991. /* fts3_snippet.c */
  104992. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  104993. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  104994. const char *, const char *, int, int
  104995. );
  104996. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  104997. /* fts3_expr.c */
  104998. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  104999. char **, int, int, int, const char *, int, Fts3Expr **, char **
  105000. );
  105001. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  105002. #ifdef SQLITE_TEST
  105003. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  105004. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  105005. #endif
  105006. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  105007. sqlite3_tokenizer_cursor **
  105008. );
  105009. /* fts3_aux.c */
  105010. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  105011. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  105012. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  105013. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  105014. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  105015. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  105016. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  105017. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  105018. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  105019. /* fts3_tokenize_vtab.c */
  105020. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  105021. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  105022. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  105023. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  105024. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  105025. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  105026. #endif
  105027. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  105028. #endif /* _FTSINT_H */
  105029. /************** End of fts3Int.h *********************************************/
  105030. /************** Continuing where we left off in fts3.c ***********************/
  105031. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  105032. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  105033. # define SQLITE_CORE 1
  105034. #endif
  105035. /* #include <assert.h> */
  105036. /* #include <stdlib.h> */
  105037. /* #include <stddef.h> */
  105038. /* #include <stdio.h> */
  105039. /* #include <string.h> */
  105040. /* #include <stdarg.h> */
  105041. #ifndef SQLITE_CORE
  105042. SQLITE_EXTENSION_INIT1
  105043. #endif
  105044. static int fts3EvalNext(Fts3Cursor *pCsr);
  105045. static int fts3EvalStart(Fts3Cursor *pCsr);
  105046. static int fts3TermSegReaderCursor(
  105047. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  105048. /*
  105049. ** Write a 64-bit variable-length integer to memory starting at p[0].
  105050. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  105051. ** The number of bytes written is returned.
  105052. */
  105053. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  105054. unsigned char *q = (unsigned char *) p;
  105055. sqlite_uint64 vu = v;
  105056. do{
  105057. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  105058. vu >>= 7;
  105059. }while( vu!=0 );
  105060. q[-1] &= 0x7f; /* turn off high bit in final byte */
  105061. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  105062. return (int) (q - (unsigned char *)p);
  105063. }
  105064. /*
  105065. ** Read a 64-bit variable-length integer from memory starting at p[0].
  105066. ** Return the number of bytes read, or 0 on error.
  105067. ** The value is stored in *v.
  105068. */
  105069. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  105070. const unsigned char *q = (const unsigned char *) p;
  105071. sqlite_uint64 x = 0, y = 1;
  105072. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  105073. x += y * (*q++ & 0x7f);
  105074. y <<= 7;
  105075. }
  105076. x += y * (*q++);
  105077. *v = (sqlite_int64) x;
  105078. return (int) (q - (unsigned char *)p);
  105079. }
  105080. /*
  105081. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  105082. ** 32-bit integer before it is returned.
  105083. */
  105084. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  105085. sqlite_int64 i;
  105086. int ret = sqlite3Fts3GetVarint(p, &i);
  105087. *pi = (int) i;
  105088. return ret;
  105089. }
  105090. /*
  105091. ** Return the number of bytes required to encode v as a varint
  105092. */
  105093. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  105094. int i = 0;
  105095. do{
  105096. i++;
  105097. v >>= 7;
  105098. }while( v!=0 );
  105099. return i;
  105100. }
  105101. /*
  105102. ** Convert an SQL-style quoted string into a normal string by removing
  105103. ** the quote characters. The conversion is done in-place. If the
  105104. ** input does not begin with a quote character, then this routine
  105105. ** is a no-op.
  105106. **
  105107. ** Examples:
  105108. **
  105109. ** "abc" becomes abc
  105110. ** 'xyz' becomes xyz
  105111. ** [pqr] becomes pqr
  105112. ** `mno` becomes mno
  105113. **
  105114. */
  105115. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  105116. char quote; /* Quote character (if any ) */
  105117. quote = z[0];
  105118. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  105119. int iIn = 1; /* Index of next byte to read from input */
  105120. int iOut = 0; /* Index of next byte to write to output */
  105121. /* If the first byte was a '[', then the close-quote character is a ']' */
  105122. if( quote=='[' ) quote = ']';
  105123. while( ALWAYS(z[iIn]) ){
  105124. if( z[iIn]==quote ){
  105125. if( z[iIn+1]!=quote ) break;
  105126. z[iOut++] = quote;
  105127. iIn += 2;
  105128. }else{
  105129. z[iOut++] = z[iIn++];
  105130. }
  105131. }
  105132. z[iOut] = '\0';
  105133. }
  105134. }
  105135. /*
  105136. ** Read a single varint from the doclist at *pp and advance *pp to point
  105137. ** to the first byte past the end of the varint. Add the value of the varint
  105138. ** to *pVal.
  105139. */
  105140. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  105141. sqlite3_int64 iVal;
  105142. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  105143. *pVal += iVal;
  105144. }
  105145. /*
  105146. ** When this function is called, *pp points to the first byte following a
  105147. ** varint that is part of a doclist (or position-list, or any other list
  105148. ** of varints). This function moves *pp to point to the start of that varint,
  105149. ** and sets *pVal by the varint value.
  105150. **
  105151. ** Argument pStart points to the first byte of the doclist that the
  105152. ** varint is part of.
  105153. */
  105154. static void fts3GetReverseVarint(
  105155. char **pp,
  105156. char *pStart,
  105157. sqlite3_int64 *pVal
  105158. ){
  105159. sqlite3_int64 iVal;
  105160. char *p;
  105161. /* Pointer p now points at the first byte past the varint we are
  105162. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  105163. ** clear on character p[-1]. */
  105164. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  105165. p++;
  105166. *pp = p;
  105167. sqlite3Fts3GetVarint(p, &iVal);
  105168. *pVal = iVal;
  105169. }
  105170. /*
  105171. ** The xDisconnect() virtual table method.
  105172. */
  105173. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  105174. Fts3Table *p = (Fts3Table *)pVtab;
  105175. int i;
  105176. assert( p->nPendingData==0 );
  105177. assert( p->pSegments==0 );
  105178. /* Free any prepared statements held */
  105179. for(i=0; i<SizeofArray(p->aStmt); i++){
  105180. sqlite3_finalize(p->aStmt[i]);
  105181. }
  105182. sqlite3_free(p->zSegmentsTbl);
  105183. sqlite3_free(p->zReadExprlist);
  105184. sqlite3_free(p->zWriteExprlist);
  105185. sqlite3_free(p->zContentTbl);
  105186. sqlite3_free(p->zLanguageid);
  105187. /* Invoke the tokenizer destructor to free the tokenizer. */
  105188. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  105189. sqlite3_free(p);
  105190. return SQLITE_OK;
  105191. }
  105192. /*
  105193. ** Construct one or more SQL statements from the format string given
  105194. ** and then evaluate those statements. The success code is written
  105195. ** into *pRc.
  105196. **
  105197. ** If *pRc is initially non-zero then this routine is a no-op.
  105198. */
  105199. static void fts3DbExec(
  105200. int *pRc, /* Success code */
  105201. sqlite3 *db, /* Database in which to run SQL */
  105202. const char *zFormat, /* Format string for SQL */
  105203. ... /* Arguments to the format string */
  105204. ){
  105205. va_list ap;
  105206. char *zSql;
  105207. if( *pRc ) return;
  105208. va_start(ap, zFormat);
  105209. zSql = sqlite3_vmprintf(zFormat, ap);
  105210. va_end(ap);
  105211. if( zSql==0 ){
  105212. *pRc = SQLITE_NOMEM;
  105213. }else{
  105214. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  105215. sqlite3_free(zSql);
  105216. }
  105217. }
  105218. /*
  105219. ** The xDestroy() virtual table method.
  105220. */
  105221. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  105222. Fts3Table *p = (Fts3Table *)pVtab;
  105223. int rc = SQLITE_OK; /* Return code */
  105224. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  105225. sqlite3 *db = p->db; /* Database handle */
  105226. /* Drop the shadow tables */
  105227. if( p->zContentTbl==0 ){
  105228. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  105229. }
  105230. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  105231. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  105232. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  105233. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  105234. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  105235. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  105236. ** Otherwise, return an SQLite error code.
  105237. */
  105238. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  105239. }
  105240. /*
  105241. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  105242. ** passed as the first argument. This is done as part of the xConnect()
  105243. ** and xCreate() methods.
  105244. **
  105245. ** If *pRc is non-zero when this function is called, it is a no-op.
  105246. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  105247. ** before returning.
  105248. */
  105249. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  105250. if( *pRc==SQLITE_OK ){
  105251. int i; /* Iterator variable */
  105252. int rc; /* Return code */
  105253. char *zSql; /* SQL statement passed to declare_vtab() */
  105254. char *zCols; /* List of user defined columns */
  105255. const char *zLanguageid;
  105256. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  105257. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  105258. /* Create a list of user columns for the virtual table */
  105259. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  105260. for(i=1; zCols && i<p->nColumn; i++){
  105261. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  105262. }
  105263. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  105264. zSql = sqlite3_mprintf(
  105265. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  105266. zCols, p->zName, zLanguageid
  105267. );
  105268. if( !zCols || !zSql ){
  105269. rc = SQLITE_NOMEM;
  105270. }else{
  105271. rc = sqlite3_declare_vtab(p->db, zSql);
  105272. }
  105273. sqlite3_free(zSql);
  105274. sqlite3_free(zCols);
  105275. *pRc = rc;
  105276. }
  105277. }
  105278. /*
  105279. ** Create the %_stat table if it does not already exist.
  105280. */
  105281. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  105282. fts3DbExec(pRc, p->db,
  105283. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  105284. "(id INTEGER PRIMARY KEY, value BLOB);",
  105285. p->zDb, p->zName
  105286. );
  105287. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  105288. }
  105289. /*
  105290. ** Create the backing store tables (%_content, %_segments and %_segdir)
  105291. ** required by the FTS3 table passed as the only argument. This is done
  105292. ** as part of the vtab xCreate() method.
  105293. **
  105294. ** If the p->bHasDocsize boolean is true (indicating that this is an
  105295. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  105296. ** %_stat tables required by FTS4.
  105297. */
  105298. static int fts3CreateTables(Fts3Table *p){
  105299. int rc = SQLITE_OK; /* Return code */
  105300. int i; /* Iterator variable */
  105301. sqlite3 *db = p->db; /* The database connection */
  105302. if( p->zContentTbl==0 ){
  105303. const char *zLanguageid = p->zLanguageid;
  105304. char *zContentCols; /* Columns of %_content table */
  105305. /* Create a list of user columns for the content table */
  105306. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  105307. for(i=0; zContentCols && i<p->nColumn; i++){
  105308. char *z = p->azColumn[i];
  105309. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  105310. }
  105311. if( zLanguageid && zContentCols ){
  105312. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  105313. }
  105314. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  105315. /* Create the content table */
  105316. fts3DbExec(&rc, db,
  105317. "CREATE TABLE %Q.'%q_content'(%s)",
  105318. p->zDb, p->zName, zContentCols
  105319. );
  105320. sqlite3_free(zContentCols);
  105321. }
  105322. /* Create other tables */
  105323. fts3DbExec(&rc, db,
  105324. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  105325. p->zDb, p->zName
  105326. );
  105327. fts3DbExec(&rc, db,
  105328. "CREATE TABLE %Q.'%q_segdir'("
  105329. "level INTEGER,"
  105330. "idx INTEGER,"
  105331. "start_block INTEGER,"
  105332. "leaves_end_block INTEGER,"
  105333. "end_block INTEGER,"
  105334. "root BLOB,"
  105335. "PRIMARY KEY(level, idx)"
  105336. ");",
  105337. p->zDb, p->zName
  105338. );
  105339. if( p->bHasDocsize ){
  105340. fts3DbExec(&rc, db,
  105341. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  105342. p->zDb, p->zName
  105343. );
  105344. }
  105345. assert( p->bHasStat==p->bFts4 );
  105346. if( p->bHasStat ){
  105347. sqlite3Fts3CreateStatTable(&rc, p);
  105348. }
  105349. return rc;
  105350. }
  105351. /*
  105352. ** Store the current database page-size in bytes in p->nPgsz.
  105353. **
  105354. ** If *pRc is non-zero when this function is called, it is a no-op.
  105355. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  105356. ** before returning.
  105357. */
  105358. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  105359. if( *pRc==SQLITE_OK ){
  105360. int rc; /* Return code */
  105361. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  105362. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  105363. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  105364. if( !zSql ){
  105365. rc = SQLITE_NOMEM;
  105366. }else{
  105367. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  105368. if( rc==SQLITE_OK ){
  105369. sqlite3_step(pStmt);
  105370. p->nPgsz = sqlite3_column_int(pStmt, 0);
  105371. rc = sqlite3_finalize(pStmt);
  105372. }else if( rc==SQLITE_AUTH ){
  105373. p->nPgsz = 1024;
  105374. rc = SQLITE_OK;
  105375. }
  105376. }
  105377. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  105378. sqlite3_free(zSql);
  105379. *pRc = rc;
  105380. }
  105381. }
  105382. /*
  105383. ** "Special" FTS4 arguments are column specifications of the following form:
  105384. **
  105385. ** <key> = <value>
  105386. **
  105387. ** There may not be whitespace surrounding the "=" character. The <value>
  105388. ** term may be quoted, but the <key> may not.
  105389. */
  105390. static int fts3IsSpecialColumn(
  105391. const char *z,
  105392. int *pnKey,
  105393. char **pzValue
  105394. ){
  105395. char *zValue;
  105396. const char *zCsr = z;
  105397. while( *zCsr!='=' ){
  105398. if( *zCsr=='\0' ) return 0;
  105399. zCsr++;
  105400. }
  105401. *pnKey = (int)(zCsr-z);
  105402. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  105403. if( zValue ){
  105404. sqlite3Fts3Dequote(zValue);
  105405. }
  105406. *pzValue = zValue;
  105407. return 1;
  105408. }
  105409. /*
  105410. ** Append the output of a printf() style formatting to an existing string.
  105411. */
  105412. static void fts3Appendf(
  105413. int *pRc, /* IN/OUT: Error code */
  105414. char **pz, /* IN/OUT: Pointer to string buffer */
  105415. const char *zFormat, /* Printf format string to append */
  105416. ... /* Arguments for printf format string */
  105417. ){
  105418. if( *pRc==SQLITE_OK ){
  105419. va_list ap;
  105420. char *z;
  105421. va_start(ap, zFormat);
  105422. z = sqlite3_vmprintf(zFormat, ap);
  105423. va_end(ap);
  105424. if( z && *pz ){
  105425. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  105426. sqlite3_free(z);
  105427. z = z2;
  105428. }
  105429. if( z==0 ) *pRc = SQLITE_NOMEM;
  105430. sqlite3_free(*pz);
  105431. *pz = z;
  105432. }
  105433. }
  105434. /*
  105435. ** Return a copy of input string zInput enclosed in double-quotes (") and
  105436. ** with all double quote characters escaped. For example:
  105437. **
  105438. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  105439. **
  105440. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  105441. ** is the callers responsibility to call sqlite3_free() to release this
  105442. ** memory.
  105443. */
  105444. static char *fts3QuoteId(char const *zInput){
  105445. int nRet;
  105446. char *zRet;
  105447. nRet = 2 + (int)strlen(zInput)*2 + 1;
  105448. zRet = sqlite3_malloc(nRet);
  105449. if( zRet ){
  105450. int i;
  105451. char *z = zRet;
  105452. *(z++) = '"';
  105453. for(i=0; zInput[i]; i++){
  105454. if( zInput[i]=='"' ) *(z++) = '"';
  105455. *(z++) = zInput[i];
  105456. }
  105457. *(z++) = '"';
  105458. *(z++) = '\0';
  105459. }
  105460. return zRet;
  105461. }
  105462. /*
  105463. ** Return a list of comma separated SQL expressions and a FROM clause that
  105464. ** could be used in a SELECT statement such as the following:
  105465. **
  105466. ** SELECT <list of expressions> FROM %_content AS x ...
  105467. **
  105468. ** to return the docid, followed by each column of text data in order
  105469. ** from left to write. If parameter zFunc is not NULL, then instead of
  105470. ** being returned directly each column of text data is passed to an SQL
  105471. ** function named zFunc first. For example, if zFunc is "unzip" and the
  105472. ** table has the three user-defined columns "a", "b", and "c", the following
  105473. ** string is returned:
  105474. **
  105475. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  105476. **
  105477. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  105478. ** is the responsibility of the caller to eventually free it.
  105479. **
  105480. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  105481. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  105482. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  105483. ** no error occurs, *pRc is left unmodified.
  105484. */
  105485. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  105486. char *zRet = 0;
  105487. char *zFree = 0;
  105488. char *zFunction;
  105489. int i;
  105490. if( p->zContentTbl==0 ){
  105491. if( !zFunc ){
  105492. zFunction = "";
  105493. }else{
  105494. zFree = zFunction = fts3QuoteId(zFunc);
  105495. }
  105496. fts3Appendf(pRc, &zRet, "docid");
  105497. for(i=0; i<p->nColumn; i++){
  105498. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  105499. }
  105500. if( p->zLanguageid ){
  105501. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  105502. }
  105503. sqlite3_free(zFree);
  105504. }else{
  105505. fts3Appendf(pRc, &zRet, "rowid");
  105506. for(i=0; i<p->nColumn; i++){
  105507. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  105508. }
  105509. if( p->zLanguageid ){
  105510. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  105511. }
  105512. }
  105513. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  105514. p->zDb,
  105515. (p->zContentTbl ? p->zContentTbl : p->zName),
  105516. (p->zContentTbl ? "" : "_content")
  105517. );
  105518. return zRet;
  105519. }
  105520. /*
  105521. ** Return a list of N comma separated question marks, where N is the number
  105522. ** of columns in the %_content table (one for the docid plus one for each
  105523. ** user-defined text column).
  105524. **
  105525. ** If argument zFunc is not NULL, then all but the first question mark
  105526. ** is preceded by zFunc and an open bracket, and followed by a closed
  105527. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  105528. ** user-defined text columns, the following string is returned:
  105529. **
  105530. ** "?, zip(?), zip(?), zip(?)"
  105531. **
  105532. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  105533. ** is the responsibility of the caller to eventually free it.
  105534. **
  105535. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  105536. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  105537. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  105538. ** no error occurs, *pRc is left unmodified.
  105539. */
  105540. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  105541. char *zRet = 0;
  105542. char *zFree = 0;
  105543. char *zFunction;
  105544. int i;
  105545. if( !zFunc ){
  105546. zFunction = "";
  105547. }else{
  105548. zFree = zFunction = fts3QuoteId(zFunc);
  105549. }
  105550. fts3Appendf(pRc, &zRet, "?");
  105551. for(i=0; i<p->nColumn; i++){
  105552. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  105553. }
  105554. if( p->zLanguageid ){
  105555. fts3Appendf(pRc, &zRet, ", ?");
  105556. }
  105557. sqlite3_free(zFree);
  105558. return zRet;
  105559. }
  105560. /*
  105561. ** This function interprets the string at (*pp) as a non-negative integer
  105562. ** value. It reads the integer and sets *pnOut to the value read, then
  105563. ** sets *pp to point to the byte immediately following the last byte of
  105564. ** the integer value.
  105565. **
  105566. ** Only decimal digits ('0'..'9') may be part of an integer value.
  105567. **
  105568. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  105569. ** the output value undefined. Otherwise SQLITE_OK is returned.
  105570. **
  105571. ** This function is used when parsing the "prefix=" FTS4 parameter.
  105572. */
  105573. static int fts3GobbleInt(const char **pp, int *pnOut){
  105574. const char *p; /* Iterator pointer */
  105575. int nInt = 0; /* Output value */
  105576. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  105577. nInt = nInt * 10 + (p[0] - '0');
  105578. }
  105579. if( p==*pp ) return SQLITE_ERROR;
  105580. *pnOut = nInt;
  105581. *pp = p;
  105582. return SQLITE_OK;
  105583. }
  105584. /*
  105585. ** This function is called to allocate an array of Fts3Index structures
  105586. ** representing the indexes maintained by the current FTS table. FTS tables
  105587. ** always maintain the main "terms" index, but may also maintain one or
  105588. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  105589. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  105590. **
  105591. ** Argument zParam is passed the value of the "prefix=" option if one was
  105592. ** specified, or NULL otherwise.
  105593. **
  105594. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  105595. ** the allocated array. *pnIndex is set to the number of elements in the
  105596. ** array. If an error does occur, an SQLite error code is returned.
  105597. **
  105598. ** Regardless of whether or not an error is returned, it is the responsibility
  105599. ** of the caller to call sqlite3_free() on the output array to free it.
  105600. */
  105601. static int fts3PrefixParameter(
  105602. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  105603. int *pnIndex, /* OUT: size of *apIndex[] array */
  105604. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  105605. ){
  105606. struct Fts3Index *aIndex; /* Allocated array */
  105607. int nIndex = 1; /* Number of entries in array */
  105608. if( zParam && zParam[0] ){
  105609. const char *p;
  105610. nIndex++;
  105611. for(p=zParam; *p; p++){
  105612. if( *p==',' ) nIndex++;
  105613. }
  105614. }
  105615. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  105616. *apIndex = aIndex;
  105617. *pnIndex = nIndex;
  105618. if( !aIndex ){
  105619. return SQLITE_NOMEM;
  105620. }
  105621. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  105622. if( zParam ){
  105623. const char *p = zParam;
  105624. int i;
  105625. for(i=1; i<nIndex; i++){
  105626. int nPrefix;
  105627. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  105628. aIndex[i].nPrefix = nPrefix;
  105629. p++;
  105630. }
  105631. }
  105632. return SQLITE_OK;
  105633. }
  105634. /*
  105635. ** This function is called when initializing an FTS4 table that uses the
  105636. ** content=xxx option. It determines the number of and names of the columns
  105637. ** of the new FTS4 table.
  105638. **
  105639. ** The third argument passed to this function is the value passed to the
  105640. ** config=xxx option (i.e. "xxx"). This function queries the database for
  105641. ** a table of that name. If found, the output variables are populated
  105642. ** as follows:
  105643. **
  105644. ** *pnCol: Set to the number of columns table xxx has,
  105645. **
  105646. ** *pnStr: Set to the total amount of space required to store a copy
  105647. ** of each columns name, including the nul-terminator.
  105648. **
  105649. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  105650. ** the name of the corresponding column in table xxx. The array
  105651. ** and its contents are allocated using a single allocation. It
  105652. ** is the responsibility of the caller to free this allocation
  105653. ** by eventually passing the *pazCol value to sqlite3_free().
  105654. **
  105655. ** If the table cannot be found, an error code is returned and the output
  105656. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  105657. ** returned (and the output variables are undefined).
  105658. */
  105659. static int fts3ContentColumns(
  105660. sqlite3 *db, /* Database handle */
  105661. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  105662. const char *zTbl, /* Name of content table */
  105663. const char ***pazCol, /* OUT: Malloc'd array of column names */
  105664. int *pnCol, /* OUT: Size of array *pazCol */
  105665. int *pnStr /* OUT: Bytes of string content */
  105666. ){
  105667. int rc = SQLITE_OK; /* Return code */
  105668. char *zSql; /* "SELECT *" statement on zTbl */
  105669. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  105670. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  105671. if( !zSql ){
  105672. rc = SQLITE_NOMEM;
  105673. }else{
  105674. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  105675. }
  105676. sqlite3_free(zSql);
  105677. if( rc==SQLITE_OK ){
  105678. const char **azCol; /* Output array */
  105679. int nStr = 0; /* Size of all column names (incl. 0x00) */
  105680. int nCol; /* Number of table columns */
  105681. int i; /* Used to iterate through columns */
  105682. /* Loop through the returned columns. Set nStr to the number of bytes of
  105683. ** space required to store a copy of each column name, including the
  105684. ** nul-terminator byte. */
  105685. nCol = sqlite3_column_count(pStmt);
  105686. for(i=0; i<nCol; i++){
  105687. const char *zCol = sqlite3_column_name(pStmt, i);
  105688. nStr += (int)strlen(zCol) + 1;
  105689. }
  105690. /* Allocate and populate the array to return. */
  105691. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  105692. if( azCol==0 ){
  105693. rc = SQLITE_NOMEM;
  105694. }else{
  105695. char *p = (char *)&azCol[nCol];
  105696. for(i=0; i<nCol; i++){
  105697. const char *zCol = sqlite3_column_name(pStmt, i);
  105698. int n = (int)strlen(zCol)+1;
  105699. memcpy(p, zCol, n);
  105700. azCol[i] = p;
  105701. p += n;
  105702. }
  105703. }
  105704. sqlite3_finalize(pStmt);
  105705. /* Set the output variables. */
  105706. *pnCol = nCol;
  105707. *pnStr = nStr;
  105708. *pazCol = azCol;
  105709. }
  105710. return rc;
  105711. }
  105712. /*
  105713. ** This function is the implementation of both the xConnect and xCreate
  105714. ** methods of the FTS3 virtual table.
  105715. **
  105716. ** The argv[] array contains the following:
  105717. **
  105718. ** argv[0] -> module name ("fts3" or "fts4")
  105719. ** argv[1] -> database name
  105720. ** argv[2] -> table name
  105721. ** argv[...] -> "column name" and other module argument fields.
  105722. */
  105723. static int fts3InitVtab(
  105724. int isCreate, /* True for xCreate, false for xConnect */
  105725. sqlite3 *db, /* The SQLite database connection */
  105726. void *pAux, /* Hash table containing tokenizers */
  105727. int argc, /* Number of elements in argv array */
  105728. const char * const *argv, /* xCreate/xConnect argument array */
  105729. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  105730. char **pzErr /* Write any error message here */
  105731. ){
  105732. Fts3Hash *pHash = (Fts3Hash *)pAux;
  105733. Fts3Table *p = 0; /* Pointer to allocated vtab */
  105734. int rc = SQLITE_OK; /* Return code */
  105735. int i; /* Iterator variable */
  105736. int nByte; /* Size of allocation used for *p */
  105737. int iCol; /* Column index */
  105738. int nString = 0; /* Bytes required to hold all column names */
  105739. int nCol = 0; /* Number of columns in the FTS table */
  105740. char *zCsr; /* Space for holding column names */
  105741. int nDb; /* Bytes required to hold database name */
  105742. int nName; /* Bytes required to hold table name */
  105743. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  105744. const char **aCol; /* Array of column names */
  105745. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  105746. int nIndex; /* Size of aIndex[] array */
  105747. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  105748. /* The results of parsing supported FTS4 key=value options: */
  105749. int bNoDocsize = 0; /* True to omit %_docsize table */
  105750. int bDescIdx = 0; /* True to store descending indexes */
  105751. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  105752. char *zCompress = 0; /* compress=? parameter (or NULL) */
  105753. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  105754. char *zContent = 0; /* content=? parameter (or NULL) */
  105755. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  105756. char **azNotindexed = 0; /* The set of notindexed= columns */
  105757. int nNotindexed = 0; /* Size of azNotindexed[] array */
  105758. assert( strlen(argv[0])==4 );
  105759. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  105760. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  105761. );
  105762. nDb = (int)strlen(argv[1]) + 1;
  105763. nName = (int)strlen(argv[2]) + 1;
  105764. nByte = sizeof(const char *) * (argc-2);
  105765. aCol = (const char **)sqlite3_malloc(nByte);
  105766. if( aCol ){
  105767. memset((void*)aCol, 0, nByte);
  105768. azNotindexed = (char **)sqlite3_malloc(nByte);
  105769. }
  105770. if( azNotindexed ){
  105771. memset(azNotindexed, 0, nByte);
  105772. }
  105773. if( !aCol || !azNotindexed ){
  105774. rc = SQLITE_NOMEM;
  105775. goto fts3_init_out;
  105776. }
  105777. /* Loop through all of the arguments passed by the user to the FTS3/4
  105778. ** module (i.e. all the column names and special arguments). This loop
  105779. ** does the following:
  105780. **
  105781. ** + Figures out the number of columns the FTSX table will have, and
  105782. ** the number of bytes of space that must be allocated to store copies
  105783. ** of the column names.
  105784. **
  105785. ** + If there is a tokenizer specification included in the arguments,
  105786. ** initializes the tokenizer pTokenizer.
  105787. */
  105788. for(i=3; rc==SQLITE_OK && i<argc; i++){
  105789. char const *z = argv[i];
  105790. int nKey;
  105791. char *zVal;
  105792. /* Check if this is a tokenizer specification */
  105793. if( !pTokenizer
  105794. && strlen(z)>8
  105795. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  105796. && 0==sqlite3Fts3IsIdChar(z[8])
  105797. ){
  105798. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  105799. }
  105800. /* Check if it is an FTS4 special argument. */
  105801. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  105802. struct Fts4Option {
  105803. const char *zOpt;
  105804. int nOpt;
  105805. } aFts4Opt[] = {
  105806. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  105807. { "prefix", 6 }, /* 1 -> PREFIX */
  105808. { "compress", 8 }, /* 2 -> COMPRESS */
  105809. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  105810. { "order", 5 }, /* 4 -> ORDER */
  105811. { "content", 7 }, /* 5 -> CONTENT */
  105812. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  105813. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  105814. };
  105815. int iOpt;
  105816. if( !zVal ){
  105817. rc = SQLITE_NOMEM;
  105818. }else{
  105819. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  105820. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  105821. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  105822. break;
  105823. }
  105824. }
  105825. if( iOpt==SizeofArray(aFts4Opt) ){
  105826. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  105827. rc = SQLITE_ERROR;
  105828. }else{
  105829. switch( iOpt ){
  105830. case 0: /* MATCHINFO */
  105831. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  105832. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  105833. rc = SQLITE_ERROR;
  105834. }
  105835. bNoDocsize = 1;
  105836. break;
  105837. case 1: /* PREFIX */
  105838. sqlite3_free(zPrefix);
  105839. zPrefix = zVal;
  105840. zVal = 0;
  105841. break;
  105842. case 2: /* COMPRESS */
  105843. sqlite3_free(zCompress);
  105844. zCompress = zVal;
  105845. zVal = 0;
  105846. break;
  105847. case 3: /* UNCOMPRESS */
  105848. sqlite3_free(zUncompress);
  105849. zUncompress = zVal;
  105850. zVal = 0;
  105851. break;
  105852. case 4: /* ORDER */
  105853. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  105854. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  105855. ){
  105856. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  105857. rc = SQLITE_ERROR;
  105858. }
  105859. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  105860. break;
  105861. case 5: /* CONTENT */
  105862. sqlite3_free(zContent);
  105863. zContent = zVal;
  105864. zVal = 0;
  105865. break;
  105866. case 6: /* LANGUAGEID */
  105867. assert( iOpt==6 );
  105868. sqlite3_free(zLanguageid);
  105869. zLanguageid = zVal;
  105870. zVal = 0;
  105871. break;
  105872. case 7: /* NOTINDEXED */
  105873. azNotindexed[nNotindexed++] = zVal;
  105874. zVal = 0;
  105875. break;
  105876. }
  105877. }
  105878. sqlite3_free(zVal);
  105879. }
  105880. }
  105881. /* Otherwise, the argument is a column name. */
  105882. else {
  105883. nString += (int)(strlen(z) + 1);
  105884. aCol[nCol++] = z;
  105885. }
  105886. }
  105887. /* If a content=xxx option was specified, the following:
  105888. **
  105889. ** 1. Ignore any compress= and uncompress= options.
  105890. **
  105891. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  105892. ** TABLE statement, use all columns from the content table.
  105893. */
  105894. if( rc==SQLITE_OK && zContent ){
  105895. sqlite3_free(zCompress);
  105896. sqlite3_free(zUncompress);
  105897. zCompress = 0;
  105898. zUncompress = 0;
  105899. if( nCol==0 ){
  105900. sqlite3_free((void*)aCol);
  105901. aCol = 0;
  105902. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  105903. /* If a languageid= option was specified, remove the language id
  105904. ** column from the aCol[] array. */
  105905. if( rc==SQLITE_OK && zLanguageid ){
  105906. int j;
  105907. for(j=0; j<nCol; j++){
  105908. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  105909. int k;
  105910. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  105911. nCol--;
  105912. break;
  105913. }
  105914. }
  105915. }
  105916. }
  105917. }
  105918. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105919. if( nCol==0 ){
  105920. assert( nString==0 );
  105921. aCol[0] = "content";
  105922. nString = 8;
  105923. nCol = 1;
  105924. }
  105925. if( pTokenizer==0 ){
  105926. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  105927. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105928. }
  105929. assert( pTokenizer );
  105930. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  105931. if( rc==SQLITE_ERROR ){
  105932. assert( zPrefix );
  105933. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  105934. }
  105935. if( rc!=SQLITE_OK ) goto fts3_init_out;
  105936. /* Allocate and populate the Fts3Table structure. */
  105937. nByte = sizeof(Fts3Table) + /* Fts3Table */
  105938. nCol * sizeof(char *) + /* azColumn */
  105939. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  105940. nCol * sizeof(u8) + /* abNotindexed */
  105941. nName + /* zName */
  105942. nDb + /* zDb */
  105943. nString; /* Space for azColumn strings */
  105944. p = (Fts3Table*)sqlite3_malloc(nByte);
  105945. if( p==0 ){
  105946. rc = SQLITE_NOMEM;
  105947. goto fts3_init_out;
  105948. }
  105949. memset(p, 0, nByte);
  105950. p->db = db;
  105951. p->nColumn = nCol;
  105952. p->nPendingData = 0;
  105953. p->azColumn = (char **)&p[1];
  105954. p->pTokenizer = pTokenizer;
  105955. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  105956. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  105957. p->bHasStat = isFts4;
  105958. p->bFts4 = isFts4;
  105959. p->bDescIdx = bDescIdx;
  105960. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  105961. p->zContentTbl = zContent;
  105962. p->zLanguageid = zLanguageid;
  105963. zContent = 0;
  105964. zLanguageid = 0;
  105965. TESTONLY( p->inTransaction = -1 );
  105966. TESTONLY( p->mxSavepoint = -1 );
  105967. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  105968. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  105969. p->nIndex = nIndex;
  105970. for(i=0; i<nIndex; i++){
  105971. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  105972. }
  105973. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  105974. /* Fill in the zName and zDb fields of the vtab structure. */
  105975. zCsr = (char *)&p->abNotindexed[nCol];
  105976. p->zName = zCsr;
  105977. memcpy(zCsr, argv[2], nName);
  105978. zCsr += nName;
  105979. p->zDb = zCsr;
  105980. memcpy(zCsr, argv[1], nDb);
  105981. zCsr += nDb;
  105982. /* Fill in the azColumn array */
  105983. for(iCol=0; iCol<nCol; iCol++){
  105984. char *z;
  105985. int n = 0;
  105986. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  105987. memcpy(zCsr, z, n);
  105988. zCsr[n] = '\0';
  105989. sqlite3Fts3Dequote(zCsr);
  105990. p->azColumn[iCol] = zCsr;
  105991. zCsr += n+1;
  105992. assert( zCsr <= &((char *)p)[nByte] );
  105993. }
  105994. /* Fill in the abNotindexed array */
  105995. for(iCol=0; iCol<nCol; iCol++){
  105996. int n = (int)strlen(p->azColumn[iCol]);
  105997. for(i=0; i<nNotindexed; i++){
  105998. char *zNot = azNotindexed[i];
  105999. if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
  106000. p->abNotindexed[iCol] = 1;
  106001. sqlite3_free(zNot);
  106002. azNotindexed[i] = 0;
  106003. }
  106004. }
  106005. }
  106006. for(i=0; i<nNotindexed; i++){
  106007. if( azNotindexed[i] ){
  106008. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  106009. rc = SQLITE_ERROR;
  106010. }
  106011. }
  106012. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  106013. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  106014. rc = SQLITE_ERROR;
  106015. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  106016. }
  106017. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  106018. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  106019. if( rc!=SQLITE_OK ) goto fts3_init_out;
  106020. /* If this is an xCreate call, create the underlying tables in the
  106021. ** database. TODO: For xConnect(), it could verify that said tables exist.
  106022. */
  106023. if( isCreate ){
  106024. rc = fts3CreateTables(p);
  106025. }
  106026. /* Check to see if a legacy fts3 table has been "upgraded" by the
  106027. ** addition of a %_stat table so that it can use incremental merge.
  106028. */
  106029. if( !isFts4 && !isCreate ){
  106030. int rc2 = SQLITE_OK;
  106031. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  106032. p->zDb, p->zName);
  106033. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  106034. }
  106035. /* Figure out the page-size for the database. This is required in order to
  106036. ** estimate the cost of loading large doclists from the database. */
  106037. fts3DatabasePageSize(&rc, p);
  106038. p->nNodeSize = p->nPgsz-35;
  106039. /* Declare the table schema to SQLite. */
  106040. fts3DeclareVtab(&rc, p);
  106041. fts3_init_out:
  106042. sqlite3_free(zPrefix);
  106043. sqlite3_free(aIndex);
  106044. sqlite3_free(zCompress);
  106045. sqlite3_free(zUncompress);
  106046. sqlite3_free(zContent);
  106047. sqlite3_free(zLanguageid);
  106048. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  106049. sqlite3_free((void *)aCol);
  106050. sqlite3_free((void *)azNotindexed);
  106051. if( rc!=SQLITE_OK ){
  106052. if( p ){
  106053. fts3DisconnectMethod((sqlite3_vtab *)p);
  106054. }else if( pTokenizer ){
  106055. pTokenizer->pModule->xDestroy(pTokenizer);
  106056. }
  106057. }else{
  106058. assert( p->pSegments==0 );
  106059. *ppVTab = &p->base;
  106060. }
  106061. return rc;
  106062. }
  106063. /*
  106064. ** The xConnect() and xCreate() methods for the virtual table. All the
  106065. ** work is done in function fts3InitVtab().
  106066. */
  106067. static int fts3ConnectMethod(
  106068. sqlite3 *db, /* Database connection */
  106069. void *pAux, /* Pointer to tokenizer hash table */
  106070. int argc, /* Number of elements in argv array */
  106071. const char * const *argv, /* xCreate/xConnect argument array */
  106072. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  106073. char **pzErr /* OUT: sqlite3_malloc'd error message */
  106074. ){
  106075. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  106076. }
  106077. static int fts3CreateMethod(
  106078. sqlite3 *db, /* Database connection */
  106079. void *pAux, /* Pointer to tokenizer hash table */
  106080. int argc, /* Number of elements in argv array */
  106081. const char * const *argv, /* xCreate/xConnect argument array */
  106082. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  106083. char **pzErr /* OUT: sqlite3_malloc'd error message */
  106084. ){
  106085. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  106086. }
  106087. /*
  106088. ** Implementation of the xBestIndex method for FTS3 tables. There
  106089. ** are three possible strategies, in order of preference:
  106090. **
  106091. ** 1. Direct lookup by rowid or docid.
  106092. ** 2. Full-text search using a MATCH operator on a non-docid column.
  106093. ** 3. Linear scan of %_content table.
  106094. */
  106095. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  106096. Fts3Table *p = (Fts3Table *)pVTab;
  106097. int i; /* Iterator variable */
  106098. int iCons = -1; /* Index of constraint to use */
  106099. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  106100. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  106101. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  106102. int iIdx;
  106103. /* By default use a full table scan. This is an expensive option,
  106104. ** so search through the constraints to see if a more efficient
  106105. ** strategy is possible.
  106106. */
  106107. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  106108. pInfo->estimatedCost = 5000000;
  106109. for(i=0; i<pInfo->nConstraint; i++){
  106110. int bDocid; /* True if this constraint is on docid */
  106111. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  106112. if( pCons->usable==0 ) continue;
  106113. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  106114. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  106115. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  106116. pInfo->idxNum = FTS3_DOCID_SEARCH;
  106117. pInfo->estimatedCost = 1.0;
  106118. iCons = i;
  106119. }
  106120. /* A MATCH constraint. Use a full-text search.
  106121. **
  106122. ** If there is more than one MATCH constraint available, use the first
  106123. ** one encountered. If there is both a MATCH constraint and a direct
  106124. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  106125. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  106126. ** it would lead to an "unable to use function MATCH in the requested
  106127. ** context" error.
  106128. */
  106129. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  106130. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  106131. ){
  106132. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  106133. pInfo->estimatedCost = 2.0;
  106134. iCons = i;
  106135. }
  106136. /* Equality constraint on the langid column */
  106137. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  106138. && pCons->iColumn==p->nColumn + 2
  106139. ){
  106140. iLangidCons = i;
  106141. }
  106142. if( bDocid ){
  106143. switch( pCons->op ){
  106144. case SQLITE_INDEX_CONSTRAINT_GE:
  106145. case SQLITE_INDEX_CONSTRAINT_GT:
  106146. iDocidGe = i;
  106147. break;
  106148. case SQLITE_INDEX_CONSTRAINT_LE:
  106149. case SQLITE_INDEX_CONSTRAINT_LT:
  106150. iDocidLe = i;
  106151. break;
  106152. }
  106153. }
  106154. }
  106155. iIdx = 1;
  106156. if( iCons>=0 ){
  106157. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  106158. pInfo->aConstraintUsage[iCons].omit = 1;
  106159. }
  106160. if( iLangidCons>=0 ){
  106161. pInfo->idxNum |= FTS3_HAVE_LANGID;
  106162. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  106163. }
  106164. if( iDocidGe>=0 ){
  106165. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  106166. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  106167. }
  106168. if( iDocidLe>=0 ){
  106169. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  106170. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  106171. }
  106172. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  106173. ** docid) order. Both ascending and descending are possible.
  106174. */
  106175. if( pInfo->nOrderBy==1 ){
  106176. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  106177. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  106178. if( pOrder->desc ){
  106179. pInfo->idxStr = "DESC";
  106180. }else{
  106181. pInfo->idxStr = "ASC";
  106182. }
  106183. pInfo->orderByConsumed = 1;
  106184. }
  106185. }
  106186. assert( p->pSegments==0 );
  106187. return SQLITE_OK;
  106188. }
  106189. /*
  106190. ** Implementation of xOpen method.
  106191. */
  106192. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  106193. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  106194. UNUSED_PARAMETER(pVTab);
  106195. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  106196. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  106197. ** if the allocation fails, return SQLITE_NOMEM.
  106198. */
  106199. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  106200. if( !pCsr ){
  106201. return SQLITE_NOMEM;
  106202. }
  106203. memset(pCsr, 0, sizeof(Fts3Cursor));
  106204. return SQLITE_OK;
  106205. }
  106206. /*
  106207. ** Close the cursor. For additional information see the documentation
  106208. ** on the xClose method of the virtual table interface.
  106209. */
  106210. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  106211. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  106212. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  106213. sqlite3_finalize(pCsr->pStmt);
  106214. sqlite3Fts3ExprFree(pCsr->pExpr);
  106215. sqlite3Fts3FreeDeferredTokens(pCsr);
  106216. sqlite3_free(pCsr->aDoclist);
  106217. sqlite3_free(pCsr->aMatchinfo);
  106218. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  106219. sqlite3_free(pCsr);
  106220. return SQLITE_OK;
  106221. }
  106222. /*
  106223. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  106224. ** compose and prepare an SQL statement of the form:
  106225. **
  106226. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  106227. **
  106228. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  106229. ** it. If an error occurs, return an SQLite error code.
  106230. **
  106231. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  106232. */
  106233. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  106234. int rc = SQLITE_OK;
  106235. if( pCsr->pStmt==0 ){
  106236. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  106237. char *zSql;
  106238. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  106239. if( !zSql ) return SQLITE_NOMEM;
  106240. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  106241. sqlite3_free(zSql);
  106242. }
  106243. *ppStmt = pCsr->pStmt;
  106244. return rc;
  106245. }
  106246. /*
  106247. ** Position the pCsr->pStmt statement so that it is on the row
  106248. ** of the %_content table that contains the last match. Return
  106249. ** SQLITE_OK on success.
  106250. */
  106251. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  106252. int rc = SQLITE_OK;
  106253. if( pCsr->isRequireSeek ){
  106254. sqlite3_stmt *pStmt = 0;
  106255. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  106256. if( rc==SQLITE_OK ){
  106257. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  106258. pCsr->isRequireSeek = 0;
  106259. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  106260. return SQLITE_OK;
  106261. }else{
  106262. rc = sqlite3_reset(pCsr->pStmt);
  106263. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  106264. /* If no row was found and no error has occurred, then the %_content
  106265. ** table is missing a row that is present in the full-text index.
  106266. ** The data structures are corrupt. */
  106267. rc = FTS_CORRUPT_VTAB;
  106268. pCsr->isEof = 1;
  106269. }
  106270. }
  106271. }
  106272. }
  106273. if( rc!=SQLITE_OK && pContext ){
  106274. sqlite3_result_error_code(pContext, rc);
  106275. }
  106276. return rc;
  106277. }
  106278. /*
  106279. ** This function is used to process a single interior node when searching
  106280. ** a b-tree for a term or term prefix. The node data is passed to this
  106281. ** function via the zNode/nNode parameters. The term to search for is
  106282. ** passed in zTerm/nTerm.
  106283. **
  106284. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  106285. ** of the child node that heads the sub-tree that may contain the term.
  106286. **
  106287. ** If piLast is not NULL, then *piLast is set to the right-most child node
  106288. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  106289. ** a prefix.
  106290. **
  106291. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  106292. */
  106293. static int fts3ScanInteriorNode(
  106294. const char *zTerm, /* Term to select leaves for */
  106295. int nTerm, /* Size of term zTerm in bytes */
  106296. const char *zNode, /* Buffer containing segment interior node */
  106297. int nNode, /* Size of buffer at zNode */
  106298. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  106299. sqlite3_int64 *piLast /* OUT: Selected child node */
  106300. ){
  106301. int rc = SQLITE_OK; /* Return code */
  106302. const char *zCsr = zNode; /* Cursor to iterate through node */
  106303. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  106304. char *zBuffer = 0; /* Buffer to load terms into */
  106305. int nAlloc = 0; /* Size of allocated buffer */
  106306. int isFirstTerm = 1; /* True when processing first term on page */
  106307. sqlite3_int64 iChild; /* Block id of child node to descend to */
  106308. /* Skip over the 'height' varint that occurs at the start of every
  106309. ** interior node. Then load the blockid of the left-child of the b-tree
  106310. ** node into variable iChild.
  106311. **
  106312. ** Even if the data structure on disk is corrupted, this (reading two
  106313. ** varints from the buffer) does not risk an overread. If zNode is a
  106314. ** root node, then the buffer comes from a SELECT statement. SQLite does
  106315. ** not make this guarantee explicitly, but in practice there are always
  106316. ** either more than 20 bytes of allocated space following the nNode bytes of
  106317. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  106318. ** table, then there are always 20 bytes of zeroed padding following the
  106319. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  106320. */
  106321. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  106322. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  106323. if( zCsr>zEnd ){
  106324. return FTS_CORRUPT_VTAB;
  106325. }
  106326. while( zCsr<zEnd && (piFirst || piLast) ){
  106327. int cmp; /* memcmp() result */
  106328. int nSuffix; /* Size of term suffix */
  106329. int nPrefix = 0; /* Size of term prefix */
  106330. int nBuffer; /* Total term size */
  106331. /* Load the next term on the node into zBuffer. Use realloc() to expand
  106332. ** the size of zBuffer if required. */
  106333. if( !isFirstTerm ){
  106334. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  106335. }
  106336. isFirstTerm = 0;
  106337. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  106338. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  106339. rc = FTS_CORRUPT_VTAB;
  106340. goto finish_scan;
  106341. }
  106342. if( nPrefix+nSuffix>nAlloc ){
  106343. char *zNew;
  106344. nAlloc = (nPrefix+nSuffix) * 2;
  106345. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  106346. if( !zNew ){
  106347. rc = SQLITE_NOMEM;
  106348. goto finish_scan;
  106349. }
  106350. zBuffer = zNew;
  106351. }
  106352. assert( zBuffer );
  106353. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  106354. nBuffer = nPrefix + nSuffix;
  106355. zCsr += nSuffix;
  106356. /* Compare the term we are searching for with the term just loaded from
  106357. ** the interior node. If the specified term is greater than or equal
  106358. ** to the term from the interior node, then all terms on the sub-tree
  106359. ** headed by node iChild are smaller than zTerm. No need to search
  106360. ** iChild.
  106361. **
  106362. ** If the interior node term is larger than the specified term, then
  106363. ** the tree headed by iChild may contain the specified term.
  106364. */
  106365. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  106366. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  106367. *piFirst = iChild;
  106368. piFirst = 0;
  106369. }
  106370. if( piLast && cmp<0 ){
  106371. *piLast = iChild;
  106372. piLast = 0;
  106373. }
  106374. iChild++;
  106375. };
  106376. if( piFirst ) *piFirst = iChild;
  106377. if( piLast ) *piLast = iChild;
  106378. finish_scan:
  106379. sqlite3_free(zBuffer);
  106380. return rc;
  106381. }
  106382. /*
  106383. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  106384. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  106385. ** contains a term. This function searches the sub-tree headed by the zNode
  106386. ** node for the range of leaf nodes that may contain the specified term
  106387. ** or terms for which the specified term is a prefix.
  106388. **
  106389. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  106390. ** left-most leaf node in the tree that may contain the specified term.
  106391. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  106392. ** right-most leaf node that may contain a term for which the specified
  106393. ** term is a prefix.
  106394. **
  106395. ** It is possible that the range of returned leaf nodes does not contain
  106396. ** the specified term or any terms for which it is a prefix. However, if the
  106397. ** segment does contain any such terms, they are stored within the identified
  106398. ** range. Because this function only inspects interior segment nodes (and
  106399. ** never loads leaf nodes into memory), it is not possible to be sure.
  106400. **
  106401. ** If an error occurs, an error code other than SQLITE_OK is returned.
  106402. */
  106403. static int fts3SelectLeaf(
  106404. Fts3Table *p, /* Virtual table handle */
  106405. const char *zTerm, /* Term to select leaves for */
  106406. int nTerm, /* Size of term zTerm in bytes */
  106407. const char *zNode, /* Buffer containing segment interior node */
  106408. int nNode, /* Size of buffer at zNode */
  106409. sqlite3_int64 *piLeaf, /* Selected leaf node */
  106410. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  106411. ){
  106412. int rc; /* Return code */
  106413. int iHeight; /* Height of this node in tree */
  106414. assert( piLeaf || piLeaf2 );
  106415. sqlite3Fts3GetVarint32(zNode, &iHeight);
  106416. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  106417. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  106418. if( rc==SQLITE_OK && iHeight>1 ){
  106419. char *zBlob = 0; /* Blob read from %_segments table */
  106420. int nBlob; /* Size of zBlob in bytes */
  106421. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  106422. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  106423. if( rc==SQLITE_OK ){
  106424. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  106425. }
  106426. sqlite3_free(zBlob);
  106427. piLeaf = 0;
  106428. zBlob = 0;
  106429. }
  106430. if( rc==SQLITE_OK ){
  106431. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  106432. }
  106433. if( rc==SQLITE_OK ){
  106434. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  106435. }
  106436. sqlite3_free(zBlob);
  106437. }
  106438. return rc;
  106439. }
  106440. /*
  106441. ** This function is used to create delta-encoded serialized lists of FTS3
  106442. ** varints. Each call to this function appends a single varint to a list.
  106443. */
  106444. static void fts3PutDeltaVarint(
  106445. char **pp, /* IN/OUT: Output pointer */
  106446. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  106447. sqlite3_int64 iVal /* Write this value to the list */
  106448. ){
  106449. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  106450. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  106451. *piPrev = iVal;
  106452. }
  106453. /*
  106454. ** When this function is called, *ppPoslist is assumed to point to the
  106455. ** start of a position-list. After it returns, *ppPoslist points to the
  106456. ** first byte after the position-list.
  106457. **
  106458. ** A position list is list of positions (delta encoded) and columns for
  106459. ** a single document record of a doclist. So, in other words, this
  106460. ** routine advances *ppPoslist so that it points to the next docid in
  106461. ** the doclist, or to the first byte past the end of the doclist.
  106462. **
  106463. ** If pp is not NULL, then the contents of the position list are copied
  106464. ** to *pp. *pp is set to point to the first byte past the last byte copied
  106465. ** before this function returns.
  106466. */
  106467. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  106468. char *pEnd = *ppPoslist;
  106469. char c = 0;
  106470. /* The end of a position list is marked by a zero encoded as an FTS3
  106471. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  106472. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  106473. ** of some other, multi-byte, value.
  106474. **
  106475. ** The following while-loop moves pEnd to point to the first byte that is not
  106476. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  106477. ** pEnd once more so that it points to the byte immediately following the
  106478. ** last byte in the position-list.
  106479. */
  106480. while( *pEnd | c ){
  106481. c = *pEnd++ & 0x80;
  106482. testcase( c!=0 && (*pEnd)==0 );
  106483. }
  106484. pEnd++; /* Advance past the POS_END terminator byte */
  106485. if( pp ){
  106486. int n = (int)(pEnd - *ppPoslist);
  106487. char *p = *pp;
  106488. memcpy(p, *ppPoslist, n);
  106489. p += n;
  106490. *pp = p;
  106491. }
  106492. *ppPoslist = pEnd;
  106493. }
  106494. /*
  106495. ** When this function is called, *ppPoslist is assumed to point to the
  106496. ** start of a column-list. After it returns, *ppPoslist points to the
  106497. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  106498. **
  106499. ** A column-list is list of delta-encoded positions for a single column
  106500. ** within a single document within a doclist.
  106501. **
  106502. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  106503. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  106504. ** the POS_COLUMN or POS_END that terminates the column-list.
  106505. **
  106506. ** If pp is not NULL, then the contents of the column-list are copied
  106507. ** to *pp. *pp is set to point to the first byte past the last byte copied
  106508. ** before this function returns. The POS_COLUMN or POS_END terminator
  106509. ** is not copied into *pp.
  106510. */
  106511. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  106512. char *pEnd = *ppPoslist;
  106513. char c = 0;
  106514. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  106515. ** not part of a multi-byte varint.
  106516. */
  106517. while( 0xFE & (*pEnd | c) ){
  106518. c = *pEnd++ & 0x80;
  106519. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  106520. }
  106521. if( pp ){
  106522. int n = (int)(pEnd - *ppPoslist);
  106523. char *p = *pp;
  106524. memcpy(p, *ppPoslist, n);
  106525. p += n;
  106526. *pp = p;
  106527. }
  106528. *ppPoslist = pEnd;
  106529. }
  106530. /*
  106531. ** Value used to signify the end of an position-list. This is safe because
  106532. ** it is not possible to have a document with 2^31 terms.
  106533. */
  106534. #define POSITION_LIST_END 0x7fffffff
  106535. /*
  106536. ** This function is used to help parse position-lists. When this function is
  106537. ** called, *pp may point to the start of the next varint in the position-list
  106538. ** being parsed, or it may point to 1 byte past the end of the position-list
  106539. ** (in which case **pp will be a terminator bytes POS_END (0) or
  106540. ** (1)).
  106541. **
  106542. ** If *pp points past the end of the current position-list, set *pi to
  106543. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  106544. ** increment the current value of *pi by the value read, and set *pp to
  106545. ** point to the next value before returning.
  106546. **
  106547. ** Before calling this routine *pi must be initialized to the value of
  106548. ** the previous position, or zero if we are reading the first position
  106549. ** in the position-list. Because positions are delta-encoded, the value
  106550. ** of the previous position is needed in order to compute the value of
  106551. ** the next position.
  106552. */
  106553. static void fts3ReadNextPos(
  106554. char **pp, /* IN/OUT: Pointer into position-list buffer */
  106555. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  106556. ){
  106557. if( (**pp)&0xFE ){
  106558. fts3GetDeltaVarint(pp, pi);
  106559. *pi -= 2;
  106560. }else{
  106561. *pi = POSITION_LIST_END;
  106562. }
  106563. }
  106564. /*
  106565. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  106566. ** the value of iCol encoded as a varint to *pp. This will start a new
  106567. ** column list.
  106568. **
  106569. ** Set *pp to point to the byte just after the last byte written before
  106570. ** returning (do not modify it if iCol==0). Return the total number of bytes
  106571. ** written (0 if iCol==0).
  106572. */
  106573. static int fts3PutColNumber(char **pp, int iCol){
  106574. int n = 0; /* Number of bytes written */
  106575. if( iCol ){
  106576. char *p = *pp; /* Output pointer */
  106577. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  106578. *p = 0x01;
  106579. *pp = &p[n];
  106580. }
  106581. return n;
  106582. }
  106583. /*
  106584. ** Compute the union of two position lists. The output written
  106585. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  106586. ** order and with any duplicates removed. All pointers are
  106587. ** updated appropriately. The caller is responsible for insuring
  106588. ** that there is enough space in *pp to hold the complete output.
  106589. */
  106590. static void fts3PoslistMerge(
  106591. char **pp, /* Output buffer */
  106592. char **pp1, /* Left input list */
  106593. char **pp2 /* Right input list */
  106594. ){
  106595. char *p = *pp;
  106596. char *p1 = *pp1;
  106597. char *p2 = *pp2;
  106598. while( *p1 || *p2 ){
  106599. int iCol1; /* The current column index in pp1 */
  106600. int iCol2; /* The current column index in pp2 */
  106601. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  106602. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  106603. else iCol1 = 0;
  106604. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  106605. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  106606. else iCol2 = 0;
  106607. if( iCol1==iCol2 ){
  106608. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  106609. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  106610. sqlite3_int64 iPrev = 0;
  106611. int n = fts3PutColNumber(&p, iCol1);
  106612. p1 += n;
  106613. p2 += n;
  106614. /* At this point, both p1 and p2 point to the start of column-lists
  106615. ** for the same column (the column with index iCol1 and iCol2).
  106616. ** A column-list is a list of non-negative delta-encoded varints, each
  106617. ** incremented by 2 before being stored. Each list is terminated by a
  106618. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  106619. ** and writes the results to buffer p. p is left pointing to the byte
  106620. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  106621. ** written to the output.
  106622. */
  106623. fts3GetDeltaVarint(&p1, &i1);
  106624. fts3GetDeltaVarint(&p2, &i2);
  106625. do {
  106626. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  106627. iPrev -= 2;
  106628. if( i1==i2 ){
  106629. fts3ReadNextPos(&p1, &i1);
  106630. fts3ReadNextPos(&p2, &i2);
  106631. }else if( i1<i2 ){
  106632. fts3ReadNextPos(&p1, &i1);
  106633. }else{
  106634. fts3ReadNextPos(&p2, &i2);
  106635. }
  106636. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  106637. }else if( iCol1<iCol2 ){
  106638. p1 += fts3PutColNumber(&p, iCol1);
  106639. fts3ColumnlistCopy(&p, &p1);
  106640. }else{
  106641. p2 += fts3PutColNumber(&p, iCol2);
  106642. fts3ColumnlistCopy(&p, &p2);
  106643. }
  106644. }
  106645. *p++ = POS_END;
  106646. *pp = p;
  106647. *pp1 = p1 + 1;
  106648. *pp2 = p2 + 1;
  106649. }
  106650. /*
  106651. ** This function is used to merge two position lists into one. When it is
  106652. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  106653. ** the part of a doclist that follows each document id. For example, if a row
  106654. ** contains:
  106655. **
  106656. ** 'a b c'|'x y z'|'a b b a'
  106657. **
  106658. ** Then the position list for this row for token 'b' would consist of:
  106659. **
  106660. ** 0x02 0x01 0x02 0x03 0x03 0x00
  106661. **
  106662. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  106663. ** byte following the 0x00 terminator of their respective position lists.
  106664. **
  106665. ** If isSaveLeft is 0, an entry is added to the output position list for
  106666. ** each position in *pp2 for which there exists one or more positions in
  106667. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  106668. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  106669. ** slots before it.
  106670. **
  106671. ** e.g. nToken==1 searches for adjacent positions.
  106672. */
  106673. static int fts3PoslistPhraseMerge(
  106674. char **pp, /* IN/OUT: Preallocated output buffer */
  106675. int nToken, /* Maximum difference in token positions */
  106676. int isSaveLeft, /* Save the left position */
  106677. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  106678. char **pp1, /* IN/OUT: Left input list */
  106679. char **pp2 /* IN/OUT: Right input list */
  106680. ){
  106681. char *p = *pp;
  106682. char *p1 = *pp1;
  106683. char *p2 = *pp2;
  106684. int iCol1 = 0;
  106685. int iCol2 = 0;
  106686. /* Never set both isSaveLeft and isExact for the same invocation. */
  106687. assert( isSaveLeft==0 || isExact==0 );
  106688. assert( p!=0 && *p1!=0 && *p2!=0 );
  106689. if( *p1==POS_COLUMN ){
  106690. p1++;
  106691. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106692. }
  106693. if( *p2==POS_COLUMN ){
  106694. p2++;
  106695. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106696. }
  106697. while( 1 ){
  106698. if( iCol1==iCol2 ){
  106699. char *pSave = p;
  106700. sqlite3_int64 iPrev = 0;
  106701. sqlite3_int64 iPos1 = 0;
  106702. sqlite3_int64 iPos2 = 0;
  106703. if( iCol1 ){
  106704. *p++ = POS_COLUMN;
  106705. p += sqlite3Fts3PutVarint(p, iCol1);
  106706. }
  106707. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  106708. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  106709. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  106710. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  106711. while( 1 ){
  106712. if( iPos2==iPos1+nToken
  106713. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  106714. ){
  106715. sqlite3_int64 iSave;
  106716. iSave = isSaveLeft ? iPos1 : iPos2;
  106717. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  106718. pSave = 0;
  106719. assert( p );
  106720. }
  106721. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  106722. if( (*p2&0xFE)==0 ) break;
  106723. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  106724. }else{
  106725. if( (*p1&0xFE)==0 ) break;
  106726. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  106727. }
  106728. }
  106729. if( pSave ){
  106730. assert( pp && p );
  106731. p = pSave;
  106732. }
  106733. fts3ColumnlistCopy(0, &p1);
  106734. fts3ColumnlistCopy(0, &p2);
  106735. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  106736. if( 0==*p1 || 0==*p2 ) break;
  106737. p1++;
  106738. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106739. p2++;
  106740. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106741. }
  106742. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  106743. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  106744. ** end of the position list, or the 0x01 that precedes the next
  106745. ** column-number in the position list.
  106746. */
  106747. else if( iCol1<iCol2 ){
  106748. fts3ColumnlistCopy(0, &p1);
  106749. if( 0==*p1 ) break;
  106750. p1++;
  106751. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  106752. }else{
  106753. fts3ColumnlistCopy(0, &p2);
  106754. if( 0==*p2 ) break;
  106755. p2++;
  106756. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  106757. }
  106758. }
  106759. fts3PoslistCopy(0, &p2);
  106760. fts3PoslistCopy(0, &p1);
  106761. *pp1 = p1;
  106762. *pp2 = p2;
  106763. if( *pp==p ){
  106764. return 0;
  106765. }
  106766. *p++ = 0x00;
  106767. *pp = p;
  106768. return 1;
  106769. }
  106770. /*
  106771. ** Merge two position-lists as required by the NEAR operator. The argument
  106772. ** position lists correspond to the left and right phrases of an expression
  106773. ** like:
  106774. **
  106775. ** "phrase 1" NEAR "phrase number 2"
  106776. **
  106777. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  106778. ** expression and *pp2 to the right. As usual, the indexes in the position
  106779. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  106780. ** in the example above).
  106781. **
  106782. ** The output position list - written to *pp - is a copy of *pp2 with those
  106783. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  106784. */
  106785. static int fts3PoslistNearMerge(
  106786. char **pp, /* Output buffer */
  106787. char *aTmp, /* Temporary buffer space */
  106788. int nRight, /* Maximum difference in token positions */
  106789. int nLeft, /* Maximum difference in token positions */
  106790. char **pp1, /* IN/OUT: Left input list */
  106791. char **pp2 /* IN/OUT: Right input list */
  106792. ){
  106793. char *p1 = *pp1;
  106794. char *p2 = *pp2;
  106795. char *pTmp1 = aTmp;
  106796. char *pTmp2;
  106797. char *aTmp2;
  106798. int res = 1;
  106799. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  106800. aTmp2 = pTmp2 = pTmp1;
  106801. *pp1 = p1;
  106802. *pp2 = p2;
  106803. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  106804. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  106805. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  106806. }else if( pTmp1!=aTmp ){
  106807. fts3PoslistCopy(pp, &aTmp);
  106808. }else if( pTmp2!=aTmp2 ){
  106809. fts3PoslistCopy(pp, &aTmp2);
  106810. }else{
  106811. res = 0;
  106812. }
  106813. return res;
  106814. }
  106815. /*
  106816. ** An instance of this function is used to merge together the (potentially
  106817. ** large number of) doclists for each term that matches a prefix query.
  106818. ** See function fts3TermSelectMerge() for details.
  106819. */
  106820. typedef struct TermSelect TermSelect;
  106821. struct TermSelect {
  106822. char *aaOutput[16]; /* Malloc'd output buffers */
  106823. int anOutput[16]; /* Size each output buffer in bytes */
  106824. };
  106825. /*
  106826. ** This function is used to read a single varint from a buffer. Parameter
  106827. ** pEnd points 1 byte past the end of the buffer. When this function is
  106828. ** called, if *pp points to pEnd or greater, then the end of the buffer
  106829. ** has been reached. In this case *pp is set to 0 and the function returns.
  106830. **
  106831. ** If *pp does not point to or past pEnd, then a single varint is read
  106832. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  106833. **
  106834. ** If bDescIdx is false, the value read is added to *pVal before returning.
  106835. ** If it is true, the value read is subtracted from *pVal before this
  106836. ** function returns.
  106837. */
  106838. static void fts3GetDeltaVarint3(
  106839. char **pp, /* IN/OUT: Point to read varint from */
  106840. char *pEnd, /* End of buffer */
  106841. int bDescIdx, /* True if docids are descending */
  106842. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  106843. ){
  106844. if( *pp>=pEnd ){
  106845. *pp = 0;
  106846. }else{
  106847. sqlite3_int64 iVal;
  106848. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  106849. if( bDescIdx ){
  106850. *pVal -= iVal;
  106851. }else{
  106852. *pVal += iVal;
  106853. }
  106854. }
  106855. }
  106856. /*
  106857. ** This function is used to write a single varint to a buffer. The varint
  106858. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  106859. ** end of the value written.
  106860. **
  106861. ** If *pbFirst is zero when this function is called, the value written to
  106862. ** the buffer is that of parameter iVal.
  106863. **
  106864. ** If *pbFirst is non-zero when this function is called, then the value
  106865. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  106866. ** (if bDescIdx is non-zero).
  106867. **
  106868. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  106869. ** to the value of parameter iVal.
  106870. */
  106871. static void fts3PutDeltaVarint3(
  106872. char **pp, /* IN/OUT: Output pointer */
  106873. int bDescIdx, /* True for descending docids */
  106874. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  106875. int *pbFirst, /* IN/OUT: True after first int written */
  106876. sqlite3_int64 iVal /* Write this value to the list */
  106877. ){
  106878. sqlite3_int64 iWrite;
  106879. if( bDescIdx==0 || *pbFirst==0 ){
  106880. iWrite = iVal - *piPrev;
  106881. }else{
  106882. iWrite = *piPrev - iVal;
  106883. }
  106884. assert( *pbFirst || *piPrev==0 );
  106885. assert( *pbFirst==0 || iWrite>0 );
  106886. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  106887. *piPrev = iVal;
  106888. *pbFirst = 1;
  106889. }
  106890. /*
  106891. ** This macro is used by various functions that merge doclists. The two
  106892. ** arguments are 64-bit docid values. If the value of the stack variable
  106893. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  106894. ** Otherwise, (i2-i1).
  106895. **
  106896. ** Using this makes it easier to write code that can merge doclists that are
  106897. ** sorted in either ascending or descending order.
  106898. */
  106899. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  106900. /*
  106901. ** This function does an "OR" merge of two doclists (output contains all
  106902. ** positions contained in either argument doclist). If the docids in the
  106903. ** input doclists are sorted in ascending order, parameter bDescDoclist
  106904. ** should be false. If they are sorted in ascending order, it should be
  106905. ** passed a non-zero value.
  106906. **
  106907. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  106908. ** containing the output doclist and SQLITE_OK is returned. In this case
  106909. ** *pnOut is set to the number of bytes in the output doclist.
  106910. **
  106911. ** If an error occurs, an SQLite error code is returned. The output values
  106912. ** are undefined in this case.
  106913. */
  106914. static int fts3DoclistOrMerge(
  106915. int bDescDoclist, /* True if arguments are desc */
  106916. char *a1, int n1, /* First doclist */
  106917. char *a2, int n2, /* Second doclist */
  106918. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  106919. ){
  106920. sqlite3_int64 i1 = 0;
  106921. sqlite3_int64 i2 = 0;
  106922. sqlite3_int64 iPrev = 0;
  106923. char *pEnd1 = &a1[n1];
  106924. char *pEnd2 = &a2[n2];
  106925. char *p1 = a1;
  106926. char *p2 = a2;
  106927. char *p;
  106928. char *aOut;
  106929. int bFirstOut = 0;
  106930. *paOut = 0;
  106931. *pnOut = 0;
  106932. /* Allocate space for the output. Both the input and output doclists
  106933. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  106934. ** then the first docid in each list is simply encoded as a varint. For
  106935. ** each subsequent docid, the varint stored is the difference between the
  106936. ** current and previous docid (a positive number - since the list is in
  106937. ** ascending order).
  106938. **
  106939. ** The first docid written to the output is therefore encoded using the
  106940. ** same number of bytes as it is in whichever of the input lists it is
  106941. ** read from. And each subsequent docid read from the same input list
  106942. ** consumes either the same or less bytes as it did in the input (since
  106943. ** the difference between it and the previous value in the output must
  106944. ** be a positive value less than or equal to the delta value read from
  106945. ** the input list). The same argument applies to all but the first docid
  106946. ** read from the 'other' list. And to the contents of all position lists
  106947. ** that will be copied and merged from the input to the output.
  106948. **
  106949. ** However, if the first docid copied to the output is a negative number,
  106950. ** then the encoding of the first docid from the 'other' input list may
  106951. ** be larger in the output than it was in the input (since the delta value
  106952. ** may be a larger positive integer than the actual docid).
  106953. **
  106954. ** The space required to store the output is therefore the sum of the
  106955. ** sizes of the two inputs, plus enough space for exactly one of the input
  106956. ** docids to grow.
  106957. **
  106958. ** A symetric argument may be made if the doclists are in descending
  106959. ** order.
  106960. */
  106961. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  106962. if( !aOut ) return SQLITE_NOMEM;
  106963. p = aOut;
  106964. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  106965. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  106966. while( p1 || p2 ){
  106967. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  106968. if( p2 && p1 && iDiff==0 ){
  106969. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  106970. fts3PoslistMerge(&p, &p1, &p2);
  106971. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  106972. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  106973. }else if( !p2 || (p1 && iDiff<0) ){
  106974. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  106975. fts3PoslistCopy(&p, &p1);
  106976. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  106977. }else{
  106978. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  106979. fts3PoslistCopy(&p, &p2);
  106980. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  106981. }
  106982. }
  106983. *paOut = aOut;
  106984. *pnOut = (int)(p-aOut);
  106985. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  106986. return SQLITE_OK;
  106987. }
  106988. /*
  106989. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  106990. ** the output contains a copy of each position from the right-hand input
  106991. ** doclist for which there is a position in the left-hand input doclist
  106992. ** exactly nDist tokens before it.
  106993. **
  106994. ** If the docids in the input doclists are sorted in ascending order,
  106995. ** parameter bDescDoclist should be false. If they are sorted in ascending
  106996. ** order, it should be passed a non-zero value.
  106997. **
  106998. ** The right-hand input doclist is overwritten by this function.
  106999. */
  107000. static void fts3DoclistPhraseMerge(
  107001. int bDescDoclist, /* True if arguments are desc */
  107002. int nDist, /* Distance from left to right (1=adjacent) */
  107003. char *aLeft, int nLeft, /* Left doclist */
  107004. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  107005. ){
  107006. sqlite3_int64 i1 = 0;
  107007. sqlite3_int64 i2 = 0;
  107008. sqlite3_int64 iPrev = 0;
  107009. char *pEnd1 = &aLeft[nLeft];
  107010. char *pEnd2 = &aRight[*pnRight];
  107011. char *p1 = aLeft;
  107012. char *p2 = aRight;
  107013. char *p;
  107014. int bFirstOut = 0;
  107015. char *aOut = aRight;
  107016. assert( nDist>0 );
  107017. p = aOut;
  107018. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  107019. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  107020. while( p1 && p2 ){
  107021. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  107022. if( iDiff==0 ){
  107023. char *pSave = p;
  107024. sqlite3_int64 iPrevSave = iPrev;
  107025. int bFirstOutSave = bFirstOut;
  107026. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  107027. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  107028. p = pSave;
  107029. iPrev = iPrevSave;
  107030. bFirstOut = bFirstOutSave;
  107031. }
  107032. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  107033. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  107034. }else if( iDiff<0 ){
  107035. fts3PoslistCopy(0, &p1);
  107036. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  107037. }else{
  107038. fts3PoslistCopy(0, &p2);
  107039. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  107040. }
  107041. }
  107042. *pnRight = (int)(p - aOut);
  107043. }
  107044. /*
  107045. ** Argument pList points to a position list nList bytes in size. This
  107046. ** function checks to see if the position list contains any entries for
  107047. ** a token in position 0 (of any column). If so, it writes argument iDelta
  107048. ** to the output buffer pOut, followed by a position list consisting only
  107049. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  107050. ** The value returned is the number of bytes written to pOut (if any).
  107051. */
  107052. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  107053. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  107054. char *pList, /* Position list (no 0x00 term) */
  107055. int nList, /* Size of pList in bytes */
  107056. char *pOut /* Write output here */
  107057. ){
  107058. int nOut = 0;
  107059. int bWritten = 0; /* True once iDelta has been written */
  107060. char *p = pList;
  107061. char *pEnd = &pList[nList];
  107062. if( *p!=0x01 ){
  107063. if( *p==0x02 ){
  107064. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  107065. pOut[nOut++] = 0x02;
  107066. bWritten = 1;
  107067. }
  107068. fts3ColumnlistCopy(0, &p);
  107069. }
  107070. while( p<pEnd && *p==0x01 ){
  107071. sqlite3_int64 iCol;
  107072. p++;
  107073. p += sqlite3Fts3GetVarint(p, &iCol);
  107074. if( *p==0x02 ){
  107075. if( bWritten==0 ){
  107076. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  107077. bWritten = 1;
  107078. }
  107079. pOut[nOut++] = 0x01;
  107080. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  107081. pOut[nOut++] = 0x02;
  107082. }
  107083. fts3ColumnlistCopy(0, &p);
  107084. }
  107085. if( bWritten ){
  107086. pOut[nOut++] = 0x00;
  107087. }
  107088. return nOut;
  107089. }
  107090. /*
  107091. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  107092. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  107093. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  107094. **
  107095. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  107096. ** the responsibility of the caller to free any doclists left in the
  107097. ** TermSelect.aaOutput[] array.
  107098. */
  107099. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  107100. char *aOut = 0;
  107101. int nOut = 0;
  107102. int i;
  107103. /* Loop through the doclists in the aaOutput[] array. Merge them all
  107104. ** into a single doclist.
  107105. */
  107106. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  107107. if( pTS->aaOutput[i] ){
  107108. if( !aOut ){
  107109. aOut = pTS->aaOutput[i];
  107110. nOut = pTS->anOutput[i];
  107111. pTS->aaOutput[i] = 0;
  107112. }else{
  107113. int nNew;
  107114. char *aNew;
  107115. int rc = fts3DoclistOrMerge(p->bDescIdx,
  107116. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  107117. );
  107118. if( rc!=SQLITE_OK ){
  107119. sqlite3_free(aOut);
  107120. return rc;
  107121. }
  107122. sqlite3_free(pTS->aaOutput[i]);
  107123. sqlite3_free(aOut);
  107124. pTS->aaOutput[i] = 0;
  107125. aOut = aNew;
  107126. nOut = nNew;
  107127. }
  107128. }
  107129. }
  107130. pTS->aaOutput[0] = aOut;
  107131. pTS->anOutput[0] = nOut;
  107132. return SQLITE_OK;
  107133. }
  107134. /*
  107135. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  107136. ** as the first argument. The merge is an "OR" merge (see function
  107137. ** fts3DoclistOrMerge() for details).
  107138. **
  107139. ** This function is called with the doclist for each term that matches
  107140. ** a queried prefix. It merges all these doclists into one, the doclist
  107141. ** for the specified prefix. Since there can be a very large number of
  107142. ** doclists to merge, the merging is done pair-wise using the TermSelect
  107143. ** object.
  107144. **
  107145. ** This function returns SQLITE_OK if the merge is successful, or an
  107146. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  107147. */
  107148. static int fts3TermSelectMerge(
  107149. Fts3Table *p, /* FTS table handle */
  107150. TermSelect *pTS, /* TermSelect object to merge into */
  107151. char *aDoclist, /* Pointer to doclist */
  107152. int nDoclist /* Size of aDoclist in bytes */
  107153. ){
  107154. if( pTS->aaOutput[0]==0 ){
  107155. /* If this is the first term selected, copy the doclist to the output
  107156. ** buffer using memcpy(). */
  107157. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  107158. pTS->anOutput[0] = nDoclist;
  107159. if( pTS->aaOutput[0] ){
  107160. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  107161. }else{
  107162. return SQLITE_NOMEM;
  107163. }
  107164. }else{
  107165. char *aMerge = aDoclist;
  107166. int nMerge = nDoclist;
  107167. int iOut;
  107168. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  107169. if( pTS->aaOutput[iOut]==0 ){
  107170. assert( iOut>0 );
  107171. pTS->aaOutput[iOut] = aMerge;
  107172. pTS->anOutput[iOut] = nMerge;
  107173. break;
  107174. }else{
  107175. char *aNew;
  107176. int nNew;
  107177. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  107178. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  107179. );
  107180. if( rc!=SQLITE_OK ){
  107181. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  107182. return rc;
  107183. }
  107184. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  107185. sqlite3_free(pTS->aaOutput[iOut]);
  107186. pTS->aaOutput[iOut] = 0;
  107187. aMerge = aNew;
  107188. nMerge = nNew;
  107189. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  107190. pTS->aaOutput[iOut] = aMerge;
  107191. pTS->anOutput[iOut] = nMerge;
  107192. }
  107193. }
  107194. }
  107195. }
  107196. return SQLITE_OK;
  107197. }
  107198. /*
  107199. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  107200. */
  107201. static int fts3SegReaderCursorAppend(
  107202. Fts3MultiSegReader *pCsr,
  107203. Fts3SegReader *pNew
  107204. ){
  107205. if( (pCsr->nSegment%16)==0 ){
  107206. Fts3SegReader **apNew;
  107207. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  107208. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  107209. if( !apNew ){
  107210. sqlite3Fts3SegReaderFree(pNew);
  107211. return SQLITE_NOMEM;
  107212. }
  107213. pCsr->apSegment = apNew;
  107214. }
  107215. pCsr->apSegment[pCsr->nSegment++] = pNew;
  107216. return SQLITE_OK;
  107217. }
  107218. /*
  107219. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  107220. ** 8th argument.
  107221. **
  107222. ** This function returns SQLITE_OK if successful, or an SQLite error code
  107223. ** otherwise.
  107224. */
  107225. static int fts3SegReaderCursor(
  107226. Fts3Table *p, /* FTS3 table handle */
  107227. int iLangid, /* Language id */
  107228. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  107229. int iLevel, /* Level of segments to scan */
  107230. const char *zTerm, /* Term to query for */
  107231. int nTerm, /* Size of zTerm in bytes */
  107232. int isPrefix, /* True for a prefix search */
  107233. int isScan, /* True to scan from zTerm to EOF */
  107234. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  107235. ){
  107236. int rc = SQLITE_OK; /* Error code */
  107237. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  107238. int rc2; /* Result of sqlite3_reset() */
  107239. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  107240. ** for the pending-terms. If this is a scan, then this call must be being
  107241. ** made by an fts4aux module, not an FTS table. In this case calling
  107242. ** Fts3SegReaderPending might segfault, as the data structures used by
  107243. ** fts4aux are not completely populated. So it's easiest to filter these
  107244. ** calls out here. */
  107245. if( iLevel<0 && p->aIndex ){
  107246. Fts3SegReader *pSeg = 0;
  107247. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  107248. if( rc==SQLITE_OK && pSeg ){
  107249. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  107250. }
  107251. }
  107252. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  107253. if( rc==SQLITE_OK ){
  107254. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  107255. }
  107256. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  107257. Fts3SegReader *pSeg = 0;
  107258. /* Read the values returned by the SELECT into local variables. */
  107259. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  107260. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  107261. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  107262. int nRoot = sqlite3_column_bytes(pStmt, 4);
  107263. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  107264. /* If zTerm is not NULL, and this segment is not stored entirely on its
  107265. ** root node, the range of leaves scanned can be reduced. Do this. */
  107266. if( iStartBlock && zTerm ){
  107267. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  107268. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  107269. if( rc!=SQLITE_OK ) goto finished;
  107270. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  107271. }
  107272. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  107273. (isPrefix==0 && isScan==0),
  107274. iStartBlock, iLeavesEndBlock,
  107275. iEndBlock, zRoot, nRoot, &pSeg
  107276. );
  107277. if( rc!=SQLITE_OK ) goto finished;
  107278. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  107279. }
  107280. }
  107281. finished:
  107282. rc2 = sqlite3_reset(pStmt);
  107283. if( rc==SQLITE_DONE ) rc = rc2;
  107284. return rc;
  107285. }
  107286. /*
  107287. ** Set up a cursor object for iterating through a full-text index or a
  107288. ** single level therein.
  107289. */
  107290. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  107291. Fts3Table *p, /* FTS3 table handle */
  107292. int iLangid, /* Language-id to search */
  107293. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  107294. int iLevel, /* Level of segments to scan */
  107295. const char *zTerm, /* Term to query for */
  107296. int nTerm, /* Size of zTerm in bytes */
  107297. int isPrefix, /* True for a prefix search */
  107298. int isScan, /* True to scan from zTerm to EOF */
  107299. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  107300. ){
  107301. assert( iIndex>=0 && iIndex<p->nIndex );
  107302. assert( iLevel==FTS3_SEGCURSOR_ALL
  107303. || iLevel==FTS3_SEGCURSOR_PENDING
  107304. || iLevel>=0
  107305. );
  107306. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  107307. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  107308. assert( isPrefix==0 || isScan==0 );
  107309. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  107310. return fts3SegReaderCursor(
  107311. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  107312. );
  107313. }
  107314. /*
  107315. ** In addition to its current configuration, have the Fts3MultiSegReader
  107316. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  107317. **
  107318. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  107319. */
  107320. static int fts3SegReaderCursorAddZero(
  107321. Fts3Table *p, /* FTS virtual table handle */
  107322. int iLangid,
  107323. const char *zTerm, /* Term to scan doclist of */
  107324. int nTerm, /* Number of bytes in zTerm */
  107325. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  107326. ){
  107327. return fts3SegReaderCursor(p,
  107328. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  107329. );
  107330. }
  107331. /*
  107332. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  107333. ** if isPrefix is true, to scan the doclist for all terms for which
  107334. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  107335. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  107336. ** an SQLite error code.
  107337. **
  107338. ** It is the responsibility of the caller to free this object by eventually
  107339. ** passing it to fts3SegReaderCursorFree()
  107340. **
  107341. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  107342. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  107343. */
  107344. static int fts3TermSegReaderCursor(
  107345. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  107346. const char *zTerm, /* Term to query for */
  107347. int nTerm, /* Size of zTerm in bytes */
  107348. int isPrefix, /* True for a prefix search */
  107349. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  107350. ){
  107351. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  107352. int rc = SQLITE_NOMEM; /* Return code */
  107353. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  107354. if( pSegcsr ){
  107355. int i;
  107356. int bFound = 0; /* True once an index has been found */
  107357. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  107358. if( isPrefix ){
  107359. for(i=1; bFound==0 && i<p->nIndex; i++){
  107360. if( p->aIndex[i].nPrefix==nTerm ){
  107361. bFound = 1;
  107362. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107363. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  107364. );
  107365. pSegcsr->bLookup = 1;
  107366. }
  107367. }
  107368. for(i=1; bFound==0 && i<p->nIndex; i++){
  107369. if( p->aIndex[i].nPrefix==nTerm+1 ){
  107370. bFound = 1;
  107371. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107372. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  107373. );
  107374. if( rc==SQLITE_OK ){
  107375. rc = fts3SegReaderCursorAddZero(
  107376. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  107377. );
  107378. }
  107379. }
  107380. }
  107381. }
  107382. if( bFound==0 ){
  107383. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  107384. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  107385. );
  107386. pSegcsr->bLookup = !isPrefix;
  107387. }
  107388. }
  107389. *ppSegcsr = pSegcsr;
  107390. return rc;
  107391. }
  107392. /*
  107393. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  107394. */
  107395. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  107396. sqlite3Fts3SegReaderFinish(pSegcsr);
  107397. sqlite3_free(pSegcsr);
  107398. }
  107399. /*
  107400. ** This function retrieves the doclist for the specified term (or term
  107401. ** prefix) from the database.
  107402. */
  107403. static int fts3TermSelect(
  107404. Fts3Table *p, /* Virtual table handle */
  107405. Fts3PhraseToken *pTok, /* Token to query for */
  107406. int iColumn, /* Column to query (or -ve for all columns) */
  107407. int *pnOut, /* OUT: Size of buffer at *ppOut */
  107408. char **ppOut /* OUT: Malloced result buffer */
  107409. ){
  107410. int rc; /* Return code */
  107411. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  107412. TermSelect tsc; /* Object for pair-wise doclist merging */
  107413. Fts3SegFilter filter; /* Segment term filter configuration */
  107414. pSegcsr = pTok->pSegcsr;
  107415. memset(&tsc, 0, sizeof(TermSelect));
  107416. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  107417. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  107418. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  107419. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  107420. filter.iCol = iColumn;
  107421. filter.zTerm = pTok->z;
  107422. filter.nTerm = pTok->n;
  107423. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  107424. while( SQLITE_OK==rc
  107425. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  107426. ){
  107427. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  107428. }
  107429. if( rc==SQLITE_OK ){
  107430. rc = fts3TermSelectFinishMerge(p, &tsc);
  107431. }
  107432. if( rc==SQLITE_OK ){
  107433. *ppOut = tsc.aaOutput[0];
  107434. *pnOut = tsc.anOutput[0];
  107435. }else{
  107436. int i;
  107437. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  107438. sqlite3_free(tsc.aaOutput[i]);
  107439. }
  107440. }
  107441. fts3SegReaderCursorFree(pSegcsr);
  107442. pTok->pSegcsr = 0;
  107443. return rc;
  107444. }
  107445. /*
  107446. ** This function counts the total number of docids in the doclist stored
  107447. ** in buffer aList[], size nList bytes.
  107448. **
  107449. ** If the isPoslist argument is true, then it is assumed that the doclist
  107450. ** contains a position-list following each docid. Otherwise, it is assumed
  107451. ** that the doclist is simply a list of docids stored as delta encoded
  107452. ** varints.
  107453. */
  107454. static int fts3DoclistCountDocids(char *aList, int nList){
  107455. int nDoc = 0; /* Return value */
  107456. if( aList ){
  107457. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  107458. char *p = aList; /* Cursor */
  107459. while( p<aEnd ){
  107460. nDoc++;
  107461. while( (*p++)&0x80 ); /* Skip docid varint */
  107462. fts3PoslistCopy(0, &p); /* Skip over position list */
  107463. }
  107464. }
  107465. return nDoc;
  107466. }
  107467. /*
  107468. ** Advance the cursor to the next row in the %_content table that
  107469. ** matches the search criteria. For a MATCH search, this will be
  107470. ** the next row that matches. For a full-table scan, this will be
  107471. ** simply the next row in the %_content table. For a docid lookup,
  107472. ** this routine simply sets the EOF flag.
  107473. **
  107474. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  107475. ** even if we reach end-of-file. The fts3EofMethod() will be called
  107476. ** subsequently to determine whether or not an EOF was hit.
  107477. */
  107478. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  107479. int rc;
  107480. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  107481. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  107482. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  107483. pCsr->isEof = 1;
  107484. rc = sqlite3_reset(pCsr->pStmt);
  107485. }else{
  107486. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  107487. rc = SQLITE_OK;
  107488. }
  107489. }else{
  107490. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  107491. }
  107492. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  107493. return rc;
  107494. }
  107495. /*
  107496. ** The following are copied from sqliteInt.h.
  107497. **
  107498. ** Constants for the largest and smallest possible 64-bit signed integers.
  107499. ** These macros are designed to work correctly on both 32-bit and 64-bit
  107500. ** compilers.
  107501. */
  107502. #ifndef SQLITE_AMALGAMATION
  107503. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  107504. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  107505. #endif
  107506. /*
  107507. ** If the numeric type of argument pVal is "integer", then return it
  107508. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  107509. ** the second parameter, iDefault.
  107510. */
  107511. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  107512. if( pVal ){
  107513. int eType = sqlite3_value_numeric_type(pVal);
  107514. if( eType==SQLITE_INTEGER ){
  107515. return sqlite3_value_int64(pVal);
  107516. }
  107517. }
  107518. return iDefault;
  107519. }
  107520. /*
  107521. ** This is the xFilter interface for the virtual table. See
  107522. ** the virtual table xFilter method documentation for additional
  107523. ** information.
  107524. **
  107525. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  107526. ** the %_content table.
  107527. **
  107528. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  107529. ** in the %_content table.
  107530. **
  107531. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  107532. ** column on the left-hand side of the MATCH operator is column
  107533. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  107534. ** side of the MATCH operator.
  107535. */
  107536. static int fts3FilterMethod(
  107537. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  107538. int idxNum, /* Strategy index */
  107539. const char *idxStr, /* Unused */
  107540. int nVal, /* Number of elements in apVal */
  107541. sqlite3_value **apVal /* Arguments for the indexing scheme */
  107542. ){
  107543. int rc;
  107544. char *zSql; /* SQL statement used to access %_content */
  107545. int eSearch;
  107546. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  107547. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  107548. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  107549. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  107550. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  107551. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  107552. int iIdx;
  107553. UNUSED_PARAMETER(idxStr);
  107554. UNUSED_PARAMETER(nVal);
  107555. eSearch = (idxNum & 0x0000FFFF);
  107556. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  107557. assert( p->pSegments==0 );
  107558. /* Collect arguments into local variables */
  107559. iIdx = 0;
  107560. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  107561. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  107562. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  107563. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  107564. assert( iIdx==nVal );
  107565. /* In case the cursor has been used before, clear it now. */
  107566. sqlite3_finalize(pCsr->pStmt);
  107567. sqlite3_free(pCsr->aDoclist);
  107568. sqlite3Fts3ExprFree(pCsr->pExpr);
  107569. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  107570. /* Set the lower and upper bounds on docids to return */
  107571. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  107572. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  107573. if( idxStr ){
  107574. pCsr->bDesc = (idxStr[0]=='D');
  107575. }else{
  107576. pCsr->bDesc = p->bDescIdx;
  107577. }
  107578. pCsr->eSearch = (i16)eSearch;
  107579. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  107580. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  107581. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  107582. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  107583. return SQLITE_NOMEM;
  107584. }
  107585. pCsr->iLangid = 0;
  107586. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  107587. assert( p->base.zErrMsg==0 );
  107588. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  107589. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  107590. &p->base.zErrMsg
  107591. );
  107592. if( rc!=SQLITE_OK ){
  107593. return rc;
  107594. }
  107595. rc = fts3EvalStart(pCsr);
  107596. sqlite3Fts3SegmentsClose(p);
  107597. if( rc!=SQLITE_OK ) return rc;
  107598. pCsr->pNextId = pCsr->aDoclist;
  107599. pCsr->iPrevId = 0;
  107600. }
  107601. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  107602. ** statement loops through all rows of the %_content table. For a
  107603. ** full-text query or docid lookup, the statement retrieves a single
  107604. ** row by docid.
  107605. */
  107606. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  107607. zSql = sqlite3_mprintf(
  107608. "SELECT %s ORDER BY rowid %s",
  107609. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  107610. );
  107611. if( zSql ){
  107612. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  107613. sqlite3_free(zSql);
  107614. }else{
  107615. rc = SQLITE_NOMEM;
  107616. }
  107617. }else if( eSearch==FTS3_DOCID_SEARCH ){
  107618. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  107619. if( rc==SQLITE_OK ){
  107620. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  107621. }
  107622. }
  107623. if( rc!=SQLITE_OK ) return rc;
  107624. return fts3NextMethod(pCursor);
  107625. }
  107626. /*
  107627. ** This is the xEof method of the virtual table. SQLite calls this
  107628. ** routine to find out if it has reached the end of a result set.
  107629. */
  107630. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  107631. return ((Fts3Cursor *)pCursor)->isEof;
  107632. }
  107633. /*
  107634. ** This is the xRowid method. The SQLite core calls this routine to
  107635. ** retrieve the rowid for the current row of the result set. fts3
  107636. ** exposes %_content.docid as the rowid for the virtual table. The
  107637. ** rowid should be written to *pRowid.
  107638. */
  107639. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  107640. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  107641. *pRowid = pCsr->iPrevId;
  107642. return SQLITE_OK;
  107643. }
  107644. /*
  107645. ** This is the xColumn method, called by SQLite to request a value from
  107646. ** the row that the supplied cursor currently points to.
  107647. **
  107648. ** If:
  107649. **
  107650. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  107651. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  107652. ** (iCol == p->nColumn+1) -> Docid column
  107653. ** (iCol == p->nColumn+2) -> Langid column
  107654. */
  107655. static int fts3ColumnMethod(
  107656. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  107657. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  107658. int iCol /* Index of column to read value from */
  107659. ){
  107660. int rc = SQLITE_OK; /* Return Code */
  107661. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  107662. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  107663. /* The column value supplied by SQLite must be in range. */
  107664. assert( iCol>=0 && iCol<=p->nColumn+2 );
  107665. if( iCol==p->nColumn+1 ){
  107666. /* This call is a request for the "docid" column. Since "docid" is an
  107667. ** alias for "rowid", use the xRowid() method to obtain the value.
  107668. */
  107669. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  107670. }else if( iCol==p->nColumn ){
  107671. /* The extra column whose name is the same as the table.
  107672. ** Return a blob which is a pointer to the cursor. */
  107673. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  107674. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  107675. sqlite3_result_int64(pCtx, pCsr->iLangid);
  107676. }else{
  107677. /* The requested column is either a user column (one that contains
  107678. ** indexed data), or the language-id column. */
  107679. rc = fts3CursorSeek(0, pCsr);
  107680. if( rc==SQLITE_OK ){
  107681. if( iCol==p->nColumn+2 ){
  107682. int iLangid = 0;
  107683. if( p->zLanguageid ){
  107684. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  107685. }
  107686. sqlite3_result_int(pCtx, iLangid);
  107687. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  107688. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  107689. }
  107690. }
  107691. }
  107692. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  107693. return rc;
  107694. }
  107695. /*
  107696. ** This function is the implementation of the xUpdate callback used by
  107697. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  107698. ** inserted, updated or deleted.
  107699. */
  107700. static int fts3UpdateMethod(
  107701. sqlite3_vtab *pVtab, /* Virtual table handle */
  107702. int nArg, /* Size of argument array */
  107703. sqlite3_value **apVal, /* Array of arguments */
  107704. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  107705. ){
  107706. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  107707. }
  107708. /*
  107709. ** Implementation of xSync() method. Flush the contents of the pending-terms
  107710. ** hash-table to the database.
  107711. */
  107712. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  107713. /* Following an incremental-merge operation, assuming that the input
  107714. ** segments are not completely consumed (the usual case), they are updated
  107715. ** in place to remove the entries that have already been merged. This
  107716. ** involves updating the leaf block that contains the smallest unmerged
  107717. ** entry and each block (if any) between the leaf and the root node. So
  107718. ** if the height of the input segment b-trees is N, and input segments
  107719. ** are merged eight at a time, updating the input segments at the end
  107720. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  107721. ** small - often between 0 and 2. So the overhead of the incremental
  107722. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  107723. ** dwarfing the actual productive work accomplished, the incremental merge
  107724. ** is only attempted if it will write at least 64 leaf blocks. Hence
  107725. ** nMinMerge.
  107726. **
  107727. ** Of course, updating the input segments also involves deleting a bunch
  107728. ** of blocks from the segments table. But this is not considered overhead
  107729. ** as it would also be required by a crisis-merge that used the same input
  107730. ** segments.
  107731. */
  107732. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  107733. Fts3Table *p = (Fts3Table*)pVtab;
  107734. int rc = sqlite3Fts3PendingTermsFlush(p);
  107735. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  107736. int mxLevel = 0; /* Maximum relative level value in db */
  107737. int A; /* Incr-merge parameter A */
  107738. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  107739. assert( rc==SQLITE_OK || mxLevel==0 );
  107740. A = p->nLeafAdd * mxLevel;
  107741. A += (A/2);
  107742. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  107743. }
  107744. sqlite3Fts3SegmentsClose(p);
  107745. return rc;
  107746. }
  107747. /*
  107748. ** Implementation of xBegin() method. This is a no-op.
  107749. */
  107750. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  107751. Fts3Table *p = (Fts3Table*)pVtab;
  107752. UNUSED_PARAMETER(pVtab);
  107753. assert( p->pSegments==0 );
  107754. assert( p->nPendingData==0 );
  107755. assert( p->inTransaction!=1 );
  107756. TESTONLY( p->inTransaction = 1 );
  107757. TESTONLY( p->mxSavepoint = -1; );
  107758. p->nLeafAdd = 0;
  107759. return SQLITE_OK;
  107760. }
  107761. /*
  107762. ** Implementation of xCommit() method. This is a no-op. The contents of
  107763. ** the pending-terms hash-table have already been flushed into the database
  107764. ** by fts3SyncMethod().
  107765. */
  107766. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  107767. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  107768. UNUSED_PARAMETER(pVtab);
  107769. assert( p->nPendingData==0 );
  107770. assert( p->inTransaction!=0 );
  107771. assert( p->pSegments==0 );
  107772. TESTONLY( p->inTransaction = 0 );
  107773. TESTONLY( p->mxSavepoint = -1; );
  107774. return SQLITE_OK;
  107775. }
  107776. /*
  107777. ** Implementation of xRollback(). Discard the contents of the pending-terms
  107778. ** hash-table. Any changes made to the database are reverted by SQLite.
  107779. */
  107780. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  107781. Fts3Table *p = (Fts3Table*)pVtab;
  107782. sqlite3Fts3PendingTermsClear(p);
  107783. assert( p->inTransaction!=0 );
  107784. TESTONLY( p->inTransaction = 0 );
  107785. TESTONLY( p->mxSavepoint = -1; );
  107786. return SQLITE_OK;
  107787. }
  107788. /*
  107789. ** When called, *ppPoslist must point to the byte immediately following the
  107790. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  107791. ** moves *ppPoslist so that it instead points to the first byte of the
  107792. ** same position list.
  107793. */
  107794. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  107795. char *p = &(*ppPoslist)[-2];
  107796. char c = 0;
  107797. while( p>pStart && (c=*p--)==0 );
  107798. while( p>pStart && (*p & 0x80) | c ){
  107799. c = *p--;
  107800. }
  107801. if( p>pStart ){ p = &p[2]; }
  107802. while( *p++&0x80 );
  107803. *ppPoslist = p;
  107804. }
  107805. /*
  107806. ** Helper function used by the implementation of the overloaded snippet(),
  107807. ** offsets() and optimize() SQL functions.
  107808. **
  107809. ** If the value passed as the third argument is a blob of size
  107810. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  107811. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  107812. ** message is written to context pContext and SQLITE_ERROR returned. The
  107813. ** string passed via zFunc is used as part of the error message.
  107814. */
  107815. static int fts3FunctionArg(
  107816. sqlite3_context *pContext, /* SQL function call context */
  107817. const char *zFunc, /* Function name */
  107818. sqlite3_value *pVal, /* argv[0] passed to function */
  107819. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  107820. ){
  107821. Fts3Cursor *pRet;
  107822. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  107823. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  107824. ){
  107825. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  107826. sqlite3_result_error(pContext, zErr, -1);
  107827. sqlite3_free(zErr);
  107828. return SQLITE_ERROR;
  107829. }
  107830. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  107831. *ppCsr = pRet;
  107832. return SQLITE_OK;
  107833. }
  107834. /*
  107835. ** Implementation of the snippet() function for FTS3
  107836. */
  107837. static void fts3SnippetFunc(
  107838. sqlite3_context *pContext, /* SQLite function call context */
  107839. int nVal, /* Size of apVal[] array */
  107840. sqlite3_value **apVal /* Array of arguments */
  107841. ){
  107842. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107843. const char *zStart = "<b>";
  107844. const char *zEnd = "</b>";
  107845. const char *zEllipsis = "<b>...</b>";
  107846. int iCol = -1;
  107847. int nToken = 15; /* Default number of tokens in snippet */
  107848. /* There must be at least one argument passed to this function (otherwise
  107849. ** the non-overloaded version would have been called instead of this one).
  107850. */
  107851. assert( nVal>=1 );
  107852. if( nVal>6 ){
  107853. sqlite3_result_error(pContext,
  107854. "wrong number of arguments to function snippet()", -1);
  107855. return;
  107856. }
  107857. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  107858. switch( nVal ){
  107859. case 6: nToken = sqlite3_value_int(apVal[5]);
  107860. case 5: iCol = sqlite3_value_int(apVal[4]);
  107861. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  107862. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  107863. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  107864. }
  107865. if( !zEllipsis || !zEnd || !zStart ){
  107866. sqlite3_result_error_nomem(pContext);
  107867. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  107868. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  107869. }
  107870. }
  107871. /*
  107872. ** Implementation of the offsets() function for FTS3
  107873. */
  107874. static void fts3OffsetsFunc(
  107875. sqlite3_context *pContext, /* SQLite function call context */
  107876. int nVal, /* Size of argument array */
  107877. sqlite3_value **apVal /* Array of arguments */
  107878. ){
  107879. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107880. UNUSED_PARAMETER(nVal);
  107881. assert( nVal==1 );
  107882. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  107883. assert( pCsr );
  107884. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  107885. sqlite3Fts3Offsets(pContext, pCsr);
  107886. }
  107887. }
  107888. /*
  107889. ** Implementation of the special optimize() function for FTS3. This
  107890. ** function merges all segments in the database to a single segment.
  107891. ** Example usage is:
  107892. **
  107893. ** SELECT optimize(t) FROM t LIMIT 1;
  107894. **
  107895. ** where 't' is the name of an FTS3 table.
  107896. */
  107897. static void fts3OptimizeFunc(
  107898. sqlite3_context *pContext, /* SQLite function call context */
  107899. int nVal, /* Size of argument array */
  107900. sqlite3_value **apVal /* Array of arguments */
  107901. ){
  107902. int rc; /* Return code */
  107903. Fts3Table *p; /* Virtual table handle */
  107904. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  107905. UNUSED_PARAMETER(nVal);
  107906. assert( nVal==1 );
  107907. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  107908. p = (Fts3Table *)pCursor->base.pVtab;
  107909. assert( p );
  107910. rc = sqlite3Fts3Optimize(p);
  107911. switch( rc ){
  107912. case SQLITE_OK:
  107913. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  107914. break;
  107915. case SQLITE_DONE:
  107916. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  107917. break;
  107918. default:
  107919. sqlite3_result_error_code(pContext, rc);
  107920. break;
  107921. }
  107922. }
  107923. /*
  107924. ** Implementation of the matchinfo() function for FTS3
  107925. */
  107926. static void fts3MatchinfoFunc(
  107927. sqlite3_context *pContext, /* SQLite function call context */
  107928. int nVal, /* Size of argument array */
  107929. sqlite3_value **apVal /* Array of arguments */
  107930. ){
  107931. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  107932. assert( nVal==1 || nVal==2 );
  107933. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  107934. const char *zArg = 0;
  107935. if( nVal>1 ){
  107936. zArg = (const char *)sqlite3_value_text(apVal[1]);
  107937. }
  107938. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  107939. }
  107940. }
  107941. /*
  107942. ** This routine implements the xFindFunction method for the FTS3
  107943. ** virtual table.
  107944. */
  107945. static int fts3FindFunctionMethod(
  107946. sqlite3_vtab *pVtab, /* Virtual table handle */
  107947. int nArg, /* Number of SQL function arguments */
  107948. const char *zName, /* Name of SQL function */
  107949. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  107950. void **ppArg /* Unused */
  107951. ){
  107952. struct Overloaded {
  107953. const char *zName;
  107954. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  107955. } aOverload[] = {
  107956. { "snippet", fts3SnippetFunc },
  107957. { "offsets", fts3OffsetsFunc },
  107958. { "optimize", fts3OptimizeFunc },
  107959. { "matchinfo", fts3MatchinfoFunc },
  107960. };
  107961. int i; /* Iterator variable */
  107962. UNUSED_PARAMETER(pVtab);
  107963. UNUSED_PARAMETER(nArg);
  107964. UNUSED_PARAMETER(ppArg);
  107965. for(i=0; i<SizeofArray(aOverload); i++){
  107966. if( strcmp(zName, aOverload[i].zName)==0 ){
  107967. *pxFunc = aOverload[i].xFunc;
  107968. return 1;
  107969. }
  107970. }
  107971. /* No function of the specified name was found. Return 0. */
  107972. return 0;
  107973. }
  107974. /*
  107975. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  107976. */
  107977. static int fts3RenameMethod(
  107978. sqlite3_vtab *pVtab, /* Virtual table handle */
  107979. const char *zName /* New name of table */
  107980. ){
  107981. Fts3Table *p = (Fts3Table *)pVtab;
  107982. sqlite3 *db = p->db; /* Database connection */
  107983. int rc; /* Return Code */
  107984. /* As it happens, the pending terms table is always empty here. This is
  107985. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  107986. ** always opens a savepoint transaction. And the xSavepoint() method
  107987. ** flushes the pending terms table. But leave the (no-op) call to
  107988. ** PendingTermsFlush() in in case that changes.
  107989. */
  107990. assert( p->nPendingData==0 );
  107991. rc = sqlite3Fts3PendingTermsFlush(p);
  107992. if( p->zContentTbl==0 ){
  107993. fts3DbExec(&rc, db,
  107994. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  107995. p->zDb, p->zName, zName
  107996. );
  107997. }
  107998. if( p->bHasDocsize ){
  107999. fts3DbExec(&rc, db,
  108000. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  108001. p->zDb, p->zName, zName
  108002. );
  108003. }
  108004. if( p->bHasStat ){
  108005. fts3DbExec(&rc, db,
  108006. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  108007. p->zDb, p->zName, zName
  108008. );
  108009. }
  108010. fts3DbExec(&rc, db,
  108011. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  108012. p->zDb, p->zName, zName
  108013. );
  108014. fts3DbExec(&rc, db,
  108015. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  108016. p->zDb, p->zName, zName
  108017. );
  108018. return rc;
  108019. }
  108020. /*
  108021. ** The xSavepoint() method.
  108022. **
  108023. ** Flush the contents of the pending-terms table to disk.
  108024. */
  108025. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108026. int rc = SQLITE_OK;
  108027. UNUSED_PARAMETER(iSavepoint);
  108028. assert( ((Fts3Table *)pVtab)->inTransaction );
  108029. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  108030. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  108031. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  108032. rc = fts3SyncMethod(pVtab);
  108033. }
  108034. return rc;
  108035. }
  108036. /*
  108037. ** The xRelease() method.
  108038. **
  108039. ** This is a no-op.
  108040. */
  108041. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108042. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  108043. UNUSED_PARAMETER(iSavepoint);
  108044. UNUSED_PARAMETER(pVtab);
  108045. assert( p->inTransaction );
  108046. assert( p->mxSavepoint >= iSavepoint );
  108047. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  108048. return SQLITE_OK;
  108049. }
  108050. /*
  108051. ** The xRollbackTo() method.
  108052. **
  108053. ** Discard the contents of the pending terms table.
  108054. */
  108055. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  108056. Fts3Table *p = (Fts3Table*)pVtab;
  108057. UNUSED_PARAMETER(iSavepoint);
  108058. assert( p->inTransaction );
  108059. assert( p->mxSavepoint >= iSavepoint );
  108060. TESTONLY( p->mxSavepoint = iSavepoint );
  108061. sqlite3Fts3PendingTermsClear(p);
  108062. return SQLITE_OK;
  108063. }
  108064. static const sqlite3_module fts3Module = {
  108065. /* iVersion */ 2,
  108066. /* xCreate */ fts3CreateMethod,
  108067. /* xConnect */ fts3ConnectMethod,
  108068. /* xBestIndex */ fts3BestIndexMethod,
  108069. /* xDisconnect */ fts3DisconnectMethod,
  108070. /* xDestroy */ fts3DestroyMethod,
  108071. /* xOpen */ fts3OpenMethod,
  108072. /* xClose */ fts3CloseMethod,
  108073. /* xFilter */ fts3FilterMethod,
  108074. /* xNext */ fts3NextMethod,
  108075. /* xEof */ fts3EofMethod,
  108076. /* xColumn */ fts3ColumnMethod,
  108077. /* xRowid */ fts3RowidMethod,
  108078. /* xUpdate */ fts3UpdateMethod,
  108079. /* xBegin */ fts3BeginMethod,
  108080. /* xSync */ fts3SyncMethod,
  108081. /* xCommit */ fts3CommitMethod,
  108082. /* xRollback */ fts3RollbackMethod,
  108083. /* xFindFunction */ fts3FindFunctionMethod,
  108084. /* xRename */ fts3RenameMethod,
  108085. /* xSavepoint */ fts3SavepointMethod,
  108086. /* xRelease */ fts3ReleaseMethod,
  108087. /* xRollbackTo */ fts3RollbackToMethod,
  108088. };
  108089. /*
  108090. ** This function is registered as the module destructor (called when an
  108091. ** FTS3 enabled database connection is closed). It frees the memory
  108092. ** allocated for the tokenizer hash table.
  108093. */
  108094. static void hashDestroy(void *p){
  108095. Fts3Hash *pHash = (Fts3Hash *)p;
  108096. sqlite3Fts3HashClear(pHash);
  108097. sqlite3_free(pHash);
  108098. }
  108099. /*
  108100. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  108101. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  108102. ** respectively. The following three forward declarations are for functions
  108103. ** declared in these files used to retrieve the respective implementations.
  108104. **
  108105. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  108106. ** to by the argument to point to the "simple" tokenizer implementation.
  108107. ** And so on.
  108108. */
  108109. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108110. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108111. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108112. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  108113. #endif
  108114. #ifdef SQLITE_ENABLE_ICU
  108115. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  108116. #endif
  108117. /*
  108118. ** Initialize the fts3 extension. If this extension is built as part
  108119. ** of the sqlite library, then this function is called directly by
  108120. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  108121. ** function is called by the sqlite3_extension_init() entry point.
  108122. */
  108123. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  108124. int rc = SQLITE_OK;
  108125. Fts3Hash *pHash = 0;
  108126. const sqlite3_tokenizer_module *pSimple = 0;
  108127. const sqlite3_tokenizer_module *pPorter = 0;
  108128. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108129. const sqlite3_tokenizer_module *pUnicode = 0;
  108130. #endif
  108131. #ifdef SQLITE_ENABLE_ICU
  108132. const sqlite3_tokenizer_module *pIcu = 0;
  108133. sqlite3Fts3IcuTokenizerModule(&pIcu);
  108134. #endif
  108135. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108136. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  108137. #endif
  108138. #ifdef SQLITE_TEST
  108139. rc = sqlite3Fts3InitTerm(db);
  108140. if( rc!=SQLITE_OK ) return rc;
  108141. #endif
  108142. rc = sqlite3Fts3InitAux(db);
  108143. if( rc!=SQLITE_OK ) return rc;
  108144. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  108145. sqlite3Fts3PorterTokenizerModule(&pPorter);
  108146. /* Allocate and initialize the hash-table used to store tokenizers. */
  108147. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  108148. if( !pHash ){
  108149. rc = SQLITE_NOMEM;
  108150. }else{
  108151. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  108152. }
  108153. /* Load the built-in tokenizers into the hash table */
  108154. if( rc==SQLITE_OK ){
  108155. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  108156. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  108157. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  108158. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  108159. #endif
  108160. #ifdef SQLITE_ENABLE_ICU
  108161. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  108162. #endif
  108163. ){
  108164. rc = SQLITE_NOMEM;
  108165. }
  108166. }
  108167. #ifdef SQLITE_TEST
  108168. if( rc==SQLITE_OK ){
  108169. rc = sqlite3Fts3ExprInitTestInterface(db);
  108170. }
  108171. #endif
  108172. /* Create the virtual table wrapper around the hash-table and overload
  108173. ** the two scalar functions. If this is successful, register the
  108174. ** module with sqlite.
  108175. */
  108176. if( SQLITE_OK==rc
  108177. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  108178. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  108179. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  108180. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  108181. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  108182. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  108183. ){
  108184. rc = sqlite3_create_module_v2(
  108185. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  108186. );
  108187. if( rc==SQLITE_OK ){
  108188. rc = sqlite3_create_module_v2(
  108189. db, "fts4", &fts3Module, (void *)pHash, 0
  108190. );
  108191. }
  108192. if( rc==SQLITE_OK ){
  108193. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  108194. }
  108195. return rc;
  108196. }
  108197. /* An error has occurred. Delete the hash table and return the error code. */
  108198. assert( rc!=SQLITE_OK );
  108199. if( pHash ){
  108200. sqlite3Fts3HashClear(pHash);
  108201. sqlite3_free(pHash);
  108202. }
  108203. return rc;
  108204. }
  108205. /*
  108206. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  108207. ** by pExpr.
  108208. **
  108209. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  108210. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  108211. ** Fts3SegReader objects internally to provide an interface to seek or scan
  108212. ** within the union of all segments of a b-tree. Hence the name.
  108213. **
  108214. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  108215. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  108216. ** there exists prefix b-tree of the right length) then it may be traversed
  108217. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  108218. ** doclist and then traversed.
  108219. */
  108220. static void fts3EvalAllocateReaders(
  108221. Fts3Cursor *pCsr, /* FTS cursor handle */
  108222. Fts3Expr *pExpr, /* Allocate readers for this expression */
  108223. int *pnToken, /* OUT: Total number of tokens in phrase. */
  108224. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  108225. int *pRc /* IN/OUT: Error code */
  108226. ){
  108227. if( pExpr && SQLITE_OK==*pRc ){
  108228. if( pExpr->eType==FTSQUERY_PHRASE ){
  108229. int i;
  108230. int nToken = pExpr->pPhrase->nToken;
  108231. *pnToken += nToken;
  108232. for(i=0; i<nToken; i++){
  108233. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  108234. int rc = fts3TermSegReaderCursor(pCsr,
  108235. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  108236. );
  108237. if( rc!=SQLITE_OK ){
  108238. *pRc = rc;
  108239. return;
  108240. }
  108241. }
  108242. assert( pExpr->pPhrase->iDoclistToken==0 );
  108243. pExpr->pPhrase->iDoclistToken = -1;
  108244. }else{
  108245. *pnOr += (pExpr->eType==FTSQUERY_OR);
  108246. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  108247. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  108248. }
  108249. }
  108250. }
  108251. /*
  108252. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  108253. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  108254. **
  108255. ** This function assumes that pList points to a buffer allocated using
  108256. ** sqlite3_malloc(). This function takes responsibility for eventually
  108257. ** freeing the buffer.
  108258. */
  108259. static void fts3EvalPhraseMergeToken(
  108260. Fts3Table *pTab, /* FTS Table pointer */
  108261. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  108262. int iToken, /* Token pList/nList corresponds to */
  108263. char *pList, /* Pointer to doclist */
  108264. int nList /* Number of bytes in pList */
  108265. ){
  108266. assert( iToken!=p->iDoclistToken );
  108267. if( pList==0 ){
  108268. sqlite3_free(p->doclist.aAll);
  108269. p->doclist.aAll = 0;
  108270. p->doclist.nAll = 0;
  108271. }
  108272. else if( p->iDoclistToken<0 ){
  108273. p->doclist.aAll = pList;
  108274. p->doclist.nAll = nList;
  108275. }
  108276. else if( p->doclist.aAll==0 ){
  108277. sqlite3_free(pList);
  108278. }
  108279. else {
  108280. char *pLeft;
  108281. char *pRight;
  108282. int nLeft;
  108283. int nRight;
  108284. int nDiff;
  108285. if( p->iDoclistToken<iToken ){
  108286. pLeft = p->doclist.aAll;
  108287. nLeft = p->doclist.nAll;
  108288. pRight = pList;
  108289. nRight = nList;
  108290. nDiff = iToken - p->iDoclistToken;
  108291. }else{
  108292. pRight = p->doclist.aAll;
  108293. nRight = p->doclist.nAll;
  108294. pLeft = pList;
  108295. nLeft = nList;
  108296. nDiff = p->iDoclistToken - iToken;
  108297. }
  108298. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  108299. sqlite3_free(pLeft);
  108300. p->doclist.aAll = pRight;
  108301. p->doclist.nAll = nRight;
  108302. }
  108303. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  108304. }
  108305. /*
  108306. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  108307. ** does not take deferred tokens into account.
  108308. **
  108309. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108310. */
  108311. static int fts3EvalPhraseLoad(
  108312. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108313. Fts3Phrase *p /* Phrase object */
  108314. ){
  108315. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108316. int iToken;
  108317. int rc = SQLITE_OK;
  108318. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  108319. Fts3PhraseToken *pToken = &p->aToken[iToken];
  108320. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  108321. if( pToken->pSegcsr ){
  108322. int nThis = 0;
  108323. char *pThis = 0;
  108324. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  108325. if( rc==SQLITE_OK ){
  108326. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  108327. }
  108328. }
  108329. assert( pToken->pSegcsr==0 );
  108330. }
  108331. return rc;
  108332. }
  108333. /*
  108334. ** This function is called on each phrase after the position lists for
  108335. ** any deferred tokens have been loaded into memory. It updates the phrases
  108336. ** current position list to include only those positions that are really
  108337. ** instances of the phrase (after considering deferred tokens). If this
  108338. ** means that the phrase does not appear in the current row, doclist.pList
  108339. ** and doclist.nList are both zeroed.
  108340. **
  108341. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108342. */
  108343. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  108344. int iToken; /* Used to iterate through phrase tokens */
  108345. char *aPoslist = 0; /* Position list for deferred tokens */
  108346. int nPoslist = 0; /* Number of bytes in aPoslist */
  108347. int iPrev = -1; /* Token number of previous deferred token */
  108348. assert( pPhrase->doclist.bFreeList==0 );
  108349. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  108350. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  108351. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  108352. if( pDeferred ){
  108353. char *pList;
  108354. int nList;
  108355. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  108356. if( rc!=SQLITE_OK ) return rc;
  108357. if( pList==0 ){
  108358. sqlite3_free(aPoslist);
  108359. pPhrase->doclist.pList = 0;
  108360. pPhrase->doclist.nList = 0;
  108361. return SQLITE_OK;
  108362. }else if( aPoslist==0 ){
  108363. aPoslist = pList;
  108364. nPoslist = nList;
  108365. }else{
  108366. char *aOut = pList;
  108367. char *p1 = aPoslist;
  108368. char *p2 = aOut;
  108369. assert( iPrev>=0 );
  108370. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  108371. sqlite3_free(aPoslist);
  108372. aPoslist = pList;
  108373. nPoslist = (int)(aOut - aPoslist);
  108374. if( nPoslist==0 ){
  108375. sqlite3_free(aPoslist);
  108376. pPhrase->doclist.pList = 0;
  108377. pPhrase->doclist.nList = 0;
  108378. return SQLITE_OK;
  108379. }
  108380. }
  108381. iPrev = iToken;
  108382. }
  108383. }
  108384. if( iPrev>=0 ){
  108385. int nMaxUndeferred = pPhrase->iDoclistToken;
  108386. if( nMaxUndeferred<0 ){
  108387. pPhrase->doclist.pList = aPoslist;
  108388. pPhrase->doclist.nList = nPoslist;
  108389. pPhrase->doclist.iDocid = pCsr->iPrevId;
  108390. pPhrase->doclist.bFreeList = 1;
  108391. }else{
  108392. int nDistance;
  108393. char *p1;
  108394. char *p2;
  108395. char *aOut;
  108396. if( nMaxUndeferred>iPrev ){
  108397. p1 = aPoslist;
  108398. p2 = pPhrase->doclist.pList;
  108399. nDistance = nMaxUndeferred - iPrev;
  108400. }else{
  108401. p1 = pPhrase->doclist.pList;
  108402. p2 = aPoslist;
  108403. nDistance = iPrev - nMaxUndeferred;
  108404. }
  108405. aOut = (char *)sqlite3_malloc(nPoslist+8);
  108406. if( !aOut ){
  108407. sqlite3_free(aPoslist);
  108408. return SQLITE_NOMEM;
  108409. }
  108410. pPhrase->doclist.pList = aOut;
  108411. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  108412. pPhrase->doclist.bFreeList = 1;
  108413. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  108414. }else{
  108415. sqlite3_free(aOut);
  108416. pPhrase->doclist.pList = 0;
  108417. pPhrase->doclist.nList = 0;
  108418. }
  108419. sqlite3_free(aPoslist);
  108420. }
  108421. }
  108422. return SQLITE_OK;
  108423. }
  108424. /*
  108425. ** Maximum number of tokens a phrase may have to be considered for the
  108426. ** incremental doclists strategy.
  108427. */
  108428. #define MAX_INCR_PHRASE_TOKENS 4
  108429. /*
  108430. ** This function is called for each Fts3Phrase in a full-text query
  108431. ** expression to initialize the mechanism for returning rows. Once this
  108432. ** function has been called successfully on an Fts3Phrase, it may be
  108433. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  108434. **
  108435. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  108436. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  108437. ** memory within this call.
  108438. **
  108439. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  108440. */
  108441. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  108442. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108443. int rc = SQLITE_OK; /* Error code */
  108444. int i;
  108445. /* Determine if doclists may be loaded from disk incrementally. This is
  108446. ** possible if the bOptOk argument is true, the FTS doclists will be
  108447. ** scanned in forward order, and the phrase consists of
  108448. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  108449. ** tokens or prefix tokens that cannot use a prefix-index. */
  108450. int bHaveIncr = 0;
  108451. int bIncrOk = (bOptOk
  108452. && pCsr->bDesc==pTab->bDescIdx
  108453. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  108454. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  108455. #ifdef SQLITE_TEST
  108456. && pTab->bNoIncrDoclist==0
  108457. #endif
  108458. );
  108459. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  108460. Fts3PhraseToken *pToken = &p->aToken[i];
  108461. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  108462. bIncrOk = 0;
  108463. }
  108464. if( pToken->pSegcsr ) bHaveIncr = 1;
  108465. }
  108466. if( bIncrOk && bHaveIncr ){
  108467. /* Use the incremental approach. */
  108468. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  108469. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  108470. Fts3PhraseToken *pToken = &p->aToken[i];
  108471. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  108472. if( pSegcsr ){
  108473. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  108474. }
  108475. }
  108476. p->bIncr = 1;
  108477. }else{
  108478. /* Load the full doclist for the phrase into memory. */
  108479. rc = fts3EvalPhraseLoad(pCsr, p);
  108480. p->bIncr = 0;
  108481. }
  108482. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  108483. return rc;
  108484. }
  108485. /*
  108486. ** This function is used to iterate backwards (from the end to start)
  108487. ** through doclists. It is used by this module to iterate through phrase
  108488. ** doclists in reverse and by the fts3_write.c module to iterate through
  108489. ** pending-terms lists when writing to databases with "order=desc".
  108490. **
  108491. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  108492. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  108493. ** function iterates from the end of the doclist to the beginning.
  108494. */
  108495. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  108496. int bDescIdx, /* True if the doclist is desc */
  108497. char *aDoclist, /* Pointer to entire doclist */
  108498. int nDoclist, /* Length of aDoclist in bytes */
  108499. char **ppIter, /* IN/OUT: Iterator pointer */
  108500. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  108501. int *pnList, /* OUT: List length pointer */
  108502. u8 *pbEof /* OUT: End-of-file flag */
  108503. ){
  108504. char *p = *ppIter;
  108505. assert( nDoclist>0 );
  108506. assert( *pbEof==0 );
  108507. assert( p || *piDocid==0 );
  108508. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  108509. if( p==0 ){
  108510. sqlite3_int64 iDocid = 0;
  108511. char *pNext = 0;
  108512. char *pDocid = aDoclist;
  108513. char *pEnd = &aDoclist[nDoclist];
  108514. int iMul = 1;
  108515. while( pDocid<pEnd ){
  108516. sqlite3_int64 iDelta;
  108517. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  108518. iDocid += (iMul * iDelta);
  108519. pNext = pDocid;
  108520. fts3PoslistCopy(0, &pDocid);
  108521. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  108522. iMul = (bDescIdx ? -1 : 1);
  108523. }
  108524. *pnList = (int)(pEnd - pNext);
  108525. *ppIter = pNext;
  108526. *piDocid = iDocid;
  108527. }else{
  108528. int iMul = (bDescIdx ? -1 : 1);
  108529. sqlite3_int64 iDelta;
  108530. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  108531. *piDocid -= (iMul * iDelta);
  108532. if( p==aDoclist ){
  108533. *pbEof = 1;
  108534. }else{
  108535. char *pSave = p;
  108536. fts3ReversePoslist(aDoclist, &p);
  108537. *pnList = (int)(pSave - p);
  108538. }
  108539. *ppIter = p;
  108540. }
  108541. }
  108542. /*
  108543. ** Iterate forwards through a doclist.
  108544. */
  108545. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  108546. int bDescIdx, /* True if the doclist is desc */
  108547. char *aDoclist, /* Pointer to entire doclist */
  108548. int nDoclist, /* Length of aDoclist in bytes */
  108549. char **ppIter, /* IN/OUT: Iterator pointer */
  108550. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  108551. u8 *pbEof /* OUT: End-of-file flag */
  108552. ){
  108553. char *p = *ppIter;
  108554. assert( nDoclist>0 );
  108555. assert( *pbEof==0 );
  108556. assert( p || *piDocid==0 );
  108557. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  108558. if( p==0 ){
  108559. p = aDoclist;
  108560. p += sqlite3Fts3GetVarint(p, piDocid);
  108561. }else{
  108562. fts3PoslistCopy(0, &p);
  108563. if( p>=&aDoclist[nDoclist] ){
  108564. *pbEof = 1;
  108565. }else{
  108566. sqlite3_int64 iVar;
  108567. p += sqlite3Fts3GetVarint(p, &iVar);
  108568. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  108569. }
  108570. }
  108571. *ppIter = p;
  108572. }
  108573. /*
  108574. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  108575. ** to true if EOF is reached.
  108576. */
  108577. static void fts3EvalDlPhraseNext(
  108578. Fts3Table *pTab,
  108579. Fts3Doclist *pDL,
  108580. u8 *pbEof
  108581. ){
  108582. char *pIter; /* Used to iterate through aAll */
  108583. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  108584. if( pDL->pNextDocid ){
  108585. pIter = pDL->pNextDocid;
  108586. }else{
  108587. pIter = pDL->aAll;
  108588. }
  108589. if( pIter>=pEnd ){
  108590. /* We have already reached the end of this doclist. EOF. */
  108591. *pbEof = 1;
  108592. }else{
  108593. sqlite3_int64 iDelta;
  108594. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  108595. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  108596. pDL->iDocid += iDelta;
  108597. }else{
  108598. pDL->iDocid -= iDelta;
  108599. }
  108600. pDL->pList = pIter;
  108601. fts3PoslistCopy(0, &pIter);
  108602. pDL->nList = (int)(pIter - pDL->pList);
  108603. /* pIter now points just past the 0x00 that terminates the position-
  108604. ** list for document pDL->iDocid. However, if this position-list was
  108605. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  108606. ** point to the start of the next docid value. The following line deals
  108607. ** with this case by advancing pIter past the zero-padding added by
  108608. ** fts3EvalNearTrim(). */
  108609. while( pIter<pEnd && *pIter==0 ) pIter++;
  108610. pDL->pNextDocid = pIter;
  108611. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  108612. *pbEof = 0;
  108613. }
  108614. }
  108615. /*
  108616. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  108617. */
  108618. typedef struct TokenDoclist TokenDoclist;
  108619. struct TokenDoclist {
  108620. int bIgnore;
  108621. sqlite3_int64 iDocid;
  108622. char *pList;
  108623. int nList;
  108624. };
  108625. /*
  108626. ** Token pToken is an incrementally loaded token that is part of a
  108627. ** multi-token phrase. Advance it to the next matching document in the
  108628. ** database and populate output variable *p with the details of the new
  108629. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  108630. **
  108631. ** If an error occurs, return an SQLite error code. Otherwise, return
  108632. ** SQLITE_OK.
  108633. */
  108634. static int incrPhraseTokenNext(
  108635. Fts3Table *pTab, /* Virtual table handle */
  108636. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  108637. int iToken, /* Specific token to advance */
  108638. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  108639. u8 *pbEof /* OUT: True if iterator is at EOF */
  108640. ){
  108641. int rc = SQLITE_OK;
  108642. if( pPhrase->iDoclistToken==iToken ){
  108643. assert( p->bIgnore==0 );
  108644. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  108645. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  108646. p->pList = pPhrase->doclist.pList;
  108647. p->nList = pPhrase->doclist.nList;
  108648. p->iDocid = pPhrase->doclist.iDocid;
  108649. }else{
  108650. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  108651. assert( pToken->pDeferred==0 );
  108652. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  108653. if( pToken->pSegcsr ){
  108654. assert( p->bIgnore==0 );
  108655. rc = sqlite3Fts3MsrIncrNext(
  108656. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  108657. );
  108658. if( p->pList==0 ) *pbEof = 1;
  108659. }else{
  108660. p->bIgnore = 1;
  108661. }
  108662. }
  108663. return rc;
  108664. }
  108665. /*
  108666. ** The phrase iterator passed as the second argument:
  108667. **
  108668. ** * features at least one token that uses an incremental doclist, and
  108669. **
  108670. ** * does not contain any deferred tokens.
  108671. **
  108672. ** Advance it to the next matching documnent in the database and populate
  108673. ** the Fts3Doclist.pList and nList fields.
  108674. **
  108675. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  108676. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  108677. ** successfully advanced, *pbEof is set to 0.
  108678. **
  108679. ** If an error occurs, return an SQLite error code. Otherwise, return
  108680. ** SQLITE_OK.
  108681. */
  108682. static int fts3EvalIncrPhraseNext(
  108683. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108684. Fts3Phrase *p, /* Phrase object to advance to next docid */
  108685. u8 *pbEof /* OUT: Set to 1 if EOF */
  108686. ){
  108687. int rc = SQLITE_OK;
  108688. Fts3Doclist *pDL = &p->doclist;
  108689. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108690. u8 bEof = 0;
  108691. /* This is only called if it is guaranteed that the phrase has at least
  108692. ** one incremental token. In which case the bIncr flag is set. */
  108693. assert( p->bIncr==1 );
  108694. if( p->nToken==1 && p->bIncr ){
  108695. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  108696. &pDL->iDocid, &pDL->pList, &pDL->nList
  108697. );
  108698. if( pDL->pList==0 ) bEof = 1;
  108699. }else{
  108700. int bDescDoclist = pCsr->bDesc;
  108701. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  108702. memset(a, 0, sizeof(a));
  108703. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  108704. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  108705. while( bEof==0 ){
  108706. int bMaxSet = 0;
  108707. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  108708. int i; /* Used to iterate through tokens */
  108709. /* Advance the iterator for each token in the phrase once. */
  108710. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  108711. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  108712. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  108713. iMax = a[i].iDocid;
  108714. bMaxSet = 1;
  108715. }
  108716. }
  108717. assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
  108718. assert( rc!=SQLITE_OK || bMaxSet );
  108719. /* Keep advancing iterators until they all point to the same document */
  108720. for(i=0; i<p->nToken; i++){
  108721. while( rc==SQLITE_OK && bEof==0
  108722. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  108723. ){
  108724. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  108725. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  108726. iMax = a[i].iDocid;
  108727. i = 0;
  108728. }
  108729. }
  108730. }
  108731. /* Check if the current entries really are a phrase match */
  108732. if( bEof==0 ){
  108733. int nList = 0;
  108734. int nByte = a[p->nToken-1].nList;
  108735. char *aDoclist = sqlite3_malloc(nByte+1);
  108736. if( !aDoclist ) return SQLITE_NOMEM;
  108737. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  108738. for(i=0; i<(p->nToken-1); i++){
  108739. if( a[i].bIgnore==0 ){
  108740. char *pL = a[i].pList;
  108741. char *pR = aDoclist;
  108742. char *pOut = aDoclist;
  108743. int nDist = p->nToken-1-i;
  108744. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  108745. if( res==0 ) break;
  108746. nList = (int)(pOut - aDoclist);
  108747. }
  108748. }
  108749. if( i==(p->nToken-1) ){
  108750. pDL->iDocid = iMax;
  108751. pDL->pList = aDoclist;
  108752. pDL->nList = nList;
  108753. pDL->bFreeList = 1;
  108754. break;
  108755. }
  108756. sqlite3_free(aDoclist);
  108757. }
  108758. }
  108759. }
  108760. *pbEof = bEof;
  108761. return rc;
  108762. }
  108763. /*
  108764. ** Attempt to move the phrase iterator to point to the next matching docid.
  108765. ** If an error occurs, return an SQLite error code. Otherwise, return
  108766. ** SQLITE_OK.
  108767. **
  108768. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  108769. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  108770. ** successfully advanced, *pbEof is set to 0.
  108771. */
  108772. static int fts3EvalPhraseNext(
  108773. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108774. Fts3Phrase *p, /* Phrase object to advance to next docid */
  108775. u8 *pbEof /* OUT: Set to 1 if EOF */
  108776. ){
  108777. int rc = SQLITE_OK;
  108778. Fts3Doclist *pDL = &p->doclist;
  108779. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108780. if( p->bIncr ){
  108781. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  108782. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  108783. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  108784. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  108785. );
  108786. pDL->pList = pDL->pNextDocid;
  108787. }else{
  108788. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  108789. }
  108790. return rc;
  108791. }
  108792. /*
  108793. **
  108794. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  108795. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  108796. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  108797. ** expressions for which all descendent tokens are deferred.
  108798. **
  108799. ** If parameter bOptOk is zero, then it is guaranteed that the
  108800. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  108801. ** each phrase in the expression (subject to deferred token processing).
  108802. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  108803. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  108804. **
  108805. ** If an error occurs within this function, *pRc is set to an SQLite error
  108806. ** code before returning.
  108807. */
  108808. static void fts3EvalStartReaders(
  108809. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108810. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  108811. int *pRc /* IN/OUT: Error code */
  108812. ){
  108813. if( pExpr && SQLITE_OK==*pRc ){
  108814. if( pExpr->eType==FTSQUERY_PHRASE ){
  108815. int i;
  108816. int nToken = pExpr->pPhrase->nToken;
  108817. for(i=0; i<nToken; i++){
  108818. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  108819. }
  108820. pExpr->bDeferred = (i==nToken);
  108821. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  108822. }else{
  108823. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  108824. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  108825. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  108826. }
  108827. }
  108828. }
  108829. /*
  108830. ** An array of the following structures is assembled as part of the process
  108831. ** of selecting tokens to defer before the query starts executing (as part
  108832. ** of the xFilter() method). There is one element in the array for each
  108833. ** token in the FTS expression.
  108834. **
  108835. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  108836. ** to phrases that are connected only by AND and NEAR operators (not OR or
  108837. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  108838. ** separately. The root of a tokens AND/NEAR cluster is stored in
  108839. ** Fts3TokenAndCost.pRoot.
  108840. */
  108841. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  108842. struct Fts3TokenAndCost {
  108843. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  108844. int iToken; /* Position of token in phrase */
  108845. Fts3PhraseToken *pToken; /* The token itself */
  108846. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  108847. int nOvfl; /* Number of overflow pages to load doclist */
  108848. int iCol; /* The column the token must match */
  108849. };
  108850. /*
  108851. ** This function is used to populate an allocated Fts3TokenAndCost array.
  108852. **
  108853. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  108854. ** Otherwise, if an error occurs during execution, *pRc is set to an
  108855. ** SQLite error code.
  108856. */
  108857. static void fts3EvalTokenCosts(
  108858. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108859. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  108860. Fts3Expr *pExpr, /* Expression to consider */
  108861. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  108862. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  108863. int *pRc /* IN/OUT: Error code */
  108864. ){
  108865. if( *pRc==SQLITE_OK ){
  108866. if( pExpr->eType==FTSQUERY_PHRASE ){
  108867. Fts3Phrase *pPhrase = pExpr->pPhrase;
  108868. int i;
  108869. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  108870. Fts3TokenAndCost *pTC = (*ppTC)++;
  108871. pTC->pPhrase = pPhrase;
  108872. pTC->iToken = i;
  108873. pTC->pRoot = pRoot;
  108874. pTC->pToken = &pPhrase->aToken[i];
  108875. pTC->iCol = pPhrase->iColumn;
  108876. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  108877. }
  108878. }else if( pExpr->eType!=FTSQUERY_NOT ){
  108879. assert( pExpr->eType==FTSQUERY_OR
  108880. || pExpr->eType==FTSQUERY_AND
  108881. || pExpr->eType==FTSQUERY_NEAR
  108882. );
  108883. assert( pExpr->pLeft && pExpr->pRight );
  108884. if( pExpr->eType==FTSQUERY_OR ){
  108885. pRoot = pExpr->pLeft;
  108886. **ppOr = pRoot;
  108887. (*ppOr)++;
  108888. }
  108889. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  108890. if( pExpr->eType==FTSQUERY_OR ){
  108891. pRoot = pExpr->pRight;
  108892. **ppOr = pRoot;
  108893. (*ppOr)++;
  108894. }
  108895. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  108896. }
  108897. }
  108898. }
  108899. /*
  108900. ** Determine the average document (row) size in pages. If successful,
  108901. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  108902. ** an SQLite error code.
  108903. **
  108904. ** The average document size in pages is calculated by first calculating
  108905. ** determining the average size in bytes, B. If B is less than the amount
  108906. ** of data that will fit on a single leaf page of an intkey table in
  108907. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  108908. ** the number of overflow pages consumed by a record B bytes in size.
  108909. */
  108910. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  108911. if( pCsr->nRowAvg==0 ){
  108912. /* The average document size, which is required to calculate the cost
  108913. ** of each doclist, has not yet been determined. Read the required
  108914. ** data from the %_stat table to calculate it.
  108915. **
  108916. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  108917. ** varints, where nCol is the number of columns in the FTS3 table.
  108918. ** The first varint is the number of documents currently stored in
  108919. ** the table. The following nCol varints contain the total amount of
  108920. ** data stored in all rows of each column of the table, from left
  108921. ** to right.
  108922. */
  108923. int rc;
  108924. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  108925. sqlite3_stmt *pStmt;
  108926. sqlite3_int64 nDoc = 0;
  108927. sqlite3_int64 nByte = 0;
  108928. const char *pEnd;
  108929. const char *a;
  108930. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  108931. if( rc!=SQLITE_OK ) return rc;
  108932. a = sqlite3_column_blob(pStmt, 0);
  108933. assert( a );
  108934. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  108935. a += sqlite3Fts3GetVarint(a, &nDoc);
  108936. while( a<pEnd ){
  108937. a += sqlite3Fts3GetVarint(a, &nByte);
  108938. }
  108939. if( nDoc==0 || nByte==0 ){
  108940. sqlite3_reset(pStmt);
  108941. return FTS_CORRUPT_VTAB;
  108942. }
  108943. pCsr->nDoc = nDoc;
  108944. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  108945. assert( pCsr->nRowAvg>0 );
  108946. rc = sqlite3_reset(pStmt);
  108947. if( rc!=SQLITE_OK ) return rc;
  108948. }
  108949. *pnPage = pCsr->nRowAvg;
  108950. return SQLITE_OK;
  108951. }
  108952. /*
  108953. ** This function is called to select the tokens (if any) that will be
  108954. ** deferred. The array aTC[] has already been populated when this is
  108955. ** called.
  108956. **
  108957. ** This function is called once for each AND/NEAR cluster in the
  108958. ** expression. Each invocation determines which tokens to defer within
  108959. ** the cluster with root node pRoot. See comments above the definition
  108960. ** of struct Fts3TokenAndCost for more details.
  108961. **
  108962. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  108963. ** called on each token to defer. Otherwise, an SQLite error code is
  108964. ** returned.
  108965. */
  108966. static int fts3EvalSelectDeferred(
  108967. Fts3Cursor *pCsr, /* FTS Cursor handle */
  108968. Fts3Expr *pRoot, /* Consider tokens with this root node */
  108969. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  108970. int nTC /* Number of entries in aTC[] */
  108971. ){
  108972. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  108973. int nDocSize = 0; /* Number of pages per doc loaded */
  108974. int rc = SQLITE_OK; /* Return code */
  108975. int ii; /* Iterator variable for various purposes */
  108976. int nOvfl = 0; /* Total overflow pages used by doclists */
  108977. int nToken = 0; /* Total number of tokens in cluster */
  108978. int nMinEst = 0; /* The minimum count for any phrase so far. */
  108979. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  108980. /* Tokens are never deferred for FTS tables created using the content=xxx
  108981. ** option. The reason being that it is not guaranteed that the content
  108982. ** table actually contains the same data as the index. To prevent this from
  108983. ** causing any problems, the deferred token optimization is completely
  108984. ** disabled for content=xxx tables. */
  108985. if( pTab->zContentTbl ){
  108986. return SQLITE_OK;
  108987. }
  108988. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  108989. ** associated with the tokens spill onto overflow pages, or if there is
  108990. ** only 1 token, exit early. No tokens to defer in this case. */
  108991. for(ii=0; ii<nTC; ii++){
  108992. if( aTC[ii].pRoot==pRoot ){
  108993. nOvfl += aTC[ii].nOvfl;
  108994. nToken++;
  108995. }
  108996. }
  108997. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  108998. /* Obtain the average docsize (in pages). */
  108999. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  109000. assert( rc!=SQLITE_OK || nDocSize>0 );
  109001. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  109002. ** of the number of overflow pages that will be loaded by the pager layer
  109003. ** to retrieve the entire doclist for the token from the full-text index.
  109004. ** Load the doclists for tokens that are either:
  109005. **
  109006. ** a. The cheapest token in the entire query (i.e. the one visited by the
  109007. ** first iteration of this loop), or
  109008. **
  109009. ** b. Part of a multi-token phrase.
  109010. **
  109011. ** After each token doclist is loaded, merge it with the others from the
  109012. ** same phrase and count the number of documents that the merged doclist
  109013. ** contains. Set variable "nMinEst" to the smallest number of documents in
  109014. ** any phrase doclist for which 1 or more token doclists have been loaded.
  109015. ** Let nOther be the number of other phrases for which it is certain that
  109016. ** one or more tokens will not be deferred.
  109017. **
  109018. ** Then, for each token, defer it if loading the doclist would result in
  109019. ** loading N or more overflow pages into memory, where N is computed as:
  109020. **
  109021. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  109022. */
  109023. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  109024. int iTC; /* Used to iterate through aTC[] array. */
  109025. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  109026. /* Set pTC to point to the cheapest remaining token. */
  109027. for(iTC=0; iTC<nTC; iTC++){
  109028. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  109029. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  109030. ){
  109031. pTC = &aTC[iTC];
  109032. }
  109033. }
  109034. assert( pTC );
  109035. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  109036. /* The number of overflow pages to load for this (and therefore all
  109037. ** subsequent) tokens is greater than the estimated number of pages
  109038. ** that will be loaded if all subsequent tokens are deferred.
  109039. */
  109040. Fts3PhraseToken *pToken = pTC->pToken;
  109041. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  109042. fts3SegReaderCursorFree(pToken->pSegcsr);
  109043. pToken->pSegcsr = 0;
  109044. }else{
  109045. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  109046. ** for-loop. Except, limit the value to 2^24 to prevent it from
  109047. ** overflowing the 32-bit integer it is stored in. */
  109048. if( ii<12 ) nLoad4 = nLoad4*4;
  109049. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  109050. /* Either this is the cheapest token in the entire query, or it is
  109051. ** part of a multi-token phrase. Either way, the entire doclist will
  109052. ** (eventually) be loaded into memory. It may as well be now. */
  109053. Fts3PhraseToken *pToken = pTC->pToken;
  109054. int nList = 0;
  109055. char *pList = 0;
  109056. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  109057. assert( rc==SQLITE_OK || pList==0 );
  109058. if( rc==SQLITE_OK ){
  109059. int nCount;
  109060. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  109061. nCount = fts3DoclistCountDocids(
  109062. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  109063. );
  109064. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  109065. }
  109066. }
  109067. }
  109068. pTC->pToken = 0;
  109069. }
  109070. return rc;
  109071. }
  109072. /*
  109073. ** This function is called from within the xFilter method. It initializes
  109074. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  109075. ** the results of a query, the caller does:
  109076. **
  109077. ** fts3EvalStart(pCsr);
  109078. ** while( 1 ){
  109079. ** fts3EvalNext(pCsr);
  109080. ** if( pCsr->bEof ) break;
  109081. ** ... return row pCsr->iPrevId to the caller ...
  109082. ** }
  109083. */
  109084. static int fts3EvalStart(Fts3Cursor *pCsr){
  109085. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109086. int rc = SQLITE_OK;
  109087. int nToken = 0;
  109088. int nOr = 0;
  109089. /* Allocate a MultiSegReader for each token in the expression. */
  109090. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  109091. /* Determine which, if any, tokens in the expression should be deferred. */
  109092. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  109093. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  109094. Fts3TokenAndCost *aTC;
  109095. Fts3Expr **apOr;
  109096. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  109097. sizeof(Fts3TokenAndCost) * nToken
  109098. + sizeof(Fts3Expr *) * nOr * 2
  109099. );
  109100. apOr = (Fts3Expr **)&aTC[nToken];
  109101. if( !aTC ){
  109102. rc = SQLITE_NOMEM;
  109103. }else{
  109104. int ii;
  109105. Fts3TokenAndCost *pTC = aTC;
  109106. Fts3Expr **ppOr = apOr;
  109107. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  109108. nToken = (int)(pTC-aTC);
  109109. nOr = (int)(ppOr-apOr);
  109110. if( rc==SQLITE_OK ){
  109111. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  109112. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  109113. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  109114. }
  109115. }
  109116. sqlite3_free(aTC);
  109117. }
  109118. }
  109119. #endif
  109120. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  109121. return rc;
  109122. }
  109123. /*
  109124. ** Invalidate the current position list for phrase pPhrase.
  109125. */
  109126. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  109127. if( pPhrase->doclist.bFreeList ){
  109128. sqlite3_free(pPhrase->doclist.pList);
  109129. }
  109130. pPhrase->doclist.pList = 0;
  109131. pPhrase->doclist.nList = 0;
  109132. pPhrase->doclist.bFreeList = 0;
  109133. }
  109134. /*
  109135. ** This function is called to edit the position list associated with
  109136. ** the phrase object passed as the fifth argument according to a NEAR
  109137. ** condition. For example:
  109138. **
  109139. ** abc NEAR/5 "def ghi"
  109140. **
  109141. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  109142. ** the example above). When this function is called, *paPoslist points to
  109143. ** the position list, and *pnToken is the number of phrase tokens in, the
  109144. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  109145. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  109146. ** the position list associated with phrase "abc".
  109147. **
  109148. ** All positions in the pPhrase position list that are not sufficiently
  109149. ** close to a position in the *paPoslist position list are removed. If this
  109150. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  109151. **
  109152. ** Before returning, *paPoslist is set to point to the position lsit
  109153. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  109154. ** pPhrase.
  109155. */
  109156. static int fts3EvalNearTrim(
  109157. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  109158. char *aTmp, /* Temporary space to use */
  109159. char **paPoslist, /* IN/OUT: Position list */
  109160. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  109161. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  109162. ){
  109163. int nParam1 = nNear + pPhrase->nToken;
  109164. int nParam2 = nNear + *pnToken;
  109165. int nNew;
  109166. char *p2;
  109167. char *pOut;
  109168. int res;
  109169. assert( pPhrase->doclist.pList );
  109170. p2 = pOut = pPhrase->doclist.pList;
  109171. res = fts3PoslistNearMerge(
  109172. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  109173. );
  109174. if( res ){
  109175. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  109176. assert( pPhrase->doclist.pList[nNew]=='\0' );
  109177. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  109178. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  109179. pPhrase->doclist.nList = nNew;
  109180. *paPoslist = pPhrase->doclist.pList;
  109181. *pnToken = pPhrase->nToken;
  109182. }
  109183. return res;
  109184. }
  109185. /*
  109186. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  109187. ** Otherwise, it advances the expression passed as the second argument to
  109188. ** point to the next matching row in the database. Expressions iterate through
  109189. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  109190. ** or descending if it is non-zero.
  109191. **
  109192. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  109193. ** successful, the following variables in pExpr are set:
  109194. **
  109195. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  109196. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  109197. **
  109198. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  109199. ** at EOF, then the following variables are populated with the position list
  109200. ** for the phrase for the visited row:
  109201. **
  109202. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  109203. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  109204. **
  109205. ** It says above that this function advances the expression to the next
  109206. ** matching row. This is usually true, but there are the following exceptions:
  109207. **
  109208. ** 1. Deferred tokens are not taken into account. If a phrase consists
  109209. ** entirely of deferred tokens, it is assumed to match every row in
  109210. ** the db. In this case the position-list is not populated at all.
  109211. **
  109212. ** Or, if a phrase contains one or more deferred tokens and one or
  109213. ** more non-deferred tokens, then the expression is advanced to the
  109214. ** next possible match, considering only non-deferred tokens. In other
  109215. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  109216. ** is advanced to the next row that contains an instance of "A * C",
  109217. ** where "*" may match any single token. The position list in this case
  109218. ** is populated as for "A * C" before returning.
  109219. **
  109220. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  109221. ** advanced to point to the next row that matches "x AND y".
  109222. **
  109223. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  109224. ** really a match, taking into account deferred tokens and NEAR operators.
  109225. */
  109226. static void fts3EvalNextRow(
  109227. Fts3Cursor *pCsr, /* FTS Cursor handle */
  109228. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  109229. int *pRc /* IN/OUT: Error code */
  109230. ){
  109231. if( *pRc==SQLITE_OK ){
  109232. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  109233. assert( pExpr->bEof==0 );
  109234. pExpr->bStart = 1;
  109235. switch( pExpr->eType ){
  109236. case FTSQUERY_NEAR:
  109237. case FTSQUERY_AND: {
  109238. Fts3Expr *pLeft = pExpr->pLeft;
  109239. Fts3Expr *pRight = pExpr->pRight;
  109240. assert( !pLeft->bDeferred || !pRight->bDeferred );
  109241. if( pLeft->bDeferred ){
  109242. /* LHS is entirely deferred. So we assume it matches every row.
  109243. ** Advance the RHS iterator to find the next row visited. */
  109244. fts3EvalNextRow(pCsr, pRight, pRc);
  109245. pExpr->iDocid = pRight->iDocid;
  109246. pExpr->bEof = pRight->bEof;
  109247. }else if( pRight->bDeferred ){
  109248. /* RHS is entirely deferred. So we assume it matches every row.
  109249. ** Advance the LHS iterator to find the next row visited. */
  109250. fts3EvalNextRow(pCsr, pLeft, pRc);
  109251. pExpr->iDocid = pLeft->iDocid;
  109252. pExpr->bEof = pLeft->bEof;
  109253. }else{
  109254. /* Neither the RHS or LHS are deferred. */
  109255. fts3EvalNextRow(pCsr, pLeft, pRc);
  109256. fts3EvalNextRow(pCsr, pRight, pRc);
  109257. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  109258. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109259. if( iDiff==0 ) break;
  109260. if( iDiff<0 ){
  109261. fts3EvalNextRow(pCsr, pLeft, pRc);
  109262. }else{
  109263. fts3EvalNextRow(pCsr, pRight, pRc);
  109264. }
  109265. }
  109266. pExpr->iDocid = pLeft->iDocid;
  109267. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  109268. }
  109269. break;
  109270. }
  109271. case FTSQUERY_OR: {
  109272. Fts3Expr *pLeft = pExpr->pLeft;
  109273. Fts3Expr *pRight = pExpr->pRight;
  109274. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109275. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  109276. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  109277. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  109278. fts3EvalNextRow(pCsr, pLeft, pRc);
  109279. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  109280. fts3EvalNextRow(pCsr, pRight, pRc);
  109281. }else{
  109282. fts3EvalNextRow(pCsr, pLeft, pRc);
  109283. fts3EvalNextRow(pCsr, pRight, pRc);
  109284. }
  109285. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  109286. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  109287. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  109288. pExpr->iDocid = pLeft->iDocid;
  109289. }else{
  109290. pExpr->iDocid = pRight->iDocid;
  109291. }
  109292. break;
  109293. }
  109294. case FTSQUERY_NOT: {
  109295. Fts3Expr *pLeft = pExpr->pLeft;
  109296. Fts3Expr *pRight = pExpr->pRight;
  109297. if( pRight->bStart==0 ){
  109298. fts3EvalNextRow(pCsr, pRight, pRc);
  109299. assert( *pRc!=SQLITE_OK || pRight->bStart );
  109300. }
  109301. fts3EvalNextRow(pCsr, pLeft, pRc);
  109302. if( pLeft->bEof==0 ){
  109303. while( !*pRc
  109304. && !pRight->bEof
  109305. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  109306. ){
  109307. fts3EvalNextRow(pCsr, pRight, pRc);
  109308. }
  109309. }
  109310. pExpr->iDocid = pLeft->iDocid;
  109311. pExpr->bEof = pLeft->bEof;
  109312. break;
  109313. }
  109314. default: {
  109315. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109316. fts3EvalInvalidatePoslist(pPhrase);
  109317. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  109318. pExpr->iDocid = pPhrase->doclist.iDocid;
  109319. break;
  109320. }
  109321. }
  109322. }
  109323. }
  109324. /*
  109325. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  109326. ** cluster, then this function returns 1 immediately.
  109327. **
  109328. ** Otherwise, it checks if the current row really does match the NEAR
  109329. ** expression, using the data currently stored in the position lists
  109330. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  109331. **
  109332. ** If the current row is a match, the position list associated with each
  109333. ** phrase in the NEAR expression is edited in place to contain only those
  109334. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  109335. ** constraints. In this case it returns 1. If the NEAR expression does not
  109336. ** match the current row, 0 is returned. The position lists may or may not
  109337. ** be edited if 0 is returned.
  109338. */
  109339. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  109340. int res = 1;
  109341. /* The following block runs if pExpr is the root of a NEAR query.
  109342. ** For example, the query:
  109343. **
  109344. ** "w" NEAR "x" NEAR "y" NEAR "z"
  109345. **
  109346. ** which is represented in tree form as:
  109347. **
  109348. ** |
  109349. ** +--NEAR--+ <-- root of NEAR query
  109350. ** | |
  109351. ** +--NEAR--+ "z"
  109352. ** | |
  109353. ** +--NEAR--+ "y"
  109354. ** | |
  109355. ** "w" "x"
  109356. **
  109357. ** The right-hand child of a NEAR node is always a phrase. The
  109358. ** left-hand child may be either a phrase or a NEAR node. There are
  109359. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  109360. */
  109361. if( *pRc==SQLITE_OK
  109362. && pExpr->eType==FTSQUERY_NEAR
  109363. && pExpr->bEof==0
  109364. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  109365. ){
  109366. Fts3Expr *p;
  109367. int nTmp = 0; /* Bytes of temp space */
  109368. char *aTmp; /* Temp space for PoslistNearMerge() */
  109369. /* Allocate temporary working space. */
  109370. for(p=pExpr; p->pLeft; p=p->pLeft){
  109371. nTmp += p->pRight->pPhrase->doclist.nList;
  109372. }
  109373. nTmp += p->pPhrase->doclist.nList;
  109374. if( nTmp==0 ){
  109375. res = 0;
  109376. }else{
  109377. aTmp = sqlite3_malloc(nTmp*2);
  109378. if( !aTmp ){
  109379. *pRc = SQLITE_NOMEM;
  109380. res = 0;
  109381. }else{
  109382. char *aPoslist = p->pPhrase->doclist.pList;
  109383. int nToken = p->pPhrase->nToken;
  109384. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  109385. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  109386. int nNear = p->nNear;
  109387. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  109388. }
  109389. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  109390. nToken = pExpr->pRight->pPhrase->nToken;
  109391. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  109392. int nNear;
  109393. Fts3Phrase *pPhrase;
  109394. assert( p->pParent && p->pParent->pLeft==p );
  109395. nNear = p->pParent->nNear;
  109396. pPhrase = (
  109397. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  109398. );
  109399. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  109400. }
  109401. }
  109402. sqlite3_free(aTmp);
  109403. }
  109404. }
  109405. return res;
  109406. }
  109407. /*
  109408. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  109409. ** Assuming no error occurs or has occurred, It returns non-zero if the
  109410. ** expression passed as the second argument matches the row that pCsr
  109411. ** currently points to, or zero if it does not.
  109412. **
  109413. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  109414. ** If an error occurs during execution of this function, *pRc is set to
  109415. ** the appropriate SQLite error code. In this case the returned value is
  109416. ** undefined.
  109417. */
  109418. static int fts3EvalTestExpr(
  109419. Fts3Cursor *pCsr, /* FTS cursor handle */
  109420. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  109421. int *pRc /* IN/OUT: Error code */
  109422. ){
  109423. int bHit = 1; /* Return value */
  109424. if( *pRc==SQLITE_OK ){
  109425. switch( pExpr->eType ){
  109426. case FTSQUERY_NEAR:
  109427. case FTSQUERY_AND:
  109428. bHit = (
  109429. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  109430. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  109431. && fts3EvalNearTest(pExpr, pRc)
  109432. );
  109433. /* If the NEAR expression does not match any rows, zero the doclist for
  109434. ** all phrases involved in the NEAR. This is because the snippet(),
  109435. ** offsets() and matchinfo() functions are not supposed to recognize
  109436. ** any instances of phrases that are part of unmatched NEAR queries.
  109437. ** For example if this expression:
  109438. **
  109439. ** ... MATCH 'a OR (b NEAR c)'
  109440. **
  109441. ** is matched against a row containing:
  109442. **
  109443. ** 'a b d e'
  109444. **
  109445. ** then any snippet() should ony highlight the "a" term, not the "b"
  109446. ** (as "b" is part of a non-matching NEAR clause).
  109447. */
  109448. if( bHit==0
  109449. && pExpr->eType==FTSQUERY_NEAR
  109450. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  109451. ){
  109452. Fts3Expr *p;
  109453. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  109454. if( p->pRight->iDocid==pCsr->iPrevId ){
  109455. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  109456. }
  109457. }
  109458. if( p->iDocid==pCsr->iPrevId ){
  109459. fts3EvalInvalidatePoslist(p->pPhrase);
  109460. }
  109461. }
  109462. break;
  109463. case FTSQUERY_OR: {
  109464. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  109465. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  109466. bHit = bHit1 || bHit2;
  109467. break;
  109468. }
  109469. case FTSQUERY_NOT:
  109470. bHit = (
  109471. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  109472. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  109473. );
  109474. break;
  109475. default: {
  109476. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  109477. if( pCsr->pDeferred
  109478. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  109479. ){
  109480. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109481. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  109482. if( pExpr->bDeferred ){
  109483. fts3EvalInvalidatePoslist(pPhrase);
  109484. }
  109485. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  109486. bHit = (pPhrase->doclist.pList!=0);
  109487. pExpr->iDocid = pCsr->iPrevId;
  109488. }else
  109489. #endif
  109490. {
  109491. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  109492. }
  109493. break;
  109494. }
  109495. }
  109496. }
  109497. return bHit;
  109498. }
  109499. /*
  109500. ** This function is called as the second part of each xNext operation when
  109501. ** iterating through the results of a full-text query. At this point the
  109502. ** cursor points to a row that matches the query expression, with the
  109503. ** following caveats:
  109504. **
  109505. ** * Up until this point, "NEAR" operators in the expression have been
  109506. ** treated as "AND".
  109507. **
  109508. ** * Deferred tokens have not yet been considered.
  109509. **
  109510. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  109511. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  109512. ** operators and deferred tokens the current row is still a match for the
  109513. ** expression. It returns 1 if both of the following are true:
  109514. **
  109515. ** 1. *pRc is SQLITE_OK when this function returns, and
  109516. **
  109517. ** 2. After scanning the current FTS table row for the deferred tokens,
  109518. ** it is determined that the row does *not* match the query.
  109519. **
  109520. ** Or, if no error occurs and it seems the current row does match the FTS
  109521. ** query, return 0.
  109522. */
  109523. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  109524. int rc = *pRc;
  109525. int bMiss = 0;
  109526. if( rc==SQLITE_OK ){
  109527. /* If there are one or more deferred tokens, load the current row into
  109528. ** memory and scan it to determine the position list for each deferred
  109529. ** token. Then, see if this row is really a match, considering deferred
  109530. ** tokens and NEAR operators (neither of which were taken into account
  109531. ** earlier, by fts3EvalNextRow()).
  109532. */
  109533. if( pCsr->pDeferred ){
  109534. rc = fts3CursorSeek(0, pCsr);
  109535. if( rc==SQLITE_OK ){
  109536. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  109537. }
  109538. }
  109539. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  109540. /* Free the position-lists accumulated for each deferred token above. */
  109541. sqlite3Fts3FreeDeferredDoclists(pCsr);
  109542. *pRc = rc;
  109543. }
  109544. return (rc==SQLITE_OK && bMiss);
  109545. }
  109546. /*
  109547. ** Advance to the next document that matches the FTS expression in
  109548. ** Fts3Cursor.pExpr.
  109549. */
  109550. static int fts3EvalNext(Fts3Cursor *pCsr){
  109551. int rc = SQLITE_OK; /* Return Code */
  109552. Fts3Expr *pExpr = pCsr->pExpr;
  109553. assert( pCsr->isEof==0 );
  109554. if( pExpr==0 ){
  109555. pCsr->isEof = 1;
  109556. }else{
  109557. do {
  109558. if( pCsr->isRequireSeek==0 ){
  109559. sqlite3_reset(pCsr->pStmt);
  109560. }
  109561. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  109562. fts3EvalNextRow(pCsr, pExpr, &rc);
  109563. pCsr->isEof = pExpr->bEof;
  109564. pCsr->isRequireSeek = 1;
  109565. pCsr->isMatchinfoNeeded = 1;
  109566. pCsr->iPrevId = pExpr->iDocid;
  109567. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  109568. }
  109569. /* Check if the cursor is past the end of the docid range specified
  109570. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  109571. if( rc==SQLITE_OK && (
  109572. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  109573. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  109574. )){
  109575. pCsr->isEof = 1;
  109576. }
  109577. return rc;
  109578. }
  109579. /*
  109580. ** Restart interation for expression pExpr so that the next call to
  109581. ** fts3EvalNext() visits the first row. Do not allow incremental
  109582. ** loading or merging of phrase doclists for this iteration.
  109583. **
  109584. ** If *pRc is other than SQLITE_OK when this function is called, it is
  109585. ** a no-op. If an error occurs within this function, *pRc is set to an
  109586. ** SQLite error code before returning.
  109587. */
  109588. static void fts3EvalRestart(
  109589. Fts3Cursor *pCsr,
  109590. Fts3Expr *pExpr,
  109591. int *pRc
  109592. ){
  109593. if( pExpr && *pRc==SQLITE_OK ){
  109594. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109595. if( pPhrase ){
  109596. fts3EvalInvalidatePoslist(pPhrase);
  109597. if( pPhrase->bIncr ){
  109598. int i;
  109599. for(i=0; i<pPhrase->nToken; i++){
  109600. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  109601. assert( pToken->pDeferred==0 );
  109602. if( pToken->pSegcsr ){
  109603. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  109604. }
  109605. }
  109606. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  109607. }
  109608. pPhrase->doclist.pNextDocid = 0;
  109609. pPhrase->doclist.iDocid = 0;
  109610. }
  109611. pExpr->iDocid = 0;
  109612. pExpr->bEof = 0;
  109613. pExpr->bStart = 0;
  109614. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  109615. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  109616. }
  109617. }
  109618. /*
  109619. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  109620. ** expression rooted at pExpr, the cursor iterates through all rows matched
  109621. ** by pExpr, calling this function for each row. This function increments
  109622. ** the values in Fts3Expr.aMI[] according to the position-list currently
  109623. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  109624. ** expression nodes.
  109625. */
  109626. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  109627. if( pExpr ){
  109628. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109629. if( pPhrase && pPhrase->doclist.pList ){
  109630. int iCol = 0;
  109631. char *p = pPhrase->doclist.pList;
  109632. assert( *p );
  109633. while( 1 ){
  109634. u8 c = 0;
  109635. int iCnt = 0;
  109636. while( 0xFE & (*p | c) ){
  109637. if( (c&0x80)==0 ) iCnt++;
  109638. c = *p++ & 0x80;
  109639. }
  109640. /* aMI[iCol*3 + 1] = Number of occurrences
  109641. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  109642. */
  109643. pExpr->aMI[iCol*3 + 1] += iCnt;
  109644. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  109645. if( *p==0x00 ) break;
  109646. p++;
  109647. p += sqlite3Fts3GetVarint32(p, &iCol);
  109648. }
  109649. }
  109650. fts3EvalUpdateCounts(pExpr->pLeft);
  109651. fts3EvalUpdateCounts(pExpr->pRight);
  109652. }
  109653. }
  109654. /*
  109655. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  109656. **
  109657. ** If it is not already allocated and populated, this function allocates and
  109658. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  109659. ** of a NEAR expression, then it also allocates and populates the same array
  109660. ** for all other phrases that are part of the NEAR expression.
  109661. **
  109662. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  109663. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  109664. */
  109665. static int fts3EvalGatherStats(
  109666. Fts3Cursor *pCsr, /* Cursor object */
  109667. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  109668. ){
  109669. int rc = SQLITE_OK; /* Return code */
  109670. assert( pExpr->eType==FTSQUERY_PHRASE );
  109671. if( pExpr->aMI==0 ){
  109672. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109673. Fts3Expr *pRoot; /* Root of NEAR expression */
  109674. Fts3Expr *p; /* Iterator used for several purposes */
  109675. sqlite3_int64 iPrevId = pCsr->iPrevId;
  109676. sqlite3_int64 iDocid;
  109677. u8 bEof;
  109678. /* Find the root of the NEAR expression */
  109679. pRoot = pExpr;
  109680. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  109681. pRoot = pRoot->pParent;
  109682. }
  109683. iDocid = pRoot->iDocid;
  109684. bEof = pRoot->bEof;
  109685. assert( pRoot->bStart );
  109686. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  109687. for(p=pRoot; p; p=p->pLeft){
  109688. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  109689. assert( pE->aMI==0 );
  109690. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  109691. if( !pE->aMI ) return SQLITE_NOMEM;
  109692. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  109693. }
  109694. fts3EvalRestart(pCsr, pRoot, &rc);
  109695. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  109696. do {
  109697. /* Ensure the %_content statement is reset. */
  109698. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  109699. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  109700. /* Advance to the next document */
  109701. fts3EvalNextRow(pCsr, pRoot, &rc);
  109702. pCsr->isEof = pRoot->bEof;
  109703. pCsr->isRequireSeek = 1;
  109704. pCsr->isMatchinfoNeeded = 1;
  109705. pCsr->iPrevId = pRoot->iDocid;
  109706. }while( pCsr->isEof==0
  109707. && pRoot->eType==FTSQUERY_NEAR
  109708. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  109709. );
  109710. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  109711. fts3EvalUpdateCounts(pRoot);
  109712. }
  109713. }
  109714. pCsr->isEof = 0;
  109715. pCsr->iPrevId = iPrevId;
  109716. if( bEof ){
  109717. pRoot->bEof = bEof;
  109718. }else{
  109719. /* Caution: pRoot may iterate through docids in ascending or descending
  109720. ** order. For this reason, even though it seems more defensive, the
  109721. ** do loop can not be written:
  109722. **
  109723. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  109724. */
  109725. fts3EvalRestart(pCsr, pRoot, &rc);
  109726. do {
  109727. fts3EvalNextRow(pCsr, pRoot, &rc);
  109728. assert( pRoot->bEof==0 );
  109729. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  109730. fts3EvalTestDeferredAndNear(pCsr, &rc);
  109731. }
  109732. }
  109733. return rc;
  109734. }
  109735. /*
  109736. ** This function is used by the matchinfo() module to query a phrase
  109737. ** expression node for the following information:
  109738. **
  109739. ** 1. The total number of occurrences of the phrase in each column of
  109740. ** the FTS table (considering all rows), and
  109741. **
  109742. ** 2. For each column, the number of rows in the table for which the
  109743. ** column contains at least one instance of the phrase.
  109744. **
  109745. ** If no error occurs, SQLITE_OK is returned and the values for each column
  109746. ** written into the array aiOut as follows:
  109747. **
  109748. ** aiOut[iCol*3 + 1] = Number of occurrences
  109749. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  109750. **
  109751. ** Caveats:
  109752. **
  109753. ** * If a phrase consists entirely of deferred tokens, then all output
  109754. ** values are set to the number of documents in the table. In other
  109755. ** words we assume that very common tokens occur exactly once in each
  109756. ** column of each row of the table.
  109757. **
  109758. ** * If a phrase contains some deferred tokens (and some non-deferred
  109759. ** tokens), count the potential occurrence identified by considering
  109760. ** the non-deferred tokens instead of actual phrase occurrences.
  109761. **
  109762. ** * If the phrase is part of a NEAR expression, then only phrase instances
  109763. ** that meet the NEAR constraint are included in the counts.
  109764. */
  109765. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  109766. Fts3Cursor *pCsr, /* FTS cursor handle */
  109767. Fts3Expr *pExpr, /* Phrase expression */
  109768. u32 *aiOut /* Array to write results into (see above) */
  109769. ){
  109770. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109771. int rc = SQLITE_OK;
  109772. int iCol;
  109773. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  109774. assert( pCsr->nDoc>0 );
  109775. for(iCol=0; iCol<pTab->nColumn; iCol++){
  109776. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  109777. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  109778. }
  109779. }else{
  109780. rc = fts3EvalGatherStats(pCsr, pExpr);
  109781. if( rc==SQLITE_OK ){
  109782. assert( pExpr->aMI );
  109783. for(iCol=0; iCol<pTab->nColumn; iCol++){
  109784. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  109785. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  109786. }
  109787. }
  109788. }
  109789. return rc;
  109790. }
  109791. /*
  109792. ** The expression pExpr passed as the second argument to this function
  109793. ** must be of type FTSQUERY_PHRASE.
  109794. **
  109795. ** The returned value is either NULL or a pointer to a buffer containing
  109796. ** a position-list indicating the occurrences of the phrase in column iCol
  109797. ** of the current row.
  109798. **
  109799. ** More specifically, the returned buffer contains 1 varint for each
  109800. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  109801. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  109802. ** if the requested column contains "a b X c d X X" and the position-list
  109803. ** for 'X' is requested, the buffer returned may contain:
  109804. **
  109805. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  109806. **
  109807. ** This function works regardless of whether or not the phrase is deferred,
  109808. ** incremental, or neither.
  109809. */
  109810. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  109811. Fts3Cursor *pCsr, /* FTS3 cursor object */
  109812. Fts3Expr *pExpr, /* Phrase to return doclist for */
  109813. int iCol, /* Column to return position list for */
  109814. char **ppOut /* OUT: Pointer to position list */
  109815. ){
  109816. Fts3Phrase *pPhrase = pExpr->pPhrase;
  109817. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  109818. char *pIter;
  109819. int iThis;
  109820. sqlite3_int64 iDocid;
  109821. /* If this phrase is applies specifically to some column other than
  109822. ** column iCol, return a NULL pointer. */
  109823. *ppOut = 0;
  109824. assert( iCol>=0 && iCol<pTab->nColumn );
  109825. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  109826. return SQLITE_OK;
  109827. }
  109828. iDocid = pExpr->iDocid;
  109829. pIter = pPhrase->doclist.pList;
  109830. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  109831. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  109832. int iMul; /* +1 if csr dir matches index dir, else -1 */
  109833. int bOr = 0;
  109834. u8 bEof = 0;
  109835. u8 bTreeEof = 0;
  109836. Fts3Expr *p; /* Used to iterate from pExpr to root */
  109837. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  109838. /* Check if this phrase descends from an OR expression node. If not,
  109839. ** return NULL. Otherwise, the entry that corresponds to docid
  109840. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  109841. ** tree that the node is part of has been marked as EOF, but the node
  109842. ** itself is not EOF, then it may point to an earlier entry. */
  109843. pNear = pExpr;
  109844. for(p=pExpr->pParent; p; p=p->pParent){
  109845. if( p->eType==FTSQUERY_OR ) bOr = 1;
  109846. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  109847. if( p->bEof ) bTreeEof = 1;
  109848. }
  109849. if( bOr==0 ) return SQLITE_OK;
  109850. /* This is the descendent of an OR node. In this case we cannot use
  109851. ** an incremental phrase. Load the entire doclist for the phrase
  109852. ** into memory in this case. */
  109853. if( pPhrase->bIncr ){
  109854. int rc = SQLITE_OK;
  109855. int bEofSave = pExpr->bEof;
  109856. fts3EvalRestart(pCsr, pExpr, &rc);
  109857. while( rc==SQLITE_OK && !pExpr->bEof ){
  109858. fts3EvalNextRow(pCsr, pExpr, &rc);
  109859. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  109860. }
  109861. pIter = pPhrase->doclist.pList;
  109862. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  109863. if( rc!=SQLITE_OK ) return rc;
  109864. }
  109865. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  109866. while( bTreeEof==1
  109867. && pNear->bEof==0
  109868. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  109869. ){
  109870. int rc = SQLITE_OK;
  109871. fts3EvalNextRow(pCsr, pExpr, &rc);
  109872. if( rc!=SQLITE_OK ) return rc;
  109873. iDocid = pExpr->iDocid;
  109874. pIter = pPhrase->doclist.pList;
  109875. }
  109876. bEof = (pPhrase->doclist.nAll==0);
  109877. assert( bDescDoclist==0 || bDescDoclist==1 );
  109878. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  109879. if( bEof==0 ){
  109880. if( pCsr->bDesc==bDescDoclist ){
  109881. int dummy;
  109882. if( pNear->bEof ){
  109883. /* This expression is already at EOF. So position it to point to the
  109884. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  109885. ** iDocid is already set for this entry, so all that is required is
  109886. ** to set pIter to point to the first byte of the last position-list
  109887. ** in the doclist.
  109888. **
  109889. ** It would also be correct to set pIter and iDocid to zero. In
  109890. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  109891. ** would also move the iterator to point to the last entry in the
  109892. ** doclist. However, this is expensive, as to do so it has to
  109893. ** iterate through the entire doclist from start to finish (since
  109894. ** it does not know the docid for the last entry). */
  109895. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  109896. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  109897. }
  109898. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  109899. sqlite3Fts3DoclistPrev(
  109900. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  109901. &pIter, &iDocid, &dummy, &bEof
  109902. );
  109903. }
  109904. }else{
  109905. if( pNear->bEof ){
  109906. pIter = 0;
  109907. iDocid = 0;
  109908. }
  109909. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  109910. sqlite3Fts3DoclistNext(
  109911. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  109912. &pIter, &iDocid, &bEof
  109913. );
  109914. }
  109915. }
  109916. }
  109917. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  109918. }
  109919. if( pIter==0 ) return SQLITE_OK;
  109920. if( *pIter==0x01 ){
  109921. pIter++;
  109922. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  109923. }else{
  109924. iThis = 0;
  109925. }
  109926. while( iThis<iCol ){
  109927. fts3ColumnlistCopy(0, &pIter);
  109928. if( *pIter==0x00 ) return 0;
  109929. pIter++;
  109930. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  109931. }
  109932. *ppOut = ((iCol==iThis)?pIter:0);
  109933. return SQLITE_OK;
  109934. }
  109935. /*
  109936. ** Free all components of the Fts3Phrase structure that were allocated by
  109937. ** the eval module. Specifically, this means to free:
  109938. **
  109939. ** * the contents of pPhrase->doclist, and
  109940. ** * any Fts3MultiSegReader objects held by phrase tokens.
  109941. */
  109942. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  109943. if( pPhrase ){
  109944. int i;
  109945. sqlite3_free(pPhrase->doclist.aAll);
  109946. fts3EvalInvalidatePoslist(pPhrase);
  109947. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  109948. for(i=0; i<pPhrase->nToken; i++){
  109949. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  109950. pPhrase->aToken[i].pSegcsr = 0;
  109951. }
  109952. }
  109953. }
  109954. /*
  109955. ** Return SQLITE_CORRUPT_VTAB.
  109956. */
  109957. #ifdef SQLITE_DEBUG
  109958. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  109959. return SQLITE_CORRUPT_VTAB;
  109960. }
  109961. #endif
  109962. #if !SQLITE_CORE
  109963. /*
  109964. ** Initialize API pointer table, if required.
  109965. */
  109966. #ifdef _WIN32
  109967. __declspec(dllexport)
  109968. #endif
  109969. SQLITE_API int sqlite3_fts3_init(
  109970. sqlite3 *db,
  109971. char **pzErrMsg,
  109972. const sqlite3_api_routines *pApi
  109973. ){
  109974. SQLITE_EXTENSION_INIT2(pApi)
  109975. return sqlite3Fts3Init(db);
  109976. }
  109977. #endif
  109978. #endif
  109979. /************** End of fts3.c ************************************************/
  109980. /************** Begin file fts3_aux.c ****************************************/
  109981. /*
  109982. ** 2011 Jan 27
  109983. **
  109984. ** The author disclaims copyright to this source code. In place of
  109985. ** a legal notice, here is a blessing:
  109986. **
  109987. ** May you do good and not evil.
  109988. ** May you find forgiveness for yourself and forgive others.
  109989. ** May you share freely, never taking more than you give.
  109990. **
  109991. ******************************************************************************
  109992. **
  109993. */
  109994. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109995. /* #include <string.h> */
  109996. /* #include <assert.h> */
  109997. typedef struct Fts3auxTable Fts3auxTable;
  109998. typedef struct Fts3auxCursor Fts3auxCursor;
  109999. struct Fts3auxTable {
  110000. sqlite3_vtab base; /* Base class used by SQLite core */
  110001. Fts3Table *pFts3Tab;
  110002. };
  110003. struct Fts3auxCursor {
  110004. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  110005. Fts3MultiSegReader csr; /* Must be right after "base" */
  110006. Fts3SegFilter filter;
  110007. char *zStop;
  110008. int nStop; /* Byte-length of string zStop */
  110009. int iLangid; /* Language id to query */
  110010. int isEof; /* True if cursor is at EOF */
  110011. sqlite3_int64 iRowid; /* Current rowid */
  110012. int iCol; /* Current value of 'col' column */
  110013. int nStat; /* Size of aStat[] array */
  110014. struct Fts3auxColstats {
  110015. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  110016. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  110017. } *aStat;
  110018. };
  110019. /*
  110020. ** Schema of the terms table.
  110021. */
  110022. #define FTS3_AUX_SCHEMA \
  110023. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  110024. /*
  110025. ** This function does all the work for both the xConnect and xCreate methods.
  110026. ** These tables have no persistent representation of their own, so xConnect
  110027. ** and xCreate are identical operations.
  110028. */
  110029. static int fts3auxConnectMethod(
  110030. sqlite3 *db, /* Database connection */
  110031. void *pUnused, /* Unused */
  110032. int argc, /* Number of elements in argv array */
  110033. const char * const *argv, /* xCreate/xConnect argument array */
  110034. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  110035. char **pzErr /* OUT: sqlite3_malloc'd error message */
  110036. ){
  110037. char const *zDb; /* Name of database (e.g. "main") */
  110038. char const *zFts3; /* Name of fts3 table */
  110039. int nDb; /* Result of strlen(zDb) */
  110040. int nFts3; /* Result of strlen(zFts3) */
  110041. int nByte; /* Bytes of space to allocate here */
  110042. int rc; /* value returned by declare_vtab() */
  110043. Fts3auxTable *p; /* Virtual table object to return */
  110044. UNUSED_PARAMETER(pUnused);
  110045. /* The user should invoke this in one of two forms:
  110046. **
  110047. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  110048. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  110049. */
  110050. if( argc!=4 && argc!=5 ) goto bad_args;
  110051. zDb = argv[1];
  110052. nDb = (int)strlen(zDb);
  110053. if( argc==5 ){
  110054. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  110055. zDb = argv[3];
  110056. nDb = (int)strlen(zDb);
  110057. zFts3 = argv[4];
  110058. }else{
  110059. goto bad_args;
  110060. }
  110061. }else{
  110062. zFts3 = argv[3];
  110063. }
  110064. nFts3 = (int)strlen(zFts3);
  110065. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  110066. if( rc!=SQLITE_OK ) return rc;
  110067. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  110068. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  110069. if( !p ) return SQLITE_NOMEM;
  110070. memset(p, 0, nByte);
  110071. p->pFts3Tab = (Fts3Table *)&p[1];
  110072. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  110073. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  110074. p->pFts3Tab->db = db;
  110075. p->pFts3Tab->nIndex = 1;
  110076. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  110077. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  110078. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  110079. *ppVtab = (sqlite3_vtab *)p;
  110080. return SQLITE_OK;
  110081. bad_args:
  110082. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  110083. return SQLITE_ERROR;
  110084. }
  110085. /*
  110086. ** This function does the work for both the xDisconnect and xDestroy methods.
  110087. ** These tables have no persistent representation of their own, so xDisconnect
  110088. ** and xDestroy are identical operations.
  110089. */
  110090. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  110091. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  110092. Fts3Table *pFts3 = p->pFts3Tab;
  110093. int i;
  110094. /* Free any prepared statements held */
  110095. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  110096. sqlite3_finalize(pFts3->aStmt[i]);
  110097. }
  110098. sqlite3_free(pFts3->zSegmentsTbl);
  110099. sqlite3_free(p);
  110100. return SQLITE_OK;
  110101. }
  110102. #define FTS4AUX_EQ_CONSTRAINT 1
  110103. #define FTS4AUX_GE_CONSTRAINT 2
  110104. #define FTS4AUX_LE_CONSTRAINT 4
  110105. /*
  110106. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  110107. */
  110108. static int fts3auxBestIndexMethod(
  110109. sqlite3_vtab *pVTab,
  110110. sqlite3_index_info *pInfo
  110111. ){
  110112. int i;
  110113. int iEq = -1;
  110114. int iGe = -1;
  110115. int iLe = -1;
  110116. int iLangid = -1;
  110117. int iNext = 1; /* Next free argvIndex value */
  110118. UNUSED_PARAMETER(pVTab);
  110119. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  110120. if( pInfo->nOrderBy==1
  110121. && pInfo->aOrderBy[0].iColumn==0
  110122. && pInfo->aOrderBy[0].desc==0
  110123. ){
  110124. pInfo->orderByConsumed = 1;
  110125. }
  110126. /* Search for equality and range constraints on the "term" column.
  110127. ** And equality constraints on the hidden "languageid" column. */
  110128. for(i=0; i<pInfo->nConstraint; i++){
  110129. if( pInfo->aConstraint[i].usable ){
  110130. int op = pInfo->aConstraint[i].op;
  110131. int iCol = pInfo->aConstraint[i].iColumn;
  110132. if( iCol==0 ){
  110133. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  110134. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  110135. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  110136. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  110137. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  110138. }
  110139. if( iCol==4 ){
  110140. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  110141. }
  110142. }
  110143. }
  110144. if( iEq>=0 ){
  110145. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  110146. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  110147. pInfo->estimatedCost = 5;
  110148. }else{
  110149. pInfo->idxNum = 0;
  110150. pInfo->estimatedCost = 20000;
  110151. if( iGe>=0 ){
  110152. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  110153. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  110154. pInfo->estimatedCost /= 2;
  110155. }
  110156. if( iLe>=0 ){
  110157. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  110158. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  110159. pInfo->estimatedCost /= 2;
  110160. }
  110161. }
  110162. if( iLangid>=0 ){
  110163. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  110164. pInfo->estimatedCost--;
  110165. }
  110166. return SQLITE_OK;
  110167. }
  110168. /*
  110169. ** xOpen - Open a cursor.
  110170. */
  110171. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  110172. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  110173. UNUSED_PARAMETER(pVTab);
  110174. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  110175. if( !pCsr ) return SQLITE_NOMEM;
  110176. memset(pCsr, 0, sizeof(Fts3auxCursor));
  110177. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  110178. return SQLITE_OK;
  110179. }
  110180. /*
  110181. ** xClose - Close a cursor.
  110182. */
  110183. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  110184. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110185. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110186. sqlite3Fts3SegmentsClose(pFts3);
  110187. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  110188. sqlite3_free((void *)pCsr->filter.zTerm);
  110189. sqlite3_free(pCsr->zStop);
  110190. sqlite3_free(pCsr->aStat);
  110191. sqlite3_free(pCsr);
  110192. return SQLITE_OK;
  110193. }
  110194. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  110195. if( nSize>pCsr->nStat ){
  110196. struct Fts3auxColstats *aNew;
  110197. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  110198. sizeof(struct Fts3auxColstats) * nSize
  110199. );
  110200. if( aNew==0 ) return SQLITE_NOMEM;
  110201. memset(&aNew[pCsr->nStat], 0,
  110202. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  110203. );
  110204. pCsr->aStat = aNew;
  110205. pCsr->nStat = nSize;
  110206. }
  110207. return SQLITE_OK;
  110208. }
  110209. /*
  110210. ** xNext - Advance the cursor to the next row, if any.
  110211. */
  110212. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  110213. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110214. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110215. int rc;
  110216. /* Increment our pretend rowid value. */
  110217. pCsr->iRowid++;
  110218. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  110219. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  110220. }
  110221. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  110222. if( rc==SQLITE_ROW ){
  110223. int i = 0;
  110224. int nDoclist = pCsr->csr.nDoclist;
  110225. char *aDoclist = pCsr->csr.aDoclist;
  110226. int iCol;
  110227. int eState = 0;
  110228. if( pCsr->zStop ){
  110229. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  110230. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  110231. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  110232. pCsr->isEof = 1;
  110233. return SQLITE_OK;
  110234. }
  110235. }
  110236. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  110237. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  110238. iCol = 0;
  110239. while( i<nDoclist ){
  110240. sqlite3_int64 v = 0;
  110241. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  110242. switch( eState ){
  110243. /* State 0. In this state the integer just read was a docid. */
  110244. case 0:
  110245. pCsr->aStat[0].nDoc++;
  110246. eState = 1;
  110247. iCol = 0;
  110248. break;
  110249. /* State 1. In this state we are expecting either a 1, indicating
  110250. ** that the following integer will be a column number, or the
  110251. ** start of a position list for column 0.
  110252. **
  110253. ** The only difference between state 1 and state 2 is that if the
  110254. ** integer encountered in state 1 is not 0 or 1, then we need to
  110255. ** increment the column 0 "nDoc" count for this term.
  110256. */
  110257. case 1:
  110258. assert( iCol==0 );
  110259. if( v>1 ){
  110260. pCsr->aStat[1].nDoc++;
  110261. }
  110262. eState = 2;
  110263. /* fall through */
  110264. case 2:
  110265. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  110266. eState = 0;
  110267. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  110268. eState = 3;
  110269. }else{ /* 2 or greater. A position. */
  110270. pCsr->aStat[iCol+1].nOcc++;
  110271. pCsr->aStat[0].nOcc++;
  110272. }
  110273. break;
  110274. /* State 3. The integer just read is a column number. */
  110275. default: assert( eState==3 );
  110276. iCol = (int)v;
  110277. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  110278. pCsr->aStat[iCol+1].nDoc++;
  110279. eState = 2;
  110280. break;
  110281. }
  110282. }
  110283. pCsr->iCol = 0;
  110284. rc = SQLITE_OK;
  110285. }else{
  110286. pCsr->isEof = 1;
  110287. }
  110288. return rc;
  110289. }
  110290. /*
  110291. ** xFilter - Initialize a cursor to point at the start of its data.
  110292. */
  110293. static int fts3auxFilterMethod(
  110294. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  110295. int idxNum, /* Strategy index */
  110296. const char *idxStr, /* Unused */
  110297. int nVal, /* Number of elements in apVal */
  110298. sqlite3_value **apVal /* Arguments for the indexing scheme */
  110299. ){
  110300. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110301. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  110302. int rc;
  110303. int isScan = 0;
  110304. int iLangVal = 0; /* Language id to query */
  110305. int iEq = -1; /* Index of term=? value in apVal */
  110306. int iGe = -1; /* Index of term>=? value in apVal */
  110307. int iLe = -1; /* Index of term<=? value in apVal */
  110308. int iLangid = -1; /* Index of languageid=? value in apVal */
  110309. int iNext = 0;
  110310. UNUSED_PARAMETER(nVal);
  110311. UNUSED_PARAMETER(idxStr);
  110312. assert( idxStr==0 );
  110313. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  110314. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  110315. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  110316. );
  110317. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  110318. iEq = iNext++;
  110319. }else{
  110320. isScan = 1;
  110321. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  110322. iGe = iNext++;
  110323. }
  110324. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  110325. iLe = iNext++;
  110326. }
  110327. }
  110328. if( iNext<nVal ){
  110329. iLangid = iNext++;
  110330. }
  110331. /* In case this cursor is being reused, close and zero it. */
  110332. testcase(pCsr->filter.zTerm);
  110333. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  110334. sqlite3_free((void *)pCsr->filter.zTerm);
  110335. sqlite3_free(pCsr->aStat);
  110336. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  110337. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  110338. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  110339. if( iEq>=0 || iGe>=0 ){
  110340. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  110341. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  110342. if( zStr ){
  110343. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  110344. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  110345. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  110346. }
  110347. }
  110348. if( iLe>=0 ){
  110349. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  110350. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  110351. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  110352. }
  110353. if( iLangid>=0 ){
  110354. iLangVal = sqlite3_value_int(apVal[iLangid]);
  110355. /* If the user specified a negative value for the languageid, use zero
  110356. ** instead. This works, as the "languageid=?" constraint will also
  110357. ** be tested by the VDBE layer. The test will always be false (since
  110358. ** this module will not return a row with a negative languageid), and
  110359. ** so the overall query will return zero rows. */
  110360. if( iLangVal<0 ) iLangVal = 0;
  110361. }
  110362. pCsr->iLangid = iLangVal;
  110363. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  110364. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  110365. );
  110366. if( rc==SQLITE_OK ){
  110367. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  110368. }
  110369. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  110370. return rc;
  110371. }
  110372. /*
  110373. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  110374. */
  110375. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  110376. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110377. return pCsr->isEof;
  110378. }
  110379. /*
  110380. ** xColumn - Return a column value.
  110381. */
  110382. static int fts3auxColumnMethod(
  110383. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  110384. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  110385. int iCol /* Index of column to read value from */
  110386. ){
  110387. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  110388. assert( p->isEof==0 );
  110389. switch( iCol ){
  110390. case 0: /* term */
  110391. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  110392. break;
  110393. case 1: /* col */
  110394. if( p->iCol ){
  110395. sqlite3_result_int(pCtx, p->iCol-1);
  110396. }else{
  110397. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  110398. }
  110399. break;
  110400. case 2: /* documents */
  110401. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  110402. break;
  110403. case 3: /* occurrences */
  110404. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  110405. break;
  110406. default: /* languageid */
  110407. assert( iCol==4 );
  110408. sqlite3_result_int(pCtx, p->iLangid);
  110409. break;
  110410. }
  110411. return SQLITE_OK;
  110412. }
  110413. /*
  110414. ** xRowid - Return the current rowid for the cursor.
  110415. */
  110416. static int fts3auxRowidMethod(
  110417. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  110418. sqlite_int64 *pRowid /* OUT: Rowid value */
  110419. ){
  110420. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  110421. *pRowid = pCsr->iRowid;
  110422. return SQLITE_OK;
  110423. }
  110424. /*
  110425. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  110426. ** if successful or an error code if sqlite3_create_module() fails.
  110427. */
  110428. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  110429. static const sqlite3_module fts3aux_module = {
  110430. 0, /* iVersion */
  110431. fts3auxConnectMethod, /* xCreate */
  110432. fts3auxConnectMethod, /* xConnect */
  110433. fts3auxBestIndexMethod, /* xBestIndex */
  110434. fts3auxDisconnectMethod, /* xDisconnect */
  110435. fts3auxDisconnectMethod, /* xDestroy */
  110436. fts3auxOpenMethod, /* xOpen */
  110437. fts3auxCloseMethod, /* xClose */
  110438. fts3auxFilterMethod, /* xFilter */
  110439. fts3auxNextMethod, /* xNext */
  110440. fts3auxEofMethod, /* xEof */
  110441. fts3auxColumnMethod, /* xColumn */
  110442. fts3auxRowidMethod, /* xRowid */
  110443. 0, /* xUpdate */
  110444. 0, /* xBegin */
  110445. 0, /* xSync */
  110446. 0, /* xCommit */
  110447. 0, /* xRollback */
  110448. 0, /* xFindFunction */
  110449. 0, /* xRename */
  110450. 0, /* xSavepoint */
  110451. 0, /* xRelease */
  110452. 0 /* xRollbackTo */
  110453. };
  110454. int rc; /* Return code */
  110455. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  110456. return rc;
  110457. }
  110458. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  110459. /************** End of fts3_aux.c ********************************************/
  110460. /************** Begin file fts3_expr.c ***************************************/
  110461. /*
  110462. ** 2008 Nov 28
  110463. **
  110464. ** The author disclaims copyright to this source code. In place of
  110465. ** a legal notice, here is a blessing:
  110466. **
  110467. ** May you do good and not evil.
  110468. ** May you find forgiveness for yourself and forgive others.
  110469. ** May you share freely, never taking more than you give.
  110470. **
  110471. ******************************************************************************
  110472. **
  110473. ** This module contains code that implements a parser for fts3 query strings
  110474. ** (the right-hand argument to the MATCH operator). Because the supported
  110475. ** syntax is relatively simple, the whole tokenizer/parser system is
  110476. ** hand-coded.
  110477. */
  110478. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  110479. /*
  110480. ** By default, this module parses the legacy syntax that has been
  110481. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  110482. ** is defined, then it uses the new syntax. The differences between
  110483. ** the new and the old syntaxes are:
  110484. **
  110485. ** a) The new syntax supports parenthesis. The old does not.
  110486. **
  110487. ** b) The new syntax supports the AND and NOT operators. The old does not.
  110488. **
  110489. ** c) The old syntax supports the "-" token qualifier. This is not
  110490. ** supported by the new syntax (it is replaced by the NOT operator).
  110491. **
  110492. ** d) When using the old syntax, the OR operator has a greater precedence
  110493. ** than an implicit AND. When using the new, both implicity and explicit
  110494. ** AND operators have a higher precedence than OR.
  110495. **
  110496. ** If compiled with SQLITE_TEST defined, then this module exports the
  110497. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  110498. ** to zero causes the module to use the old syntax. If it is set to
  110499. ** non-zero the new syntax is activated. This is so both syntaxes can
  110500. ** be tested using a single build of testfixture.
  110501. **
  110502. ** The following describes the syntax supported by the fts3 MATCH
  110503. ** operator in a similar format to that used by the lemon parser
  110504. ** generator. This module does not use actually lemon, it uses a
  110505. ** custom parser.
  110506. **
  110507. ** query ::= andexpr (OR andexpr)*.
  110508. **
  110509. ** andexpr ::= notexpr (AND? notexpr)*.
  110510. **
  110511. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  110512. ** notexpr ::= LP query RP.
  110513. **
  110514. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  110515. **
  110516. ** distance_opt ::= .
  110517. ** distance_opt ::= / INTEGER.
  110518. **
  110519. ** phrase ::= TOKEN.
  110520. ** phrase ::= COLUMN:TOKEN.
  110521. ** phrase ::= "TOKEN TOKEN TOKEN...".
  110522. */
  110523. #ifdef SQLITE_TEST
  110524. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  110525. #else
  110526. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  110527. # define sqlite3_fts3_enable_parentheses 1
  110528. # else
  110529. # define sqlite3_fts3_enable_parentheses 0
  110530. # endif
  110531. #endif
  110532. /*
  110533. ** Default span for NEAR operators.
  110534. */
  110535. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  110536. /* #include <string.h> */
  110537. /* #include <assert.h> */
  110538. /*
  110539. ** isNot:
  110540. ** This variable is used by function getNextNode(). When getNextNode() is
  110541. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  110542. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  110543. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  110544. ** zero.
  110545. */
  110546. typedef struct ParseContext ParseContext;
  110547. struct ParseContext {
  110548. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  110549. int iLangid; /* Language id used with tokenizer */
  110550. const char **azCol; /* Array of column names for fts3 table */
  110551. int bFts4; /* True to allow FTS4-only syntax */
  110552. int nCol; /* Number of entries in azCol[] */
  110553. int iDefaultCol; /* Default column to query */
  110554. int isNot; /* True if getNextNode() sees a unary - */
  110555. sqlite3_context *pCtx; /* Write error message here */
  110556. int nNest; /* Number of nested brackets */
  110557. };
  110558. /*
  110559. ** This function is equivalent to the standard isspace() function.
  110560. **
  110561. ** The standard isspace() can be awkward to use safely, because although it
  110562. ** is defined to accept an argument of type int, its behavior when passed
  110563. ** an integer that falls outside of the range of the unsigned char type
  110564. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  110565. ** is defined to accept an argument of type char, and always returns 0 for
  110566. ** any values that fall outside of the range of the unsigned char type (i.e.
  110567. ** negative values).
  110568. */
  110569. static int fts3isspace(char c){
  110570. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  110571. }
  110572. /*
  110573. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  110574. ** zero the memory before returning a pointer to it. If unsuccessful,
  110575. ** return NULL.
  110576. */
  110577. static void *fts3MallocZero(int nByte){
  110578. void *pRet = sqlite3_malloc(nByte);
  110579. if( pRet ) memset(pRet, 0, nByte);
  110580. return pRet;
  110581. }
  110582. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  110583. sqlite3_tokenizer *pTokenizer,
  110584. int iLangid,
  110585. const char *z,
  110586. int n,
  110587. sqlite3_tokenizer_cursor **ppCsr
  110588. ){
  110589. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110590. sqlite3_tokenizer_cursor *pCsr = 0;
  110591. int rc;
  110592. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  110593. assert( rc==SQLITE_OK || pCsr==0 );
  110594. if( rc==SQLITE_OK ){
  110595. pCsr->pTokenizer = pTokenizer;
  110596. if( pModule->iVersion>=1 ){
  110597. rc = pModule->xLanguageid(pCsr, iLangid);
  110598. if( rc!=SQLITE_OK ){
  110599. pModule->xClose(pCsr);
  110600. pCsr = 0;
  110601. }
  110602. }
  110603. }
  110604. *ppCsr = pCsr;
  110605. return rc;
  110606. }
  110607. /*
  110608. ** Extract the next token from buffer z (length n) using the tokenizer
  110609. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  110610. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  110611. ** single token and set *ppExpr to point to it. If the end of the buffer is
  110612. ** reached before a token is found, set *ppExpr to zero. It is the
  110613. ** responsibility of the caller to eventually deallocate the allocated
  110614. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  110615. **
  110616. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  110617. ** fails.
  110618. */
  110619. static int getNextToken(
  110620. ParseContext *pParse, /* fts3 query parse context */
  110621. int iCol, /* Value for Fts3Phrase.iColumn */
  110622. const char *z, int n, /* Input string */
  110623. Fts3Expr **ppExpr, /* OUT: expression */
  110624. int *pnConsumed /* OUT: Number of bytes consumed */
  110625. ){
  110626. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  110627. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110628. int rc;
  110629. sqlite3_tokenizer_cursor *pCursor;
  110630. Fts3Expr *pRet = 0;
  110631. int nConsumed = 0;
  110632. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  110633. if( rc==SQLITE_OK ){
  110634. const char *zToken;
  110635. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  110636. int nByte; /* total space to allocate */
  110637. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  110638. if( rc==SQLITE_OK ){
  110639. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  110640. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  110641. if( !pRet ){
  110642. rc = SQLITE_NOMEM;
  110643. }else{
  110644. pRet->eType = FTSQUERY_PHRASE;
  110645. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  110646. pRet->pPhrase->nToken = 1;
  110647. pRet->pPhrase->iColumn = iCol;
  110648. pRet->pPhrase->aToken[0].n = nToken;
  110649. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  110650. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  110651. if( iEnd<n && z[iEnd]=='*' ){
  110652. pRet->pPhrase->aToken[0].isPrefix = 1;
  110653. iEnd++;
  110654. }
  110655. while( 1 ){
  110656. if( !sqlite3_fts3_enable_parentheses
  110657. && iStart>0 && z[iStart-1]=='-'
  110658. ){
  110659. pParse->isNot = 1;
  110660. iStart--;
  110661. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  110662. pRet->pPhrase->aToken[0].bFirst = 1;
  110663. iStart--;
  110664. }else{
  110665. break;
  110666. }
  110667. }
  110668. }
  110669. nConsumed = iEnd;
  110670. }
  110671. pModule->xClose(pCursor);
  110672. }
  110673. *pnConsumed = nConsumed;
  110674. *ppExpr = pRet;
  110675. return rc;
  110676. }
  110677. /*
  110678. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  110679. ** then free the old allocation.
  110680. */
  110681. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  110682. void *pRet = sqlite3_realloc(pOrig, nNew);
  110683. if( !pRet ){
  110684. sqlite3_free(pOrig);
  110685. }
  110686. return pRet;
  110687. }
  110688. /*
  110689. ** Buffer zInput, length nInput, contains the contents of a quoted string
  110690. ** that appeared as part of an fts3 query expression. Neither quote character
  110691. ** is included in the buffer. This function attempts to tokenize the entire
  110692. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  110693. ** containing the results.
  110694. **
  110695. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  110696. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  110697. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  110698. ** to 0.
  110699. */
  110700. static int getNextString(
  110701. ParseContext *pParse, /* fts3 query parse context */
  110702. const char *zInput, int nInput, /* Input string */
  110703. Fts3Expr **ppExpr /* OUT: expression */
  110704. ){
  110705. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  110706. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110707. int rc;
  110708. Fts3Expr *p = 0;
  110709. sqlite3_tokenizer_cursor *pCursor = 0;
  110710. char *zTemp = 0;
  110711. int nTemp = 0;
  110712. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  110713. int nToken = 0;
  110714. /* The final Fts3Expr data structure, including the Fts3Phrase,
  110715. ** Fts3PhraseToken structures token buffers are all stored as a single
  110716. ** allocation so that the expression can be freed with a single call to
  110717. ** sqlite3_free(). Setting this up requires a two pass approach.
  110718. **
  110719. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  110720. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  110721. ** to assemble data in two dynamic buffers:
  110722. **
  110723. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  110724. ** structure, followed by the array of Fts3PhraseToken
  110725. ** structures. This pass only populates the Fts3PhraseToken array.
  110726. **
  110727. ** Buffer zTemp: Contains copies of all tokens.
  110728. **
  110729. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  110730. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  110731. ** structures.
  110732. */
  110733. rc = sqlite3Fts3OpenTokenizer(
  110734. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  110735. if( rc==SQLITE_OK ){
  110736. int ii;
  110737. for(ii=0; rc==SQLITE_OK; ii++){
  110738. const char *zByte;
  110739. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  110740. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  110741. if( rc==SQLITE_OK ){
  110742. Fts3PhraseToken *pToken;
  110743. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  110744. if( !p ) goto no_mem;
  110745. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  110746. if( !zTemp ) goto no_mem;
  110747. assert( nToken==ii );
  110748. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  110749. memset(pToken, 0, sizeof(Fts3PhraseToken));
  110750. memcpy(&zTemp[nTemp], zByte, nByte);
  110751. nTemp += nByte;
  110752. pToken->n = nByte;
  110753. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  110754. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  110755. nToken = ii+1;
  110756. }
  110757. }
  110758. pModule->xClose(pCursor);
  110759. pCursor = 0;
  110760. }
  110761. if( rc==SQLITE_DONE ){
  110762. int jj;
  110763. char *zBuf = 0;
  110764. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  110765. if( !p ) goto no_mem;
  110766. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  110767. p->eType = FTSQUERY_PHRASE;
  110768. p->pPhrase = (Fts3Phrase *)&p[1];
  110769. p->pPhrase->iColumn = pParse->iDefaultCol;
  110770. p->pPhrase->nToken = nToken;
  110771. zBuf = (char *)&p->pPhrase->aToken[nToken];
  110772. if( zTemp ){
  110773. memcpy(zBuf, zTemp, nTemp);
  110774. sqlite3_free(zTemp);
  110775. }else{
  110776. assert( nTemp==0 );
  110777. }
  110778. for(jj=0; jj<p->pPhrase->nToken; jj++){
  110779. p->pPhrase->aToken[jj].z = zBuf;
  110780. zBuf += p->pPhrase->aToken[jj].n;
  110781. }
  110782. rc = SQLITE_OK;
  110783. }
  110784. *ppExpr = p;
  110785. return rc;
  110786. no_mem:
  110787. if( pCursor ){
  110788. pModule->xClose(pCursor);
  110789. }
  110790. sqlite3_free(zTemp);
  110791. sqlite3_free(p);
  110792. *ppExpr = 0;
  110793. return SQLITE_NOMEM;
  110794. }
  110795. /*
  110796. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  110797. ** call fts3ExprParse(). So this forward declaration is required.
  110798. */
  110799. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  110800. /*
  110801. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  110802. ** structure, or set to 0 if the end of the input buffer is reached.
  110803. **
  110804. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  110805. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  110806. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  110807. */
  110808. static int getNextNode(
  110809. ParseContext *pParse, /* fts3 query parse context */
  110810. const char *z, int n, /* Input string */
  110811. Fts3Expr **ppExpr, /* OUT: expression */
  110812. int *pnConsumed /* OUT: Number of bytes consumed */
  110813. ){
  110814. static const struct Fts3Keyword {
  110815. char *z; /* Keyword text */
  110816. unsigned char n; /* Length of the keyword */
  110817. unsigned char parenOnly; /* Only valid in paren mode */
  110818. unsigned char eType; /* Keyword code */
  110819. } aKeyword[] = {
  110820. { "OR" , 2, 0, FTSQUERY_OR },
  110821. { "AND", 3, 1, FTSQUERY_AND },
  110822. { "NOT", 3, 1, FTSQUERY_NOT },
  110823. { "NEAR", 4, 0, FTSQUERY_NEAR }
  110824. };
  110825. int ii;
  110826. int iCol;
  110827. int iColLen;
  110828. int rc;
  110829. Fts3Expr *pRet = 0;
  110830. const char *zInput = z;
  110831. int nInput = n;
  110832. pParse->isNot = 0;
  110833. /* Skip over any whitespace before checking for a keyword, an open or
  110834. ** close bracket, or a quoted string.
  110835. */
  110836. while( nInput>0 && fts3isspace(*zInput) ){
  110837. nInput--;
  110838. zInput++;
  110839. }
  110840. if( nInput==0 ){
  110841. return SQLITE_DONE;
  110842. }
  110843. /* See if we are dealing with a keyword. */
  110844. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  110845. const struct Fts3Keyword *pKey = &aKeyword[ii];
  110846. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  110847. continue;
  110848. }
  110849. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  110850. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  110851. int nKey = pKey->n;
  110852. char cNext;
  110853. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  110854. if( pKey->eType==FTSQUERY_NEAR ){
  110855. assert( nKey==4 );
  110856. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  110857. nNear = 0;
  110858. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  110859. nNear = nNear * 10 + (zInput[nKey] - '0');
  110860. }
  110861. }
  110862. }
  110863. /* At this point this is probably a keyword. But for that to be true,
  110864. ** the next byte must contain either whitespace, an open or close
  110865. ** parenthesis, a quote character, or EOF.
  110866. */
  110867. cNext = zInput[nKey];
  110868. if( fts3isspace(cNext)
  110869. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  110870. ){
  110871. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  110872. if( !pRet ){
  110873. return SQLITE_NOMEM;
  110874. }
  110875. pRet->eType = pKey->eType;
  110876. pRet->nNear = nNear;
  110877. *ppExpr = pRet;
  110878. *pnConsumed = (int)((zInput - z) + nKey);
  110879. return SQLITE_OK;
  110880. }
  110881. /* Turns out that wasn't a keyword after all. This happens if the
  110882. ** user has supplied a token such as "ORacle". Continue.
  110883. */
  110884. }
  110885. }
  110886. /* Check for an open bracket. */
  110887. if( sqlite3_fts3_enable_parentheses ){
  110888. if( *zInput=='(' ){
  110889. int nConsumed;
  110890. pParse->nNest++;
  110891. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  110892. if( rc==SQLITE_OK && !*ppExpr ){
  110893. rc = SQLITE_DONE;
  110894. }
  110895. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  110896. return rc;
  110897. }
  110898. /* Check for a close bracket. */
  110899. if( *zInput==')' ){
  110900. pParse->nNest--;
  110901. *pnConsumed = (int)((zInput - z) + 1);
  110902. return SQLITE_DONE;
  110903. }
  110904. }
  110905. /* See if we are dealing with a quoted phrase. If this is the case, then
  110906. ** search for the closing quote and pass the whole string to getNextString()
  110907. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  110908. ** a quote character embedded in a string.
  110909. */
  110910. if( *zInput=='"' ){
  110911. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  110912. *pnConsumed = (int)((zInput - z) + ii + 1);
  110913. if( ii==nInput ){
  110914. return SQLITE_ERROR;
  110915. }
  110916. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  110917. }
  110918. /* If control flows to this point, this must be a regular token, or
  110919. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  110920. ** interface. Before doing so, figure out if there is an explicit
  110921. ** column specifier for the token.
  110922. **
  110923. ** TODO: Strangely, it is not possible to associate a column specifier
  110924. ** with a quoted phrase, only with a single token. Not sure if this was
  110925. ** an implementation artifact or an intentional decision when fts3 was
  110926. ** first implemented. Whichever it was, this module duplicates the
  110927. ** limitation.
  110928. */
  110929. iCol = pParse->iDefaultCol;
  110930. iColLen = 0;
  110931. for(ii=0; ii<pParse->nCol; ii++){
  110932. const char *zStr = pParse->azCol[ii];
  110933. int nStr = (int)strlen(zStr);
  110934. if( nInput>nStr && zInput[nStr]==':'
  110935. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  110936. ){
  110937. iCol = ii;
  110938. iColLen = (int)((zInput - z) + nStr + 1);
  110939. break;
  110940. }
  110941. }
  110942. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  110943. *pnConsumed += iColLen;
  110944. return rc;
  110945. }
  110946. /*
  110947. ** The argument is an Fts3Expr structure for a binary operator (any type
  110948. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  110949. ** precedence of the operator. Lower values have a higher precedence (i.e.
  110950. ** group more tightly). For example, in the C language, the == operator
  110951. ** groups more tightly than ||, and would therefore have a higher precedence.
  110952. **
  110953. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  110954. ** is defined), the order of the operators in precedence from highest to
  110955. ** lowest is:
  110956. **
  110957. ** NEAR
  110958. ** NOT
  110959. ** AND (including implicit ANDs)
  110960. ** OR
  110961. **
  110962. ** Note that when using the old query syntax, the OR operator has a higher
  110963. ** precedence than the AND operator.
  110964. */
  110965. static int opPrecedence(Fts3Expr *p){
  110966. assert( p->eType!=FTSQUERY_PHRASE );
  110967. if( sqlite3_fts3_enable_parentheses ){
  110968. return p->eType;
  110969. }else if( p->eType==FTSQUERY_NEAR ){
  110970. return 1;
  110971. }else if( p->eType==FTSQUERY_OR ){
  110972. return 2;
  110973. }
  110974. assert( p->eType==FTSQUERY_AND );
  110975. return 3;
  110976. }
  110977. /*
  110978. ** Argument ppHead contains a pointer to the current head of a query
  110979. ** expression tree being parsed. pPrev is the expression node most recently
  110980. ** inserted into the tree. This function adds pNew, which is always a binary
  110981. ** operator node, into the expression tree based on the relative precedence
  110982. ** of pNew and the existing nodes of the tree. This may result in the head
  110983. ** of the tree changing, in which case *ppHead is set to the new root node.
  110984. */
  110985. static void insertBinaryOperator(
  110986. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  110987. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  110988. Fts3Expr *pNew /* New binary node to insert into expression tree */
  110989. ){
  110990. Fts3Expr *pSplit = pPrev;
  110991. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  110992. pSplit = pSplit->pParent;
  110993. }
  110994. if( pSplit->pParent ){
  110995. assert( pSplit->pParent->pRight==pSplit );
  110996. pSplit->pParent->pRight = pNew;
  110997. pNew->pParent = pSplit->pParent;
  110998. }else{
  110999. *ppHead = pNew;
  111000. }
  111001. pNew->pLeft = pSplit;
  111002. pSplit->pParent = pNew;
  111003. }
  111004. /*
  111005. ** Parse the fts3 query expression found in buffer z, length n. This function
  111006. ** returns either when the end of the buffer is reached or an unmatched
  111007. ** closing bracket - ')' - is encountered.
  111008. **
  111009. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  111010. ** parsed form of the expression and *pnConsumed is set to the number of
  111011. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  111012. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  111013. */
  111014. static int fts3ExprParse(
  111015. ParseContext *pParse, /* fts3 query parse context */
  111016. const char *z, int n, /* Text of MATCH query */
  111017. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  111018. int *pnConsumed /* OUT: Number of bytes consumed */
  111019. ){
  111020. Fts3Expr *pRet = 0;
  111021. Fts3Expr *pPrev = 0;
  111022. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  111023. int nIn = n;
  111024. const char *zIn = z;
  111025. int rc = SQLITE_OK;
  111026. int isRequirePhrase = 1;
  111027. while( rc==SQLITE_OK ){
  111028. Fts3Expr *p = 0;
  111029. int nByte = 0;
  111030. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  111031. if( rc==SQLITE_OK ){
  111032. int isPhrase;
  111033. if( !sqlite3_fts3_enable_parentheses
  111034. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  111035. ){
  111036. /* Create an implicit NOT operator. */
  111037. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  111038. if( !pNot ){
  111039. sqlite3Fts3ExprFree(p);
  111040. rc = SQLITE_NOMEM;
  111041. goto exprparse_out;
  111042. }
  111043. pNot->eType = FTSQUERY_NOT;
  111044. pNot->pRight = p;
  111045. p->pParent = pNot;
  111046. if( pNotBranch ){
  111047. pNot->pLeft = pNotBranch;
  111048. pNotBranch->pParent = pNot;
  111049. }
  111050. pNotBranch = pNot;
  111051. p = pPrev;
  111052. }else{
  111053. int eType = p->eType;
  111054. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  111055. /* The isRequirePhrase variable is set to true if a phrase or
  111056. ** an expression contained in parenthesis is required. If a
  111057. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  111058. ** isRequirePhrase is set, this is a syntax error.
  111059. */
  111060. if( !isPhrase && isRequirePhrase ){
  111061. sqlite3Fts3ExprFree(p);
  111062. rc = SQLITE_ERROR;
  111063. goto exprparse_out;
  111064. }
  111065. if( isPhrase && !isRequirePhrase ){
  111066. /* Insert an implicit AND operator. */
  111067. Fts3Expr *pAnd;
  111068. assert( pRet && pPrev );
  111069. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  111070. if( !pAnd ){
  111071. sqlite3Fts3ExprFree(p);
  111072. rc = SQLITE_NOMEM;
  111073. goto exprparse_out;
  111074. }
  111075. pAnd->eType = FTSQUERY_AND;
  111076. insertBinaryOperator(&pRet, pPrev, pAnd);
  111077. pPrev = pAnd;
  111078. }
  111079. /* This test catches attempts to make either operand of a NEAR
  111080. ** operator something other than a phrase. For example, either of
  111081. ** the following:
  111082. **
  111083. ** (bracketed expression) NEAR phrase
  111084. ** phrase NEAR (bracketed expression)
  111085. **
  111086. ** Return an error in either case.
  111087. */
  111088. if( pPrev && (
  111089. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  111090. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  111091. )){
  111092. sqlite3Fts3ExprFree(p);
  111093. rc = SQLITE_ERROR;
  111094. goto exprparse_out;
  111095. }
  111096. if( isPhrase ){
  111097. if( pRet ){
  111098. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  111099. pPrev->pRight = p;
  111100. p->pParent = pPrev;
  111101. }else{
  111102. pRet = p;
  111103. }
  111104. }else{
  111105. insertBinaryOperator(&pRet, pPrev, p);
  111106. }
  111107. isRequirePhrase = !isPhrase;
  111108. }
  111109. assert( nByte>0 );
  111110. }
  111111. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  111112. nIn -= nByte;
  111113. zIn += nByte;
  111114. pPrev = p;
  111115. }
  111116. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  111117. rc = SQLITE_ERROR;
  111118. }
  111119. if( rc==SQLITE_DONE ){
  111120. rc = SQLITE_OK;
  111121. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  111122. if( !pRet ){
  111123. rc = SQLITE_ERROR;
  111124. }else{
  111125. Fts3Expr *pIter = pNotBranch;
  111126. while( pIter->pLeft ){
  111127. pIter = pIter->pLeft;
  111128. }
  111129. pIter->pLeft = pRet;
  111130. pRet->pParent = pIter;
  111131. pRet = pNotBranch;
  111132. }
  111133. }
  111134. }
  111135. *pnConsumed = n - nIn;
  111136. exprparse_out:
  111137. if( rc!=SQLITE_OK ){
  111138. sqlite3Fts3ExprFree(pRet);
  111139. sqlite3Fts3ExprFree(pNotBranch);
  111140. pRet = 0;
  111141. }
  111142. *ppExpr = pRet;
  111143. return rc;
  111144. }
  111145. /*
  111146. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  111147. ** as the only argument is more than nMaxDepth.
  111148. */
  111149. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  111150. int rc = SQLITE_OK;
  111151. if( p ){
  111152. if( nMaxDepth<0 ){
  111153. rc = SQLITE_TOOBIG;
  111154. }else{
  111155. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  111156. if( rc==SQLITE_OK ){
  111157. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  111158. }
  111159. }
  111160. }
  111161. return rc;
  111162. }
  111163. /*
  111164. ** This function attempts to transform the expression tree at (*pp) to
  111165. ** an equivalent but more balanced form. The tree is modified in place.
  111166. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  111167. ** new root expression node.
  111168. **
  111169. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  111170. **
  111171. ** Otherwise, if an error occurs, an SQLite error code is returned and
  111172. ** expression (*pp) freed.
  111173. */
  111174. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  111175. int rc = SQLITE_OK; /* Return code */
  111176. Fts3Expr *pRoot = *pp; /* Initial root node */
  111177. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  111178. int eType = pRoot->eType; /* Type of node in this tree */
  111179. if( nMaxDepth==0 ){
  111180. rc = SQLITE_ERROR;
  111181. }
  111182. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  111183. Fts3Expr **apLeaf;
  111184. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  111185. if( 0==apLeaf ){
  111186. rc = SQLITE_NOMEM;
  111187. }else{
  111188. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  111189. }
  111190. if( rc==SQLITE_OK ){
  111191. int i;
  111192. Fts3Expr *p;
  111193. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  111194. for(p=pRoot; p->eType==eType; p=p->pLeft){
  111195. assert( p->pParent==0 || p->pParent->pLeft==p );
  111196. assert( p->pLeft && p->pRight );
  111197. }
  111198. /* This loop runs once for each leaf in the tree of eType nodes. */
  111199. while( 1 ){
  111200. int iLvl;
  111201. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  111202. assert( pParent==0 || pParent->pLeft==p );
  111203. p->pParent = 0;
  111204. if( pParent ){
  111205. pParent->pLeft = 0;
  111206. }else{
  111207. pRoot = 0;
  111208. }
  111209. rc = fts3ExprBalance(&p, nMaxDepth-1);
  111210. if( rc!=SQLITE_OK ) break;
  111211. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  111212. if( apLeaf[iLvl]==0 ){
  111213. apLeaf[iLvl] = p;
  111214. p = 0;
  111215. }else{
  111216. assert( pFree );
  111217. pFree->pLeft = apLeaf[iLvl];
  111218. pFree->pRight = p;
  111219. pFree->pLeft->pParent = pFree;
  111220. pFree->pRight->pParent = pFree;
  111221. p = pFree;
  111222. pFree = pFree->pParent;
  111223. p->pParent = 0;
  111224. apLeaf[iLvl] = 0;
  111225. }
  111226. }
  111227. if( p ){
  111228. sqlite3Fts3ExprFree(p);
  111229. rc = SQLITE_TOOBIG;
  111230. break;
  111231. }
  111232. /* If that was the last leaf node, break out of the loop */
  111233. if( pParent==0 ) break;
  111234. /* Set $p to point to the next leaf in the tree of eType nodes */
  111235. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  111236. /* Remove pParent from the original tree. */
  111237. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  111238. pParent->pRight->pParent = pParent->pParent;
  111239. if( pParent->pParent ){
  111240. pParent->pParent->pLeft = pParent->pRight;
  111241. }else{
  111242. assert( pParent==pRoot );
  111243. pRoot = pParent->pRight;
  111244. }
  111245. /* Link pParent into the free node list. It will be used as an
  111246. ** internal node of the new tree. */
  111247. pParent->pParent = pFree;
  111248. pFree = pParent;
  111249. }
  111250. if( rc==SQLITE_OK ){
  111251. p = 0;
  111252. for(i=0; i<nMaxDepth; i++){
  111253. if( apLeaf[i] ){
  111254. if( p==0 ){
  111255. p = apLeaf[i];
  111256. p->pParent = 0;
  111257. }else{
  111258. assert( pFree!=0 );
  111259. pFree->pRight = p;
  111260. pFree->pLeft = apLeaf[i];
  111261. pFree->pLeft->pParent = pFree;
  111262. pFree->pRight->pParent = pFree;
  111263. p = pFree;
  111264. pFree = pFree->pParent;
  111265. p->pParent = 0;
  111266. }
  111267. }
  111268. }
  111269. pRoot = p;
  111270. }else{
  111271. /* An error occurred. Delete the contents of the apLeaf[] array
  111272. ** and pFree list. Everything else is cleaned up by the call to
  111273. ** sqlite3Fts3ExprFree(pRoot) below. */
  111274. Fts3Expr *pDel;
  111275. for(i=0; i<nMaxDepth; i++){
  111276. sqlite3Fts3ExprFree(apLeaf[i]);
  111277. }
  111278. while( (pDel=pFree)!=0 ){
  111279. pFree = pDel->pParent;
  111280. sqlite3_free(pDel);
  111281. }
  111282. }
  111283. assert( pFree==0 );
  111284. sqlite3_free( apLeaf );
  111285. }
  111286. }
  111287. if( rc!=SQLITE_OK ){
  111288. sqlite3Fts3ExprFree(pRoot);
  111289. pRoot = 0;
  111290. }
  111291. *pp = pRoot;
  111292. return rc;
  111293. }
  111294. /*
  111295. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  111296. ** differences:
  111297. **
  111298. ** 1. It does not do expression rebalancing.
  111299. ** 2. It does not check that the expression does not exceed the
  111300. ** maximum allowable depth.
  111301. ** 3. Even if it fails, *ppExpr may still be set to point to an
  111302. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  111303. ** in this case.
  111304. */
  111305. static int fts3ExprParseUnbalanced(
  111306. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  111307. int iLangid, /* Language id for tokenizer */
  111308. char **azCol, /* Array of column names for fts3 table */
  111309. int bFts4, /* True to allow FTS4-only syntax */
  111310. int nCol, /* Number of entries in azCol[] */
  111311. int iDefaultCol, /* Default column to query */
  111312. const char *z, int n, /* Text of MATCH query */
  111313. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  111314. ){
  111315. int nParsed;
  111316. int rc;
  111317. ParseContext sParse;
  111318. memset(&sParse, 0, sizeof(ParseContext));
  111319. sParse.pTokenizer = pTokenizer;
  111320. sParse.iLangid = iLangid;
  111321. sParse.azCol = (const char **)azCol;
  111322. sParse.nCol = nCol;
  111323. sParse.iDefaultCol = iDefaultCol;
  111324. sParse.bFts4 = bFts4;
  111325. if( z==0 ){
  111326. *ppExpr = 0;
  111327. return SQLITE_OK;
  111328. }
  111329. if( n<0 ){
  111330. n = (int)strlen(z);
  111331. }
  111332. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  111333. assert( rc==SQLITE_OK || *ppExpr==0 );
  111334. /* Check for mismatched parenthesis */
  111335. if( rc==SQLITE_OK && sParse.nNest ){
  111336. rc = SQLITE_ERROR;
  111337. }
  111338. return rc;
  111339. }
  111340. /*
  111341. ** Parameters z and n contain a pointer to and length of a buffer containing
  111342. ** an fts3 query expression, respectively. This function attempts to parse the
  111343. ** query expression and create a tree of Fts3Expr structures representing the
  111344. ** parsed expression. If successful, *ppExpr is set to point to the head
  111345. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  111346. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  111347. ** error) is returned and *ppExpr is set to 0.
  111348. **
  111349. ** If parameter n is a negative number, then z is assumed to point to a
  111350. ** nul-terminated string and the length is determined using strlen().
  111351. **
  111352. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  111353. ** use to normalize query tokens while parsing the expression. The azCol[]
  111354. ** array, which is assumed to contain nCol entries, should contain the names
  111355. ** of each column in the target fts3 table, in order from left to right.
  111356. ** Column names must be nul-terminated strings.
  111357. **
  111358. ** The iDefaultCol parameter should be passed the index of the table column
  111359. ** that appears on the left-hand-side of the MATCH operator (the default
  111360. ** column to match against for tokens for which a column name is not explicitly
  111361. ** specified as part of the query string), or -1 if tokens may by default
  111362. ** match any table column.
  111363. */
  111364. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  111365. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  111366. int iLangid, /* Language id for tokenizer */
  111367. char **azCol, /* Array of column names for fts3 table */
  111368. int bFts4, /* True to allow FTS4-only syntax */
  111369. int nCol, /* Number of entries in azCol[] */
  111370. int iDefaultCol, /* Default column to query */
  111371. const char *z, int n, /* Text of MATCH query */
  111372. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  111373. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  111374. ){
  111375. int rc = fts3ExprParseUnbalanced(
  111376. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  111377. );
  111378. /* Rebalance the expression. And check that its depth does not exceed
  111379. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  111380. if( rc==SQLITE_OK && *ppExpr ){
  111381. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  111382. if( rc==SQLITE_OK ){
  111383. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  111384. }
  111385. }
  111386. if( rc!=SQLITE_OK ){
  111387. sqlite3Fts3ExprFree(*ppExpr);
  111388. *ppExpr = 0;
  111389. if( rc==SQLITE_TOOBIG ){
  111390. *pzErr = sqlite3_mprintf(
  111391. "FTS expression tree is too large (maximum depth %d)",
  111392. SQLITE_FTS3_MAX_EXPR_DEPTH
  111393. );
  111394. rc = SQLITE_ERROR;
  111395. }else if( rc==SQLITE_ERROR ){
  111396. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  111397. }
  111398. }
  111399. return rc;
  111400. }
  111401. /*
  111402. ** Free a single node of an expression tree.
  111403. */
  111404. static void fts3FreeExprNode(Fts3Expr *p){
  111405. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  111406. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  111407. sqlite3_free(p->aMI);
  111408. sqlite3_free(p);
  111409. }
  111410. /*
  111411. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  111412. **
  111413. ** This function would be simpler if it recursively called itself. But
  111414. ** that would mean passing a sufficiently large expression to ExprParse()
  111415. ** could cause a stack overflow.
  111416. */
  111417. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  111418. Fts3Expr *p;
  111419. assert( pDel==0 || pDel->pParent==0 );
  111420. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  111421. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  111422. }
  111423. while( p ){
  111424. Fts3Expr *pParent = p->pParent;
  111425. fts3FreeExprNode(p);
  111426. if( pParent && p==pParent->pLeft && pParent->pRight ){
  111427. p = pParent->pRight;
  111428. while( p && (p->pLeft || p->pRight) ){
  111429. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  111430. p = (p->pLeft ? p->pLeft : p->pRight);
  111431. }
  111432. }else{
  111433. p = pParent;
  111434. }
  111435. }
  111436. }
  111437. /****************************************************************************
  111438. *****************************************************************************
  111439. ** Everything after this point is just test code.
  111440. */
  111441. #ifdef SQLITE_TEST
  111442. /* #include <stdio.h> */
  111443. /*
  111444. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  111445. */
  111446. static int queryTestTokenizer(
  111447. sqlite3 *db,
  111448. const char *zName,
  111449. const sqlite3_tokenizer_module **pp
  111450. ){
  111451. int rc;
  111452. sqlite3_stmt *pStmt;
  111453. const char zSql[] = "SELECT fts3_tokenizer(?)";
  111454. *pp = 0;
  111455. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  111456. if( rc!=SQLITE_OK ){
  111457. return rc;
  111458. }
  111459. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  111460. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  111461. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  111462. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  111463. }
  111464. }
  111465. return sqlite3_finalize(pStmt);
  111466. }
  111467. /*
  111468. ** Return a pointer to a buffer containing a text representation of the
  111469. ** expression passed as the first argument. The buffer is obtained from
  111470. ** sqlite3_malloc(). It is the responsibility of the caller to use
  111471. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  111472. ** NULL is returned.
  111473. **
  111474. ** If the second argument is not NULL, then its contents are prepended to
  111475. ** the returned expression text and then freed using sqlite3_free().
  111476. */
  111477. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  111478. if( pExpr==0 ){
  111479. return sqlite3_mprintf("");
  111480. }
  111481. switch( pExpr->eType ){
  111482. case FTSQUERY_PHRASE: {
  111483. Fts3Phrase *pPhrase = pExpr->pPhrase;
  111484. int i;
  111485. zBuf = sqlite3_mprintf(
  111486. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  111487. for(i=0; zBuf && i<pPhrase->nToken; i++){
  111488. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  111489. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  111490. (pPhrase->aToken[i].isPrefix?"+":"")
  111491. );
  111492. }
  111493. return zBuf;
  111494. }
  111495. case FTSQUERY_NEAR:
  111496. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  111497. break;
  111498. case FTSQUERY_NOT:
  111499. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  111500. break;
  111501. case FTSQUERY_AND:
  111502. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  111503. break;
  111504. case FTSQUERY_OR:
  111505. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  111506. break;
  111507. }
  111508. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  111509. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  111510. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  111511. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  111512. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  111513. return zBuf;
  111514. }
  111515. /*
  111516. ** This is the implementation of a scalar SQL function used to test the
  111517. ** expression parser. It should be called as follows:
  111518. **
  111519. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  111520. **
  111521. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  111522. ** to parse the query expression (see README.tokenizers). The second argument
  111523. ** is the query expression to parse. Each subsequent argument is the name
  111524. ** of a column of the fts3 table that the query expression may refer to.
  111525. ** For example:
  111526. **
  111527. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  111528. */
  111529. static void fts3ExprTest(
  111530. sqlite3_context *context,
  111531. int argc,
  111532. sqlite3_value **argv
  111533. ){
  111534. sqlite3_tokenizer_module const *pModule = 0;
  111535. sqlite3_tokenizer *pTokenizer = 0;
  111536. int rc;
  111537. char **azCol = 0;
  111538. const char *zExpr;
  111539. int nExpr;
  111540. int nCol;
  111541. int ii;
  111542. Fts3Expr *pExpr;
  111543. char *zBuf = 0;
  111544. sqlite3 *db = sqlite3_context_db_handle(context);
  111545. if( argc<3 ){
  111546. sqlite3_result_error(context,
  111547. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  111548. );
  111549. return;
  111550. }
  111551. rc = queryTestTokenizer(db,
  111552. (const char *)sqlite3_value_text(argv[0]), &pModule);
  111553. if( rc==SQLITE_NOMEM ){
  111554. sqlite3_result_error_nomem(context);
  111555. goto exprtest_out;
  111556. }else if( !pModule ){
  111557. sqlite3_result_error(context, "No such tokenizer module", -1);
  111558. goto exprtest_out;
  111559. }
  111560. rc = pModule->xCreate(0, 0, &pTokenizer);
  111561. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  111562. if( rc==SQLITE_NOMEM ){
  111563. sqlite3_result_error_nomem(context);
  111564. goto exprtest_out;
  111565. }
  111566. pTokenizer->pModule = pModule;
  111567. zExpr = (const char *)sqlite3_value_text(argv[1]);
  111568. nExpr = sqlite3_value_bytes(argv[1]);
  111569. nCol = argc-2;
  111570. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  111571. if( !azCol ){
  111572. sqlite3_result_error_nomem(context);
  111573. goto exprtest_out;
  111574. }
  111575. for(ii=0; ii<nCol; ii++){
  111576. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  111577. }
  111578. if( sqlite3_user_data(context) ){
  111579. char *zDummy = 0;
  111580. rc = sqlite3Fts3ExprParse(
  111581. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  111582. );
  111583. assert( rc==SQLITE_OK || pExpr==0 );
  111584. sqlite3_free(zDummy);
  111585. }else{
  111586. rc = fts3ExprParseUnbalanced(
  111587. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  111588. );
  111589. }
  111590. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  111591. sqlite3Fts3ExprFree(pExpr);
  111592. sqlite3_result_error(context, "Error parsing expression", -1);
  111593. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  111594. sqlite3_result_error_nomem(context);
  111595. }else{
  111596. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  111597. sqlite3_free(zBuf);
  111598. }
  111599. sqlite3Fts3ExprFree(pExpr);
  111600. exprtest_out:
  111601. if( pModule && pTokenizer ){
  111602. rc = pModule->xDestroy(pTokenizer);
  111603. }
  111604. sqlite3_free(azCol);
  111605. }
  111606. /*
  111607. ** Register the query expression parser test function fts3_exprtest()
  111608. ** with database connection db.
  111609. */
  111610. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  111611. int rc = sqlite3_create_function(
  111612. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  111613. );
  111614. if( rc==SQLITE_OK ){
  111615. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  111616. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  111617. );
  111618. }
  111619. return rc;
  111620. }
  111621. #endif
  111622. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  111623. /************** End of fts3_expr.c *******************************************/
  111624. /************** Begin file fts3_hash.c ***************************************/
  111625. /*
  111626. ** 2001 September 22
  111627. **
  111628. ** The author disclaims copyright to this source code. In place of
  111629. ** a legal notice, here is a blessing:
  111630. **
  111631. ** May you do good and not evil.
  111632. ** May you find forgiveness for yourself and forgive others.
  111633. ** May you share freely, never taking more than you give.
  111634. **
  111635. *************************************************************************
  111636. ** This is the implementation of generic hash-tables used in SQLite.
  111637. ** We've modified it slightly to serve as a standalone hash table
  111638. ** implementation for the full-text indexing module.
  111639. */
  111640. /*
  111641. ** The code in this file is only compiled if:
  111642. **
  111643. ** * The FTS3 module is being built as an extension
  111644. ** (in which case SQLITE_CORE is not defined), or
  111645. **
  111646. ** * The FTS3 module is being built into the core of
  111647. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  111648. */
  111649. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  111650. /* #include <assert.h> */
  111651. /* #include <stdlib.h> */
  111652. /* #include <string.h> */
  111653. /*
  111654. ** Malloc and Free functions
  111655. */
  111656. static void *fts3HashMalloc(int n){
  111657. void *p = sqlite3_malloc(n);
  111658. if( p ){
  111659. memset(p, 0, n);
  111660. }
  111661. return p;
  111662. }
  111663. static void fts3HashFree(void *p){
  111664. sqlite3_free(p);
  111665. }
  111666. /* Turn bulk memory into a hash table object by initializing the
  111667. ** fields of the Hash structure.
  111668. **
  111669. ** "pNew" is a pointer to the hash table that is to be initialized.
  111670. ** keyClass is one of the constants
  111671. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  111672. ** determines what kind of key the hash table will use. "copyKey" is
  111673. ** true if the hash table should make its own private copy of keys and
  111674. ** false if it should just use the supplied pointer.
  111675. */
  111676. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  111677. assert( pNew!=0 );
  111678. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  111679. pNew->keyClass = keyClass;
  111680. pNew->copyKey = copyKey;
  111681. pNew->first = 0;
  111682. pNew->count = 0;
  111683. pNew->htsize = 0;
  111684. pNew->ht = 0;
  111685. }
  111686. /* Remove all entries from a hash table. Reclaim all memory.
  111687. ** Call this routine to delete a hash table or to reset a hash table
  111688. ** to the empty state.
  111689. */
  111690. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  111691. Fts3HashElem *elem; /* For looping over all elements of the table */
  111692. assert( pH!=0 );
  111693. elem = pH->first;
  111694. pH->first = 0;
  111695. fts3HashFree(pH->ht);
  111696. pH->ht = 0;
  111697. pH->htsize = 0;
  111698. while( elem ){
  111699. Fts3HashElem *next_elem = elem->next;
  111700. if( pH->copyKey && elem->pKey ){
  111701. fts3HashFree(elem->pKey);
  111702. }
  111703. fts3HashFree(elem);
  111704. elem = next_elem;
  111705. }
  111706. pH->count = 0;
  111707. }
  111708. /*
  111709. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  111710. */
  111711. static int fts3StrHash(const void *pKey, int nKey){
  111712. const char *z = (const char *)pKey;
  111713. int h = 0;
  111714. if( nKey<=0 ) nKey = (int) strlen(z);
  111715. while( nKey > 0 ){
  111716. h = (h<<3) ^ h ^ *z++;
  111717. nKey--;
  111718. }
  111719. return h & 0x7fffffff;
  111720. }
  111721. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  111722. if( n1!=n2 ) return 1;
  111723. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  111724. }
  111725. /*
  111726. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  111727. */
  111728. static int fts3BinHash(const void *pKey, int nKey){
  111729. int h = 0;
  111730. const char *z = (const char *)pKey;
  111731. while( nKey-- > 0 ){
  111732. h = (h<<3) ^ h ^ *(z++);
  111733. }
  111734. return h & 0x7fffffff;
  111735. }
  111736. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  111737. if( n1!=n2 ) return 1;
  111738. return memcmp(pKey1,pKey2,n1);
  111739. }
  111740. /*
  111741. ** Return a pointer to the appropriate hash function given the key class.
  111742. **
  111743. ** The C syntax in this function definition may be unfamilar to some
  111744. ** programmers, so we provide the following additional explanation:
  111745. **
  111746. ** The name of the function is "ftsHashFunction". The function takes a
  111747. ** single parameter "keyClass". The return value of ftsHashFunction()
  111748. ** is a pointer to another function. Specifically, the return value
  111749. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  111750. ** with types "const void*" and "int" and returns an "int".
  111751. */
  111752. static int (*ftsHashFunction(int keyClass))(const void*,int){
  111753. if( keyClass==FTS3_HASH_STRING ){
  111754. return &fts3StrHash;
  111755. }else{
  111756. assert( keyClass==FTS3_HASH_BINARY );
  111757. return &fts3BinHash;
  111758. }
  111759. }
  111760. /*
  111761. ** Return a pointer to the appropriate hash function given the key class.
  111762. **
  111763. ** For help in interpreted the obscure C code in the function definition,
  111764. ** see the header comment on the previous function.
  111765. */
  111766. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  111767. if( keyClass==FTS3_HASH_STRING ){
  111768. return &fts3StrCompare;
  111769. }else{
  111770. assert( keyClass==FTS3_HASH_BINARY );
  111771. return &fts3BinCompare;
  111772. }
  111773. }
  111774. /* Link an element into the hash table
  111775. */
  111776. static void fts3HashInsertElement(
  111777. Fts3Hash *pH, /* The complete hash table */
  111778. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  111779. Fts3HashElem *pNew /* The element to be inserted */
  111780. ){
  111781. Fts3HashElem *pHead; /* First element already in pEntry */
  111782. pHead = pEntry->chain;
  111783. if( pHead ){
  111784. pNew->next = pHead;
  111785. pNew->prev = pHead->prev;
  111786. if( pHead->prev ){ pHead->prev->next = pNew; }
  111787. else { pH->first = pNew; }
  111788. pHead->prev = pNew;
  111789. }else{
  111790. pNew->next = pH->first;
  111791. if( pH->first ){ pH->first->prev = pNew; }
  111792. pNew->prev = 0;
  111793. pH->first = pNew;
  111794. }
  111795. pEntry->count++;
  111796. pEntry->chain = pNew;
  111797. }
  111798. /* Resize the hash table so that it cantains "new_size" buckets.
  111799. ** "new_size" must be a power of 2. The hash table might fail
  111800. ** to resize if sqliteMalloc() fails.
  111801. **
  111802. ** Return non-zero if a memory allocation error occurs.
  111803. */
  111804. static int fts3Rehash(Fts3Hash *pH, int new_size){
  111805. struct _fts3ht *new_ht; /* The new hash table */
  111806. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  111807. int (*xHash)(const void*,int); /* The hash function */
  111808. assert( (new_size & (new_size-1))==0 );
  111809. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  111810. if( new_ht==0 ) return 1;
  111811. fts3HashFree(pH->ht);
  111812. pH->ht = new_ht;
  111813. pH->htsize = new_size;
  111814. xHash = ftsHashFunction(pH->keyClass);
  111815. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  111816. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  111817. next_elem = elem->next;
  111818. fts3HashInsertElement(pH, &new_ht[h], elem);
  111819. }
  111820. return 0;
  111821. }
  111822. /* This function (for internal use only) locates an element in an
  111823. ** hash table that matches the given key. The hash for this key has
  111824. ** already been computed and is passed as the 4th parameter.
  111825. */
  111826. static Fts3HashElem *fts3FindElementByHash(
  111827. const Fts3Hash *pH, /* The pH to be searched */
  111828. const void *pKey, /* The key we are searching for */
  111829. int nKey,
  111830. int h /* The hash for this key. */
  111831. ){
  111832. Fts3HashElem *elem; /* Used to loop thru the element list */
  111833. int count; /* Number of elements left to test */
  111834. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  111835. if( pH->ht ){
  111836. struct _fts3ht *pEntry = &pH->ht[h];
  111837. elem = pEntry->chain;
  111838. count = pEntry->count;
  111839. xCompare = ftsCompareFunction(pH->keyClass);
  111840. while( count-- && elem ){
  111841. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  111842. return elem;
  111843. }
  111844. elem = elem->next;
  111845. }
  111846. }
  111847. return 0;
  111848. }
  111849. /* Remove a single entry from the hash table given a pointer to that
  111850. ** element and a hash on the element's key.
  111851. */
  111852. static void fts3RemoveElementByHash(
  111853. Fts3Hash *pH, /* The pH containing "elem" */
  111854. Fts3HashElem* elem, /* The element to be removed from the pH */
  111855. int h /* Hash value for the element */
  111856. ){
  111857. struct _fts3ht *pEntry;
  111858. if( elem->prev ){
  111859. elem->prev->next = elem->next;
  111860. }else{
  111861. pH->first = elem->next;
  111862. }
  111863. if( elem->next ){
  111864. elem->next->prev = elem->prev;
  111865. }
  111866. pEntry = &pH->ht[h];
  111867. if( pEntry->chain==elem ){
  111868. pEntry->chain = elem->next;
  111869. }
  111870. pEntry->count--;
  111871. if( pEntry->count<=0 ){
  111872. pEntry->chain = 0;
  111873. }
  111874. if( pH->copyKey && elem->pKey ){
  111875. fts3HashFree(elem->pKey);
  111876. }
  111877. fts3HashFree( elem );
  111878. pH->count--;
  111879. if( pH->count<=0 ){
  111880. assert( pH->first==0 );
  111881. assert( pH->count==0 );
  111882. fts3HashClear(pH);
  111883. }
  111884. }
  111885. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  111886. const Fts3Hash *pH,
  111887. const void *pKey,
  111888. int nKey
  111889. ){
  111890. int h; /* A hash on key */
  111891. int (*xHash)(const void*,int); /* The hash function */
  111892. if( pH==0 || pH->ht==0 ) return 0;
  111893. xHash = ftsHashFunction(pH->keyClass);
  111894. assert( xHash!=0 );
  111895. h = (*xHash)(pKey,nKey);
  111896. assert( (pH->htsize & (pH->htsize-1))==0 );
  111897. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  111898. }
  111899. /*
  111900. ** Attempt to locate an element of the hash table pH with a key
  111901. ** that matches pKey,nKey. Return the data for this element if it is
  111902. ** found, or NULL if there is no match.
  111903. */
  111904. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  111905. Fts3HashElem *pElem; /* The element that matches key (if any) */
  111906. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  111907. return pElem ? pElem->data : 0;
  111908. }
  111909. /* Insert an element into the hash table pH. The key is pKey,nKey
  111910. ** and the data is "data".
  111911. **
  111912. ** If no element exists with a matching key, then a new
  111913. ** element is created. A copy of the key is made if the copyKey
  111914. ** flag is set. NULL is returned.
  111915. **
  111916. ** If another element already exists with the same key, then the
  111917. ** new data replaces the old data and the old data is returned.
  111918. ** The key is not copied in this instance. If a malloc fails, then
  111919. ** the new data is returned and the hash table is unchanged.
  111920. **
  111921. ** If the "data" parameter to this function is NULL, then the
  111922. ** element corresponding to "key" is removed from the hash table.
  111923. */
  111924. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  111925. Fts3Hash *pH, /* The hash table to insert into */
  111926. const void *pKey, /* The key */
  111927. int nKey, /* Number of bytes in the key */
  111928. void *data /* The data */
  111929. ){
  111930. int hraw; /* Raw hash value of the key */
  111931. int h; /* the hash of the key modulo hash table size */
  111932. Fts3HashElem *elem; /* Used to loop thru the element list */
  111933. Fts3HashElem *new_elem; /* New element added to the pH */
  111934. int (*xHash)(const void*,int); /* The hash function */
  111935. assert( pH!=0 );
  111936. xHash = ftsHashFunction(pH->keyClass);
  111937. assert( xHash!=0 );
  111938. hraw = (*xHash)(pKey, nKey);
  111939. assert( (pH->htsize & (pH->htsize-1))==0 );
  111940. h = hraw & (pH->htsize-1);
  111941. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  111942. if( elem ){
  111943. void *old_data = elem->data;
  111944. if( data==0 ){
  111945. fts3RemoveElementByHash(pH,elem,h);
  111946. }else{
  111947. elem->data = data;
  111948. }
  111949. return old_data;
  111950. }
  111951. if( data==0 ) return 0;
  111952. if( (pH->htsize==0 && fts3Rehash(pH,8))
  111953. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  111954. ){
  111955. pH->count = 0;
  111956. return data;
  111957. }
  111958. assert( pH->htsize>0 );
  111959. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  111960. if( new_elem==0 ) return data;
  111961. if( pH->copyKey && pKey!=0 ){
  111962. new_elem->pKey = fts3HashMalloc( nKey );
  111963. if( new_elem->pKey==0 ){
  111964. fts3HashFree(new_elem);
  111965. return data;
  111966. }
  111967. memcpy((void*)new_elem->pKey, pKey, nKey);
  111968. }else{
  111969. new_elem->pKey = (void*)pKey;
  111970. }
  111971. new_elem->nKey = nKey;
  111972. pH->count++;
  111973. assert( pH->htsize>0 );
  111974. assert( (pH->htsize & (pH->htsize-1))==0 );
  111975. h = hraw & (pH->htsize-1);
  111976. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  111977. new_elem->data = data;
  111978. return 0;
  111979. }
  111980. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  111981. /************** End of fts3_hash.c *******************************************/
  111982. /************** Begin file fts3_porter.c *************************************/
  111983. /*
  111984. ** 2006 September 30
  111985. **
  111986. ** The author disclaims copyright to this source code. In place of
  111987. ** a legal notice, here is a blessing:
  111988. **
  111989. ** May you do good and not evil.
  111990. ** May you find forgiveness for yourself and forgive others.
  111991. ** May you share freely, never taking more than you give.
  111992. **
  111993. *************************************************************************
  111994. ** Implementation of the full-text-search tokenizer that implements
  111995. ** a Porter stemmer.
  111996. */
  111997. /*
  111998. ** The code in this file is only compiled if:
  111999. **
  112000. ** * The FTS3 module is being built as an extension
  112001. ** (in which case SQLITE_CORE is not defined), or
  112002. **
  112003. ** * The FTS3 module is being built into the core of
  112004. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  112005. */
  112006. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  112007. /* #include <assert.h> */
  112008. /* #include <stdlib.h> */
  112009. /* #include <stdio.h> */
  112010. /* #include <string.h> */
  112011. /*
  112012. ** Class derived from sqlite3_tokenizer
  112013. */
  112014. typedef struct porter_tokenizer {
  112015. sqlite3_tokenizer base; /* Base class */
  112016. } porter_tokenizer;
  112017. /*
  112018. ** Class derived from sqlite3_tokenizer_cursor
  112019. */
  112020. typedef struct porter_tokenizer_cursor {
  112021. sqlite3_tokenizer_cursor base;
  112022. const char *zInput; /* input we are tokenizing */
  112023. int nInput; /* size of the input */
  112024. int iOffset; /* current position in zInput */
  112025. int iToken; /* index of next token to be returned */
  112026. char *zToken; /* storage for current token */
  112027. int nAllocated; /* space allocated to zToken buffer */
  112028. } porter_tokenizer_cursor;
  112029. /*
  112030. ** Create a new tokenizer instance.
  112031. */
  112032. static int porterCreate(
  112033. int argc, const char * const *argv,
  112034. sqlite3_tokenizer **ppTokenizer
  112035. ){
  112036. porter_tokenizer *t;
  112037. UNUSED_PARAMETER(argc);
  112038. UNUSED_PARAMETER(argv);
  112039. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  112040. if( t==NULL ) return SQLITE_NOMEM;
  112041. memset(t, 0, sizeof(*t));
  112042. *ppTokenizer = &t->base;
  112043. return SQLITE_OK;
  112044. }
  112045. /*
  112046. ** Destroy a tokenizer
  112047. */
  112048. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  112049. sqlite3_free(pTokenizer);
  112050. return SQLITE_OK;
  112051. }
  112052. /*
  112053. ** Prepare to begin tokenizing a particular string. The input
  112054. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  112055. ** used to incrementally tokenize this string is returned in
  112056. ** *ppCursor.
  112057. */
  112058. static int porterOpen(
  112059. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  112060. const char *zInput, int nInput, /* String to be tokenized */
  112061. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  112062. ){
  112063. porter_tokenizer_cursor *c;
  112064. UNUSED_PARAMETER(pTokenizer);
  112065. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  112066. if( c==NULL ) return SQLITE_NOMEM;
  112067. c->zInput = zInput;
  112068. if( zInput==0 ){
  112069. c->nInput = 0;
  112070. }else if( nInput<0 ){
  112071. c->nInput = (int)strlen(zInput);
  112072. }else{
  112073. c->nInput = nInput;
  112074. }
  112075. c->iOffset = 0; /* start tokenizing at the beginning */
  112076. c->iToken = 0;
  112077. c->zToken = NULL; /* no space allocated, yet. */
  112078. c->nAllocated = 0;
  112079. *ppCursor = &c->base;
  112080. return SQLITE_OK;
  112081. }
  112082. /*
  112083. ** Close a tokenization cursor previously opened by a call to
  112084. ** porterOpen() above.
  112085. */
  112086. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  112087. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  112088. sqlite3_free(c->zToken);
  112089. sqlite3_free(c);
  112090. return SQLITE_OK;
  112091. }
  112092. /*
  112093. ** Vowel or consonant
  112094. */
  112095. static const char cType[] = {
  112096. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  112097. 1, 1, 1, 2, 1
  112098. };
  112099. /*
  112100. ** isConsonant() and isVowel() determine if their first character in
  112101. ** the string they point to is a consonant or a vowel, according
  112102. ** to Porter ruls.
  112103. **
  112104. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  112105. ** 'Y' is a consonant unless it follows another consonant,
  112106. ** in which case it is a vowel.
  112107. **
  112108. ** In these routine, the letters are in reverse order. So the 'y' rule
  112109. ** is that 'y' is a consonant unless it is followed by another
  112110. ** consonent.
  112111. */
  112112. static int isVowel(const char*);
  112113. static int isConsonant(const char *z){
  112114. int j;
  112115. char x = *z;
  112116. if( x==0 ) return 0;
  112117. assert( x>='a' && x<='z' );
  112118. j = cType[x-'a'];
  112119. if( j<2 ) return j;
  112120. return z[1]==0 || isVowel(z + 1);
  112121. }
  112122. static int isVowel(const char *z){
  112123. int j;
  112124. char x = *z;
  112125. if( x==0 ) return 0;
  112126. assert( x>='a' && x<='z' );
  112127. j = cType[x-'a'];
  112128. if( j<2 ) return 1-j;
  112129. return isConsonant(z + 1);
  112130. }
  112131. /*
  112132. ** Let any sequence of one or more vowels be represented by V and let
  112133. ** C be sequence of one or more consonants. Then every word can be
  112134. ** represented as:
  112135. **
  112136. ** [C] (VC){m} [V]
  112137. **
  112138. ** In prose: A word is an optional consonant followed by zero or
  112139. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  112140. ** number of vowel consonant pairs. This routine computes the value
  112141. ** of m for the first i bytes of a word.
  112142. **
  112143. ** Return true if the m-value for z is 1 or more. In other words,
  112144. ** return true if z contains at least one vowel that is followed
  112145. ** by a consonant.
  112146. **
  112147. ** In this routine z[] is in reverse order. So we are really looking
  112148. ** for an instance of of a consonant followed by a vowel.
  112149. */
  112150. static int m_gt_0(const char *z){
  112151. while( isVowel(z) ){ z++; }
  112152. if( *z==0 ) return 0;
  112153. while( isConsonant(z) ){ z++; }
  112154. return *z!=0;
  112155. }
  112156. /* Like mgt0 above except we are looking for a value of m which is
  112157. ** exactly 1
  112158. */
  112159. static int m_eq_1(const char *z){
  112160. while( isVowel(z) ){ z++; }
  112161. if( *z==0 ) return 0;
  112162. while( isConsonant(z) ){ z++; }
  112163. if( *z==0 ) return 0;
  112164. while( isVowel(z) ){ z++; }
  112165. if( *z==0 ) return 1;
  112166. while( isConsonant(z) ){ z++; }
  112167. return *z==0;
  112168. }
  112169. /* Like mgt0 above except we are looking for a value of m>1 instead
  112170. ** or m>0
  112171. */
  112172. static int m_gt_1(const char *z){
  112173. while( isVowel(z) ){ z++; }
  112174. if( *z==0 ) return 0;
  112175. while( isConsonant(z) ){ z++; }
  112176. if( *z==0 ) return 0;
  112177. while( isVowel(z) ){ z++; }
  112178. if( *z==0 ) return 0;
  112179. while( isConsonant(z) ){ z++; }
  112180. return *z!=0;
  112181. }
  112182. /*
  112183. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  112184. */
  112185. static int hasVowel(const char *z){
  112186. while( isConsonant(z) ){ z++; }
  112187. return *z!=0;
  112188. }
  112189. /*
  112190. ** Return TRUE if the word ends in a double consonant.
  112191. **
  112192. ** The text is reversed here. So we are really looking at
  112193. ** the first two characters of z[].
  112194. */
  112195. static int doubleConsonant(const char *z){
  112196. return isConsonant(z) && z[0]==z[1];
  112197. }
  112198. /*
  112199. ** Return TRUE if the word ends with three letters which
  112200. ** are consonant-vowel-consonent and where the final consonant
  112201. ** is not 'w', 'x', or 'y'.
  112202. **
  112203. ** The word is reversed here. So we are really checking the
  112204. ** first three letters and the first one cannot be in [wxy].
  112205. */
  112206. static int star_oh(const char *z){
  112207. return
  112208. isConsonant(z) &&
  112209. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  112210. isVowel(z+1) &&
  112211. isConsonant(z+2);
  112212. }
  112213. /*
  112214. ** If the word ends with zFrom and xCond() is true for the stem
  112215. ** of the word that preceeds the zFrom ending, then change the
  112216. ** ending to zTo.
  112217. **
  112218. ** The input word *pz and zFrom are both in reverse order. zTo
  112219. ** is in normal order.
  112220. **
  112221. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  112222. ** match. Not that TRUE is returned even if xCond() fails and
  112223. ** no substitution occurs.
  112224. */
  112225. static int stem(
  112226. char **pz, /* The word being stemmed (Reversed) */
  112227. const char *zFrom, /* If the ending matches this... (Reversed) */
  112228. const char *zTo, /* ... change the ending to this (not reversed) */
  112229. int (*xCond)(const char*) /* Condition that must be true */
  112230. ){
  112231. char *z = *pz;
  112232. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  112233. if( *zFrom!=0 ) return 0;
  112234. if( xCond && !xCond(z) ) return 1;
  112235. while( *zTo ){
  112236. *(--z) = *(zTo++);
  112237. }
  112238. *pz = z;
  112239. return 1;
  112240. }
  112241. /*
  112242. ** This is the fallback stemmer used when the porter stemmer is
  112243. ** inappropriate. The input word is copied into the output with
  112244. ** US-ASCII case folding. If the input word is too long (more
  112245. ** than 20 bytes if it contains no digits or more than 6 bytes if
  112246. ** it contains digits) then word is truncated to 20 or 6 bytes
  112247. ** by taking 10 or 3 bytes from the beginning and end.
  112248. */
  112249. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  112250. int i, mx, j;
  112251. int hasDigit = 0;
  112252. for(i=0; i<nIn; i++){
  112253. char c = zIn[i];
  112254. if( c>='A' && c<='Z' ){
  112255. zOut[i] = c - 'A' + 'a';
  112256. }else{
  112257. if( c>='0' && c<='9' ) hasDigit = 1;
  112258. zOut[i] = c;
  112259. }
  112260. }
  112261. mx = hasDigit ? 3 : 10;
  112262. if( nIn>mx*2 ){
  112263. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  112264. zOut[j] = zOut[i];
  112265. }
  112266. i = j;
  112267. }
  112268. zOut[i] = 0;
  112269. *pnOut = i;
  112270. }
  112271. /*
  112272. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  112273. ** zOut is at least big enough to hold nIn bytes. Write the actual
  112274. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  112275. **
  112276. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  112277. ** are converted to lower case. Upper-case UTF characters are
  112278. ** unchanged.
  112279. **
  112280. ** Words that are longer than about 20 bytes are stemmed by retaining
  112281. ** a few bytes from the beginning and the end of the word. If the
  112282. ** word contains digits, 3 bytes are taken from the beginning and
  112283. ** 3 bytes from the end. For long words without digits, 10 bytes
  112284. ** are taken from each end. US-ASCII case folding still applies.
  112285. **
  112286. ** If the input word contains not digits but does characters not
  112287. ** in [a-zA-Z] then no stemming is attempted and this routine just
  112288. ** copies the input into the input into the output with US-ASCII
  112289. ** case folding.
  112290. **
  112291. ** Stemming never increases the length of the word. So there is
  112292. ** no chance of overflowing the zOut buffer.
  112293. */
  112294. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  112295. int i, j;
  112296. char zReverse[28];
  112297. char *z, *z2;
  112298. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  112299. /* The word is too big or too small for the porter stemmer.
  112300. ** Fallback to the copy stemmer */
  112301. copy_stemmer(zIn, nIn, zOut, pnOut);
  112302. return;
  112303. }
  112304. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  112305. char c = zIn[i];
  112306. if( c>='A' && c<='Z' ){
  112307. zReverse[j] = c + 'a' - 'A';
  112308. }else if( c>='a' && c<='z' ){
  112309. zReverse[j] = c;
  112310. }else{
  112311. /* The use of a character not in [a-zA-Z] means that we fallback
  112312. ** to the copy stemmer */
  112313. copy_stemmer(zIn, nIn, zOut, pnOut);
  112314. return;
  112315. }
  112316. }
  112317. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  112318. z = &zReverse[j+1];
  112319. /* Step 1a */
  112320. if( z[0]=='s' ){
  112321. if(
  112322. !stem(&z, "sess", "ss", 0) &&
  112323. !stem(&z, "sei", "i", 0) &&
  112324. !stem(&z, "ss", "ss", 0)
  112325. ){
  112326. z++;
  112327. }
  112328. }
  112329. /* Step 1b */
  112330. z2 = z;
  112331. if( stem(&z, "dee", "ee", m_gt_0) ){
  112332. /* Do nothing. The work was all in the test */
  112333. }else if(
  112334. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  112335. && z!=z2
  112336. ){
  112337. if( stem(&z, "ta", "ate", 0) ||
  112338. stem(&z, "lb", "ble", 0) ||
  112339. stem(&z, "zi", "ize", 0) ){
  112340. /* Do nothing. The work was all in the test */
  112341. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  112342. z++;
  112343. }else if( m_eq_1(z) && star_oh(z) ){
  112344. *(--z) = 'e';
  112345. }
  112346. }
  112347. /* Step 1c */
  112348. if( z[0]=='y' && hasVowel(z+1) ){
  112349. z[0] = 'i';
  112350. }
  112351. /* Step 2 */
  112352. switch( z[1] ){
  112353. case 'a':
  112354. stem(&z, "lanoita", "ate", m_gt_0) ||
  112355. stem(&z, "lanoit", "tion", m_gt_0);
  112356. break;
  112357. case 'c':
  112358. stem(&z, "icne", "ence", m_gt_0) ||
  112359. stem(&z, "icna", "ance", m_gt_0);
  112360. break;
  112361. case 'e':
  112362. stem(&z, "rezi", "ize", m_gt_0);
  112363. break;
  112364. case 'g':
  112365. stem(&z, "igol", "log", m_gt_0);
  112366. break;
  112367. case 'l':
  112368. stem(&z, "ilb", "ble", m_gt_0) ||
  112369. stem(&z, "illa", "al", m_gt_0) ||
  112370. stem(&z, "iltne", "ent", m_gt_0) ||
  112371. stem(&z, "ile", "e", m_gt_0) ||
  112372. stem(&z, "ilsuo", "ous", m_gt_0);
  112373. break;
  112374. case 'o':
  112375. stem(&z, "noitazi", "ize", m_gt_0) ||
  112376. stem(&z, "noita", "ate", m_gt_0) ||
  112377. stem(&z, "rota", "ate", m_gt_0);
  112378. break;
  112379. case 's':
  112380. stem(&z, "msila", "al", m_gt_0) ||
  112381. stem(&z, "ssenevi", "ive", m_gt_0) ||
  112382. stem(&z, "ssenluf", "ful", m_gt_0) ||
  112383. stem(&z, "ssensuo", "ous", m_gt_0);
  112384. break;
  112385. case 't':
  112386. stem(&z, "itila", "al", m_gt_0) ||
  112387. stem(&z, "itivi", "ive", m_gt_0) ||
  112388. stem(&z, "itilib", "ble", m_gt_0);
  112389. break;
  112390. }
  112391. /* Step 3 */
  112392. switch( z[0] ){
  112393. case 'e':
  112394. stem(&z, "etaci", "ic", m_gt_0) ||
  112395. stem(&z, "evita", "", m_gt_0) ||
  112396. stem(&z, "ezila", "al", m_gt_0);
  112397. break;
  112398. case 'i':
  112399. stem(&z, "itici", "ic", m_gt_0);
  112400. break;
  112401. case 'l':
  112402. stem(&z, "laci", "ic", m_gt_0) ||
  112403. stem(&z, "luf", "", m_gt_0);
  112404. break;
  112405. case 's':
  112406. stem(&z, "ssen", "", m_gt_0);
  112407. break;
  112408. }
  112409. /* Step 4 */
  112410. switch( z[1] ){
  112411. case 'a':
  112412. if( z[0]=='l' && m_gt_1(z+2) ){
  112413. z += 2;
  112414. }
  112415. break;
  112416. case 'c':
  112417. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  112418. z += 4;
  112419. }
  112420. break;
  112421. case 'e':
  112422. if( z[0]=='r' && m_gt_1(z+2) ){
  112423. z += 2;
  112424. }
  112425. break;
  112426. case 'i':
  112427. if( z[0]=='c' && m_gt_1(z+2) ){
  112428. z += 2;
  112429. }
  112430. break;
  112431. case 'l':
  112432. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  112433. z += 4;
  112434. }
  112435. break;
  112436. case 'n':
  112437. if( z[0]=='t' ){
  112438. if( z[2]=='a' ){
  112439. if( m_gt_1(z+3) ){
  112440. z += 3;
  112441. }
  112442. }else if( z[2]=='e' ){
  112443. stem(&z, "tneme", "", m_gt_1) ||
  112444. stem(&z, "tnem", "", m_gt_1) ||
  112445. stem(&z, "tne", "", m_gt_1);
  112446. }
  112447. }
  112448. break;
  112449. case 'o':
  112450. if( z[0]=='u' ){
  112451. if( m_gt_1(z+2) ){
  112452. z += 2;
  112453. }
  112454. }else if( z[3]=='s' || z[3]=='t' ){
  112455. stem(&z, "noi", "", m_gt_1);
  112456. }
  112457. break;
  112458. case 's':
  112459. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  112460. z += 3;
  112461. }
  112462. break;
  112463. case 't':
  112464. stem(&z, "eta", "", m_gt_1) ||
  112465. stem(&z, "iti", "", m_gt_1);
  112466. break;
  112467. case 'u':
  112468. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  112469. z += 3;
  112470. }
  112471. break;
  112472. case 'v':
  112473. case 'z':
  112474. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  112475. z += 3;
  112476. }
  112477. break;
  112478. }
  112479. /* Step 5a */
  112480. if( z[0]=='e' ){
  112481. if( m_gt_1(z+1) ){
  112482. z++;
  112483. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  112484. z++;
  112485. }
  112486. }
  112487. /* Step 5b */
  112488. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  112489. z++;
  112490. }
  112491. /* z[] is now the stemmed word in reverse order. Flip it back
  112492. ** around into forward order and return.
  112493. */
  112494. *pnOut = i = (int)strlen(z);
  112495. zOut[i] = 0;
  112496. while( *z ){
  112497. zOut[--i] = *(z++);
  112498. }
  112499. }
  112500. /*
  112501. ** Characters that can be part of a token. We assume any character
  112502. ** whose value is greater than 0x80 (any UTF character) can be
  112503. ** part of a token. In other words, delimiters all must have
  112504. ** values of 0x7f or lower.
  112505. */
  112506. static const char porterIdChar[] = {
  112507. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  112508. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  112509. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  112510. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  112511. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  112512. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  112513. };
  112514. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  112515. /*
  112516. ** Extract the next token from a tokenization cursor. The cursor must
  112517. ** have been opened by a prior call to porterOpen().
  112518. */
  112519. static int porterNext(
  112520. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  112521. const char **pzToken, /* OUT: *pzToken is the token text */
  112522. int *pnBytes, /* OUT: Number of bytes in token */
  112523. int *piStartOffset, /* OUT: Starting offset of token */
  112524. int *piEndOffset, /* OUT: Ending offset of token */
  112525. int *piPosition /* OUT: Position integer of token */
  112526. ){
  112527. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  112528. const char *z = c->zInput;
  112529. while( c->iOffset<c->nInput ){
  112530. int iStartOffset, ch;
  112531. /* Scan past delimiter characters */
  112532. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  112533. c->iOffset++;
  112534. }
  112535. /* Count non-delimiter characters. */
  112536. iStartOffset = c->iOffset;
  112537. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  112538. c->iOffset++;
  112539. }
  112540. if( c->iOffset>iStartOffset ){
  112541. int n = c->iOffset-iStartOffset;
  112542. if( n>c->nAllocated ){
  112543. char *pNew;
  112544. c->nAllocated = n+20;
  112545. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  112546. if( !pNew ) return SQLITE_NOMEM;
  112547. c->zToken = pNew;
  112548. }
  112549. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  112550. *pzToken = c->zToken;
  112551. *piStartOffset = iStartOffset;
  112552. *piEndOffset = c->iOffset;
  112553. *piPosition = c->iToken++;
  112554. return SQLITE_OK;
  112555. }
  112556. }
  112557. return SQLITE_DONE;
  112558. }
  112559. /*
  112560. ** The set of routines that implement the porter-stemmer tokenizer
  112561. */
  112562. static const sqlite3_tokenizer_module porterTokenizerModule = {
  112563. 0,
  112564. porterCreate,
  112565. porterDestroy,
  112566. porterOpen,
  112567. porterClose,
  112568. porterNext,
  112569. 0
  112570. };
  112571. /*
  112572. ** Allocate a new porter tokenizer. Return a pointer to the new
  112573. ** tokenizer in *ppModule
  112574. */
  112575. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  112576. sqlite3_tokenizer_module const**ppModule
  112577. ){
  112578. *ppModule = &porterTokenizerModule;
  112579. }
  112580. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  112581. /************** End of fts3_porter.c *****************************************/
  112582. /************** Begin file fts3_tokenizer.c **********************************/
  112583. /*
  112584. ** 2007 June 22
  112585. **
  112586. ** The author disclaims copyright to this source code. In place of
  112587. ** a legal notice, here is a blessing:
  112588. **
  112589. ** May you do good and not evil.
  112590. ** May you find forgiveness for yourself and forgive others.
  112591. ** May you share freely, never taking more than you give.
  112592. **
  112593. ******************************************************************************
  112594. **
  112595. ** This is part of an SQLite module implementing full-text search.
  112596. ** This particular file implements the generic tokenizer interface.
  112597. */
  112598. /*
  112599. ** The code in this file is only compiled if:
  112600. **
  112601. ** * The FTS3 module is being built as an extension
  112602. ** (in which case SQLITE_CORE is not defined), or
  112603. **
  112604. ** * The FTS3 module is being built into the core of
  112605. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  112606. */
  112607. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  112608. /* #include <assert.h> */
  112609. /* #include <string.h> */
  112610. /*
  112611. ** Implementation of the SQL scalar function for accessing the underlying
  112612. ** hash table. This function may be called as follows:
  112613. **
  112614. ** SELECT <function-name>(<key-name>);
  112615. ** SELECT <function-name>(<key-name>, <pointer>);
  112616. **
  112617. ** where <function-name> is the name passed as the second argument
  112618. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  112619. **
  112620. ** If the <pointer> argument is specified, it must be a blob value
  112621. ** containing a pointer to be stored as the hash data corresponding
  112622. ** to the string <key-name>. If <pointer> is not specified, then
  112623. ** the string <key-name> must already exist in the has table. Otherwise,
  112624. ** an error is returned.
  112625. **
  112626. ** Whether or not the <pointer> argument is specified, the value returned
  112627. ** is a blob containing the pointer stored as the hash data corresponding
  112628. ** to string <key-name> (after the hash-table is updated, if applicable).
  112629. */
  112630. static void scalarFunc(
  112631. sqlite3_context *context,
  112632. int argc,
  112633. sqlite3_value **argv
  112634. ){
  112635. Fts3Hash *pHash;
  112636. void *pPtr = 0;
  112637. const unsigned char *zName;
  112638. int nName;
  112639. assert( argc==1 || argc==2 );
  112640. pHash = (Fts3Hash *)sqlite3_user_data(context);
  112641. zName = sqlite3_value_text(argv[0]);
  112642. nName = sqlite3_value_bytes(argv[0])+1;
  112643. if( argc==2 ){
  112644. void *pOld;
  112645. int n = sqlite3_value_bytes(argv[1]);
  112646. if( n!=sizeof(pPtr) ){
  112647. sqlite3_result_error(context, "argument type mismatch", -1);
  112648. return;
  112649. }
  112650. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  112651. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  112652. if( pOld==pPtr ){
  112653. sqlite3_result_error(context, "out of memory", -1);
  112654. return;
  112655. }
  112656. }else{
  112657. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  112658. if( !pPtr ){
  112659. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  112660. sqlite3_result_error(context, zErr, -1);
  112661. sqlite3_free(zErr);
  112662. return;
  112663. }
  112664. }
  112665. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  112666. }
  112667. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  112668. static const char isFtsIdChar[] = {
  112669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  112670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  112671. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  112672. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  112673. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  112674. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  112675. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  112676. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  112677. };
  112678. return (c&0x80 || isFtsIdChar[(int)(c)]);
  112679. }
  112680. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  112681. const char *z1;
  112682. const char *z2 = 0;
  112683. /* Find the start of the next token. */
  112684. z1 = zStr;
  112685. while( z2==0 ){
  112686. char c = *z1;
  112687. switch( c ){
  112688. case '\0': return 0; /* No more tokens here */
  112689. case '\'':
  112690. case '"':
  112691. case '`': {
  112692. z2 = z1;
  112693. while( *++z2 && (*z2!=c || *++z2==c) );
  112694. break;
  112695. }
  112696. case '[':
  112697. z2 = &z1[1];
  112698. while( *z2 && z2[0]!=']' ) z2++;
  112699. if( *z2 ) z2++;
  112700. break;
  112701. default:
  112702. if( sqlite3Fts3IsIdChar(*z1) ){
  112703. z2 = &z1[1];
  112704. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  112705. }else{
  112706. z1++;
  112707. }
  112708. }
  112709. }
  112710. *pn = (int)(z2-z1);
  112711. return z1;
  112712. }
  112713. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  112714. Fts3Hash *pHash, /* Tokenizer hash table */
  112715. const char *zArg, /* Tokenizer name */
  112716. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  112717. char **pzErr /* OUT: Set to malloced error message */
  112718. ){
  112719. int rc;
  112720. char *z = (char *)zArg;
  112721. int n = 0;
  112722. char *zCopy;
  112723. char *zEnd; /* Pointer to nul-term of zCopy */
  112724. sqlite3_tokenizer_module *m;
  112725. zCopy = sqlite3_mprintf("%s", zArg);
  112726. if( !zCopy ) return SQLITE_NOMEM;
  112727. zEnd = &zCopy[strlen(zCopy)];
  112728. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  112729. z[n] = '\0';
  112730. sqlite3Fts3Dequote(z);
  112731. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  112732. if( !m ){
  112733. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  112734. rc = SQLITE_ERROR;
  112735. }else{
  112736. char const **aArg = 0;
  112737. int iArg = 0;
  112738. z = &z[n+1];
  112739. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  112740. int nNew = sizeof(char *)*(iArg+1);
  112741. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  112742. if( !aNew ){
  112743. sqlite3_free(zCopy);
  112744. sqlite3_free((void *)aArg);
  112745. return SQLITE_NOMEM;
  112746. }
  112747. aArg = aNew;
  112748. aArg[iArg++] = z;
  112749. z[n] = '\0';
  112750. sqlite3Fts3Dequote(z);
  112751. z = &z[n+1];
  112752. }
  112753. rc = m->xCreate(iArg, aArg, ppTok);
  112754. assert( rc!=SQLITE_OK || *ppTok );
  112755. if( rc!=SQLITE_OK ){
  112756. *pzErr = sqlite3_mprintf("unknown tokenizer");
  112757. }else{
  112758. (*ppTok)->pModule = m;
  112759. }
  112760. sqlite3_free((void *)aArg);
  112761. }
  112762. sqlite3_free(zCopy);
  112763. return rc;
  112764. }
  112765. #ifdef SQLITE_TEST
  112766. #include <tcl.h>
  112767. /* #include <string.h> */
  112768. /*
  112769. ** Implementation of a special SQL scalar function for testing tokenizers
  112770. ** designed to be used in concert with the Tcl testing framework. This
  112771. ** function must be called with two or more arguments:
  112772. **
  112773. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  112774. **
  112775. ** where <function-name> is the name passed as the second argument
  112776. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  112777. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  112778. **
  112779. ** The return value is a string that may be interpreted as a Tcl
  112780. ** list. For each token in the <input-string>, three elements are
  112781. ** added to the returned list. The first is the token position, the
  112782. ** second is the token text (folded, stemmed, etc.) and the third is the
  112783. ** substring of <input-string> associated with the token. For example,
  112784. ** using the built-in "simple" tokenizer:
  112785. **
  112786. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  112787. **
  112788. ** will return the string:
  112789. **
  112790. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  112791. **
  112792. */
  112793. static void testFunc(
  112794. sqlite3_context *context,
  112795. int argc,
  112796. sqlite3_value **argv
  112797. ){
  112798. Fts3Hash *pHash;
  112799. sqlite3_tokenizer_module *p;
  112800. sqlite3_tokenizer *pTokenizer = 0;
  112801. sqlite3_tokenizer_cursor *pCsr = 0;
  112802. const char *zErr = 0;
  112803. const char *zName;
  112804. int nName;
  112805. const char *zInput;
  112806. int nInput;
  112807. const char *azArg[64];
  112808. const char *zToken;
  112809. int nToken = 0;
  112810. int iStart = 0;
  112811. int iEnd = 0;
  112812. int iPos = 0;
  112813. int i;
  112814. Tcl_Obj *pRet;
  112815. if( argc<2 ){
  112816. sqlite3_result_error(context, "insufficient arguments", -1);
  112817. return;
  112818. }
  112819. nName = sqlite3_value_bytes(argv[0]);
  112820. zName = (const char *)sqlite3_value_text(argv[0]);
  112821. nInput = sqlite3_value_bytes(argv[argc-1]);
  112822. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  112823. pHash = (Fts3Hash *)sqlite3_user_data(context);
  112824. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  112825. if( !p ){
  112826. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  112827. sqlite3_result_error(context, zErr, -1);
  112828. sqlite3_free(zErr);
  112829. return;
  112830. }
  112831. pRet = Tcl_NewObj();
  112832. Tcl_IncrRefCount(pRet);
  112833. for(i=1; i<argc-1; i++){
  112834. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  112835. }
  112836. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  112837. zErr = "error in xCreate()";
  112838. goto finish;
  112839. }
  112840. pTokenizer->pModule = p;
  112841. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  112842. zErr = "error in xOpen()";
  112843. goto finish;
  112844. }
  112845. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  112846. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  112847. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  112848. zToken = &zInput[iStart];
  112849. nToken = iEnd-iStart;
  112850. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  112851. }
  112852. if( SQLITE_OK!=p->xClose(pCsr) ){
  112853. zErr = "error in xClose()";
  112854. goto finish;
  112855. }
  112856. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  112857. zErr = "error in xDestroy()";
  112858. goto finish;
  112859. }
  112860. finish:
  112861. if( zErr ){
  112862. sqlite3_result_error(context, zErr, -1);
  112863. }else{
  112864. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  112865. }
  112866. Tcl_DecrRefCount(pRet);
  112867. }
  112868. static
  112869. int registerTokenizer(
  112870. sqlite3 *db,
  112871. char *zName,
  112872. const sqlite3_tokenizer_module *p
  112873. ){
  112874. int rc;
  112875. sqlite3_stmt *pStmt;
  112876. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  112877. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  112878. if( rc!=SQLITE_OK ){
  112879. return rc;
  112880. }
  112881. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  112882. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  112883. sqlite3_step(pStmt);
  112884. return sqlite3_finalize(pStmt);
  112885. }
  112886. static
  112887. int queryTokenizer(
  112888. sqlite3 *db,
  112889. char *zName,
  112890. const sqlite3_tokenizer_module **pp
  112891. ){
  112892. int rc;
  112893. sqlite3_stmt *pStmt;
  112894. const char zSql[] = "SELECT fts3_tokenizer(?)";
  112895. *pp = 0;
  112896. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  112897. if( rc!=SQLITE_OK ){
  112898. return rc;
  112899. }
  112900. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  112901. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  112902. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  112903. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  112904. }
  112905. }
  112906. return sqlite3_finalize(pStmt);
  112907. }
  112908. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  112909. /*
  112910. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  112911. ** This function is used for testing only, it is not included in the
  112912. ** build unless SQLITE_TEST is defined.
  112913. **
  112914. ** The purpose of this is to test that the fts3_tokenizer() function
  112915. ** can be used as designed by the C-code in the queryTokenizer and
  112916. ** registerTokenizer() functions above. These two functions are repeated
  112917. ** in the README.tokenizer file as an example, so it is important to
  112918. ** test them.
  112919. **
  112920. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  112921. ** function with no arguments. An assert() will fail if a problem is
  112922. ** detected. i.e.:
  112923. **
  112924. ** SELECT fts3_tokenizer_internal_test();
  112925. **
  112926. */
  112927. static void intTestFunc(
  112928. sqlite3_context *context,
  112929. int argc,
  112930. sqlite3_value **argv
  112931. ){
  112932. int rc;
  112933. const sqlite3_tokenizer_module *p1;
  112934. const sqlite3_tokenizer_module *p2;
  112935. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  112936. UNUSED_PARAMETER(argc);
  112937. UNUSED_PARAMETER(argv);
  112938. /* Test the query function */
  112939. sqlite3Fts3SimpleTokenizerModule(&p1);
  112940. rc = queryTokenizer(db, "simple", &p2);
  112941. assert( rc==SQLITE_OK );
  112942. assert( p1==p2 );
  112943. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  112944. assert( rc==SQLITE_ERROR );
  112945. assert( p2==0 );
  112946. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  112947. /* Test the storage function */
  112948. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  112949. assert( rc==SQLITE_OK );
  112950. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  112951. assert( rc==SQLITE_OK );
  112952. assert( p2==p1 );
  112953. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  112954. }
  112955. #endif
  112956. /*
  112957. ** Set up SQL objects in database db used to access the contents of
  112958. ** the hash table pointed to by argument pHash. The hash table must
  112959. ** been initialized to use string keys, and to take a private copy
  112960. ** of the key when a value is inserted. i.e. by a call similar to:
  112961. **
  112962. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  112963. **
  112964. ** This function adds a scalar function (see header comment above
  112965. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  112966. ** defined at compilation time, a temporary virtual table (see header
  112967. ** comment above struct HashTableVtab) to the database schema. Both
  112968. ** provide read/write access to the contents of *pHash.
  112969. **
  112970. ** The third argument to this function, zName, is used as the name
  112971. ** of both the scalar and, if created, the virtual table.
  112972. */
  112973. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  112974. sqlite3 *db,
  112975. Fts3Hash *pHash,
  112976. const char *zName
  112977. ){
  112978. int rc = SQLITE_OK;
  112979. void *p = (void *)pHash;
  112980. const int any = SQLITE_ANY;
  112981. #ifdef SQLITE_TEST
  112982. char *zTest = 0;
  112983. char *zTest2 = 0;
  112984. void *pdb = (void *)db;
  112985. zTest = sqlite3_mprintf("%s_test", zName);
  112986. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  112987. if( !zTest || !zTest2 ){
  112988. rc = SQLITE_NOMEM;
  112989. }
  112990. #endif
  112991. if( SQLITE_OK==rc ){
  112992. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  112993. }
  112994. if( SQLITE_OK==rc ){
  112995. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  112996. }
  112997. #ifdef SQLITE_TEST
  112998. if( SQLITE_OK==rc ){
  112999. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  113000. }
  113001. if( SQLITE_OK==rc ){
  113002. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  113003. }
  113004. #endif
  113005. #ifdef SQLITE_TEST
  113006. sqlite3_free(zTest);
  113007. sqlite3_free(zTest2);
  113008. #endif
  113009. return rc;
  113010. }
  113011. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113012. /************** End of fts3_tokenizer.c **************************************/
  113013. /************** Begin file fts3_tokenizer1.c *********************************/
  113014. /*
  113015. ** 2006 Oct 10
  113016. **
  113017. ** The author disclaims copyright to this source code. In place of
  113018. ** a legal notice, here is a blessing:
  113019. **
  113020. ** May you do good and not evil.
  113021. ** May you find forgiveness for yourself and forgive others.
  113022. ** May you share freely, never taking more than you give.
  113023. **
  113024. ******************************************************************************
  113025. **
  113026. ** Implementation of the "simple" full-text-search tokenizer.
  113027. */
  113028. /*
  113029. ** The code in this file is only compiled if:
  113030. **
  113031. ** * The FTS3 module is being built as an extension
  113032. ** (in which case SQLITE_CORE is not defined), or
  113033. **
  113034. ** * The FTS3 module is being built into the core of
  113035. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  113036. */
  113037. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113038. /* #include <assert.h> */
  113039. /* #include <stdlib.h> */
  113040. /* #include <stdio.h> */
  113041. /* #include <string.h> */
  113042. typedef struct simple_tokenizer {
  113043. sqlite3_tokenizer base;
  113044. char delim[128]; /* flag ASCII delimiters */
  113045. } simple_tokenizer;
  113046. typedef struct simple_tokenizer_cursor {
  113047. sqlite3_tokenizer_cursor base;
  113048. const char *pInput; /* input we are tokenizing */
  113049. int nBytes; /* size of the input */
  113050. int iOffset; /* current position in pInput */
  113051. int iToken; /* index of next token to be returned */
  113052. char *pToken; /* storage for current token */
  113053. int nTokenAllocated; /* space allocated to zToken buffer */
  113054. } simple_tokenizer_cursor;
  113055. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  113056. return c<0x80 && t->delim[c];
  113057. }
  113058. static int fts3_isalnum(int x){
  113059. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  113060. }
  113061. /*
  113062. ** Create a new tokenizer instance.
  113063. */
  113064. static int simpleCreate(
  113065. int argc, const char * const *argv,
  113066. sqlite3_tokenizer **ppTokenizer
  113067. ){
  113068. simple_tokenizer *t;
  113069. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  113070. if( t==NULL ) return SQLITE_NOMEM;
  113071. memset(t, 0, sizeof(*t));
  113072. /* TODO(shess) Delimiters need to remain the same from run to run,
  113073. ** else we need to reindex. One solution would be a meta-table to
  113074. ** track such information in the database, then we'd only want this
  113075. ** information on the initial create.
  113076. */
  113077. if( argc>1 ){
  113078. int i, n = (int)strlen(argv[1]);
  113079. for(i=0; i<n; i++){
  113080. unsigned char ch = argv[1][i];
  113081. /* We explicitly don't support UTF-8 delimiters for now. */
  113082. if( ch>=0x80 ){
  113083. sqlite3_free(t);
  113084. return SQLITE_ERROR;
  113085. }
  113086. t->delim[ch] = 1;
  113087. }
  113088. } else {
  113089. /* Mark non-alphanumeric ASCII characters as delimiters */
  113090. int i;
  113091. for(i=1; i<0x80; i++){
  113092. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  113093. }
  113094. }
  113095. *ppTokenizer = &t->base;
  113096. return SQLITE_OK;
  113097. }
  113098. /*
  113099. ** Destroy a tokenizer
  113100. */
  113101. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  113102. sqlite3_free(pTokenizer);
  113103. return SQLITE_OK;
  113104. }
  113105. /*
  113106. ** Prepare to begin tokenizing a particular string. The input
  113107. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  113108. ** used to incrementally tokenize this string is returned in
  113109. ** *ppCursor.
  113110. */
  113111. static int simpleOpen(
  113112. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  113113. const char *pInput, int nBytes, /* String to be tokenized */
  113114. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  113115. ){
  113116. simple_tokenizer_cursor *c;
  113117. UNUSED_PARAMETER(pTokenizer);
  113118. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  113119. if( c==NULL ) return SQLITE_NOMEM;
  113120. c->pInput = pInput;
  113121. if( pInput==0 ){
  113122. c->nBytes = 0;
  113123. }else if( nBytes<0 ){
  113124. c->nBytes = (int)strlen(pInput);
  113125. }else{
  113126. c->nBytes = nBytes;
  113127. }
  113128. c->iOffset = 0; /* start tokenizing at the beginning */
  113129. c->iToken = 0;
  113130. c->pToken = NULL; /* no space allocated, yet. */
  113131. c->nTokenAllocated = 0;
  113132. *ppCursor = &c->base;
  113133. return SQLITE_OK;
  113134. }
  113135. /*
  113136. ** Close a tokenization cursor previously opened by a call to
  113137. ** simpleOpen() above.
  113138. */
  113139. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  113140. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  113141. sqlite3_free(c->pToken);
  113142. sqlite3_free(c);
  113143. return SQLITE_OK;
  113144. }
  113145. /*
  113146. ** Extract the next token from a tokenization cursor. The cursor must
  113147. ** have been opened by a prior call to simpleOpen().
  113148. */
  113149. static int simpleNext(
  113150. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  113151. const char **ppToken, /* OUT: *ppToken is the token text */
  113152. int *pnBytes, /* OUT: Number of bytes in token */
  113153. int *piStartOffset, /* OUT: Starting offset of token */
  113154. int *piEndOffset, /* OUT: Ending offset of token */
  113155. int *piPosition /* OUT: Position integer of token */
  113156. ){
  113157. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  113158. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  113159. unsigned char *p = (unsigned char *)c->pInput;
  113160. while( c->iOffset<c->nBytes ){
  113161. int iStartOffset;
  113162. /* Scan past delimiter characters */
  113163. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  113164. c->iOffset++;
  113165. }
  113166. /* Count non-delimiter characters. */
  113167. iStartOffset = c->iOffset;
  113168. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  113169. c->iOffset++;
  113170. }
  113171. if( c->iOffset>iStartOffset ){
  113172. int i, n = c->iOffset-iStartOffset;
  113173. if( n>c->nTokenAllocated ){
  113174. char *pNew;
  113175. c->nTokenAllocated = n+20;
  113176. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  113177. if( !pNew ) return SQLITE_NOMEM;
  113178. c->pToken = pNew;
  113179. }
  113180. for(i=0; i<n; i++){
  113181. /* TODO(shess) This needs expansion to handle UTF-8
  113182. ** case-insensitivity.
  113183. */
  113184. unsigned char ch = p[iStartOffset+i];
  113185. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  113186. }
  113187. *ppToken = c->pToken;
  113188. *pnBytes = n;
  113189. *piStartOffset = iStartOffset;
  113190. *piEndOffset = c->iOffset;
  113191. *piPosition = c->iToken++;
  113192. return SQLITE_OK;
  113193. }
  113194. }
  113195. return SQLITE_DONE;
  113196. }
  113197. /*
  113198. ** The set of routines that implement the simple tokenizer
  113199. */
  113200. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  113201. 0,
  113202. simpleCreate,
  113203. simpleDestroy,
  113204. simpleOpen,
  113205. simpleClose,
  113206. simpleNext,
  113207. 0,
  113208. };
  113209. /*
  113210. ** Allocate a new simple tokenizer. Return a pointer to the new
  113211. ** tokenizer in *ppModule
  113212. */
  113213. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  113214. sqlite3_tokenizer_module const**ppModule
  113215. ){
  113216. *ppModule = &simpleTokenizerModule;
  113217. }
  113218. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113219. /************** End of fts3_tokenizer1.c *************************************/
  113220. /************** Begin file fts3_tokenize_vtab.c ******************************/
  113221. /*
  113222. ** 2013 Apr 22
  113223. **
  113224. ** The author disclaims copyright to this source code. In place of
  113225. ** a legal notice, here is a blessing:
  113226. **
  113227. ** May you do good and not evil.
  113228. ** May you find forgiveness for yourself and forgive others.
  113229. ** May you share freely, never taking more than you give.
  113230. **
  113231. ******************************************************************************
  113232. **
  113233. ** This file contains code for the "fts3tokenize" virtual table module.
  113234. ** An fts3tokenize virtual table is created as follows:
  113235. **
  113236. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  113237. ** <tokenizer-name>, <arg-1>, ...
  113238. ** );
  113239. **
  113240. ** The table created has the following schema:
  113241. **
  113242. ** CREATE TABLE <tbl>(input, token, start, end, position)
  113243. **
  113244. ** When queried, the query must include a WHERE clause of type:
  113245. **
  113246. ** input = <string>
  113247. **
  113248. ** The virtual table module tokenizes this <string>, using the FTS3
  113249. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  113250. ** statement and returns one row for each token in the result. With
  113251. ** fields set as follows:
  113252. **
  113253. ** input: Always set to a copy of <string>
  113254. ** token: A token from the input.
  113255. ** start: Byte offset of the token within the input <string>.
  113256. ** end: Byte offset of the byte immediately following the end of the
  113257. ** token within the input string.
  113258. ** pos: Token offset of token within input.
  113259. **
  113260. */
  113261. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113262. /* #include <string.h> */
  113263. /* #include <assert.h> */
  113264. typedef struct Fts3tokTable Fts3tokTable;
  113265. typedef struct Fts3tokCursor Fts3tokCursor;
  113266. /*
  113267. ** Virtual table structure.
  113268. */
  113269. struct Fts3tokTable {
  113270. sqlite3_vtab base; /* Base class used by SQLite core */
  113271. const sqlite3_tokenizer_module *pMod;
  113272. sqlite3_tokenizer *pTok;
  113273. };
  113274. /*
  113275. ** Virtual table cursor structure.
  113276. */
  113277. struct Fts3tokCursor {
  113278. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  113279. char *zInput; /* Input string */
  113280. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  113281. int iRowid; /* Current 'rowid' value */
  113282. const char *zToken; /* Current 'token' value */
  113283. int nToken; /* Size of zToken in bytes */
  113284. int iStart; /* Current 'start' value */
  113285. int iEnd; /* Current 'end' value */
  113286. int iPos; /* Current 'pos' value */
  113287. };
  113288. /*
  113289. ** Query FTS for the tokenizer implementation named zName.
  113290. */
  113291. static int fts3tokQueryTokenizer(
  113292. Fts3Hash *pHash,
  113293. const char *zName,
  113294. const sqlite3_tokenizer_module **pp,
  113295. char **pzErr
  113296. ){
  113297. sqlite3_tokenizer_module *p;
  113298. int nName = (int)strlen(zName);
  113299. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  113300. if( !p ){
  113301. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  113302. return SQLITE_ERROR;
  113303. }
  113304. *pp = p;
  113305. return SQLITE_OK;
  113306. }
  113307. /*
  113308. ** The second argument, argv[], is an array of pointers to nul-terminated
  113309. ** strings. This function makes a copy of the array and strings into a
  113310. ** single block of memory. It then dequotes any of the strings that appear
  113311. ** to be quoted.
  113312. **
  113313. ** If successful, output parameter *pazDequote is set to point at the
  113314. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  113315. ** responsible for eventually calling sqlite3_free() to free the array
  113316. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  113317. ** The final value of *pazDequote is undefined in this case.
  113318. */
  113319. static int fts3tokDequoteArray(
  113320. int argc, /* Number of elements in argv[] */
  113321. const char * const *argv, /* Input array */
  113322. char ***pazDequote /* Output array */
  113323. ){
  113324. int rc = SQLITE_OK; /* Return code */
  113325. if( argc==0 ){
  113326. *pazDequote = 0;
  113327. }else{
  113328. int i;
  113329. int nByte = 0;
  113330. char **azDequote;
  113331. for(i=0; i<argc; i++){
  113332. nByte += (int)(strlen(argv[i]) + 1);
  113333. }
  113334. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  113335. if( azDequote==0 ){
  113336. rc = SQLITE_NOMEM;
  113337. }else{
  113338. char *pSpace = (char *)&azDequote[argc];
  113339. for(i=0; i<argc; i++){
  113340. int n = (int)strlen(argv[i]);
  113341. azDequote[i] = pSpace;
  113342. memcpy(pSpace, argv[i], n+1);
  113343. sqlite3Fts3Dequote(pSpace);
  113344. pSpace += (n+1);
  113345. }
  113346. }
  113347. }
  113348. return rc;
  113349. }
  113350. /*
  113351. ** Schema of the tokenizer table.
  113352. */
  113353. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  113354. /*
  113355. ** This function does all the work for both the xConnect and xCreate methods.
  113356. ** These tables have no persistent representation of their own, so xConnect
  113357. ** and xCreate are identical operations.
  113358. **
  113359. ** argv[0]: module name
  113360. ** argv[1]: database name
  113361. ** argv[2]: table name
  113362. ** argv[3]: first argument (tokenizer name)
  113363. */
  113364. static int fts3tokConnectMethod(
  113365. sqlite3 *db, /* Database connection */
  113366. void *pHash, /* Hash table of tokenizers */
  113367. int argc, /* Number of elements in argv array */
  113368. const char * const *argv, /* xCreate/xConnect argument array */
  113369. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  113370. char **pzErr /* OUT: sqlite3_malloc'd error message */
  113371. ){
  113372. Fts3tokTable *pTab;
  113373. const sqlite3_tokenizer_module *pMod = 0;
  113374. sqlite3_tokenizer *pTok = 0;
  113375. int rc;
  113376. char **azDequote = 0;
  113377. int nDequote;
  113378. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  113379. if( rc!=SQLITE_OK ) return rc;
  113380. nDequote = argc-3;
  113381. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  113382. if( rc==SQLITE_OK ){
  113383. const char *zModule;
  113384. if( nDequote<1 ){
  113385. zModule = "simple";
  113386. }else{
  113387. zModule = azDequote[0];
  113388. }
  113389. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  113390. }
  113391. assert( (rc==SQLITE_OK)==(pMod!=0) );
  113392. if( rc==SQLITE_OK ){
  113393. const char * const *azArg = (const char * const *)&azDequote[1];
  113394. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  113395. }
  113396. if( rc==SQLITE_OK ){
  113397. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  113398. if( pTab==0 ){
  113399. rc = SQLITE_NOMEM;
  113400. }
  113401. }
  113402. if( rc==SQLITE_OK ){
  113403. memset(pTab, 0, sizeof(Fts3tokTable));
  113404. pTab->pMod = pMod;
  113405. pTab->pTok = pTok;
  113406. *ppVtab = &pTab->base;
  113407. }else{
  113408. if( pTok ){
  113409. pMod->xDestroy(pTok);
  113410. }
  113411. }
  113412. sqlite3_free(azDequote);
  113413. return rc;
  113414. }
  113415. /*
  113416. ** This function does the work for both the xDisconnect and xDestroy methods.
  113417. ** These tables have no persistent representation of their own, so xDisconnect
  113418. ** and xDestroy are identical operations.
  113419. */
  113420. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  113421. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  113422. pTab->pMod->xDestroy(pTab->pTok);
  113423. sqlite3_free(pTab);
  113424. return SQLITE_OK;
  113425. }
  113426. /*
  113427. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  113428. */
  113429. static int fts3tokBestIndexMethod(
  113430. sqlite3_vtab *pVTab,
  113431. sqlite3_index_info *pInfo
  113432. ){
  113433. int i;
  113434. UNUSED_PARAMETER(pVTab);
  113435. for(i=0; i<pInfo->nConstraint; i++){
  113436. if( pInfo->aConstraint[i].usable
  113437. && pInfo->aConstraint[i].iColumn==0
  113438. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  113439. ){
  113440. pInfo->idxNum = 1;
  113441. pInfo->aConstraintUsage[i].argvIndex = 1;
  113442. pInfo->aConstraintUsage[i].omit = 1;
  113443. pInfo->estimatedCost = 1;
  113444. return SQLITE_OK;
  113445. }
  113446. }
  113447. pInfo->idxNum = 0;
  113448. assert( pInfo->estimatedCost>1000000.0 );
  113449. return SQLITE_OK;
  113450. }
  113451. /*
  113452. ** xOpen - Open a cursor.
  113453. */
  113454. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  113455. Fts3tokCursor *pCsr;
  113456. UNUSED_PARAMETER(pVTab);
  113457. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  113458. if( pCsr==0 ){
  113459. return SQLITE_NOMEM;
  113460. }
  113461. memset(pCsr, 0, sizeof(Fts3tokCursor));
  113462. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  113463. return SQLITE_OK;
  113464. }
  113465. /*
  113466. ** Reset the tokenizer cursor passed as the only argument. As if it had
  113467. ** just been returned by fts3tokOpenMethod().
  113468. */
  113469. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  113470. if( pCsr->pCsr ){
  113471. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  113472. pTab->pMod->xClose(pCsr->pCsr);
  113473. pCsr->pCsr = 0;
  113474. }
  113475. sqlite3_free(pCsr->zInput);
  113476. pCsr->zInput = 0;
  113477. pCsr->zToken = 0;
  113478. pCsr->nToken = 0;
  113479. pCsr->iStart = 0;
  113480. pCsr->iEnd = 0;
  113481. pCsr->iPos = 0;
  113482. pCsr->iRowid = 0;
  113483. }
  113484. /*
  113485. ** xClose - Close a cursor.
  113486. */
  113487. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  113488. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113489. fts3tokResetCursor(pCsr);
  113490. sqlite3_free(pCsr);
  113491. return SQLITE_OK;
  113492. }
  113493. /*
  113494. ** xNext - Advance the cursor to the next row, if any.
  113495. */
  113496. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  113497. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113498. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  113499. int rc; /* Return code */
  113500. pCsr->iRowid++;
  113501. rc = pTab->pMod->xNext(pCsr->pCsr,
  113502. &pCsr->zToken, &pCsr->nToken,
  113503. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  113504. );
  113505. if( rc!=SQLITE_OK ){
  113506. fts3tokResetCursor(pCsr);
  113507. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  113508. }
  113509. return rc;
  113510. }
  113511. /*
  113512. ** xFilter - Initialize a cursor to point at the start of its data.
  113513. */
  113514. static int fts3tokFilterMethod(
  113515. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  113516. int idxNum, /* Strategy index */
  113517. const char *idxStr, /* Unused */
  113518. int nVal, /* Number of elements in apVal */
  113519. sqlite3_value **apVal /* Arguments for the indexing scheme */
  113520. ){
  113521. int rc = SQLITE_ERROR;
  113522. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113523. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  113524. UNUSED_PARAMETER(idxStr);
  113525. UNUSED_PARAMETER(nVal);
  113526. fts3tokResetCursor(pCsr);
  113527. if( idxNum==1 ){
  113528. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  113529. int nByte = sqlite3_value_bytes(apVal[0]);
  113530. pCsr->zInput = sqlite3_malloc(nByte+1);
  113531. if( pCsr->zInput==0 ){
  113532. rc = SQLITE_NOMEM;
  113533. }else{
  113534. memcpy(pCsr->zInput, zByte, nByte);
  113535. pCsr->zInput[nByte] = 0;
  113536. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  113537. if( rc==SQLITE_OK ){
  113538. pCsr->pCsr->pTokenizer = pTab->pTok;
  113539. }
  113540. }
  113541. }
  113542. if( rc!=SQLITE_OK ) return rc;
  113543. return fts3tokNextMethod(pCursor);
  113544. }
  113545. /*
  113546. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  113547. */
  113548. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  113549. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113550. return (pCsr->zToken==0);
  113551. }
  113552. /*
  113553. ** xColumn - Return a column value.
  113554. */
  113555. static int fts3tokColumnMethod(
  113556. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  113557. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  113558. int iCol /* Index of column to read value from */
  113559. ){
  113560. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113561. /* CREATE TABLE x(input, token, start, end, position) */
  113562. switch( iCol ){
  113563. case 0:
  113564. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  113565. break;
  113566. case 1:
  113567. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  113568. break;
  113569. case 2:
  113570. sqlite3_result_int(pCtx, pCsr->iStart);
  113571. break;
  113572. case 3:
  113573. sqlite3_result_int(pCtx, pCsr->iEnd);
  113574. break;
  113575. default:
  113576. assert( iCol==4 );
  113577. sqlite3_result_int(pCtx, pCsr->iPos);
  113578. break;
  113579. }
  113580. return SQLITE_OK;
  113581. }
  113582. /*
  113583. ** xRowid - Return the current rowid for the cursor.
  113584. */
  113585. static int fts3tokRowidMethod(
  113586. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  113587. sqlite_int64 *pRowid /* OUT: Rowid value */
  113588. ){
  113589. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  113590. *pRowid = (sqlite3_int64)pCsr->iRowid;
  113591. return SQLITE_OK;
  113592. }
  113593. /*
  113594. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  113595. ** if successful or an error code if sqlite3_create_module() fails.
  113596. */
  113597. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  113598. static const sqlite3_module fts3tok_module = {
  113599. 0, /* iVersion */
  113600. fts3tokConnectMethod, /* xCreate */
  113601. fts3tokConnectMethod, /* xConnect */
  113602. fts3tokBestIndexMethod, /* xBestIndex */
  113603. fts3tokDisconnectMethod, /* xDisconnect */
  113604. fts3tokDisconnectMethod, /* xDestroy */
  113605. fts3tokOpenMethod, /* xOpen */
  113606. fts3tokCloseMethod, /* xClose */
  113607. fts3tokFilterMethod, /* xFilter */
  113608. fts3tokNextMethod, /* xNext */
  113609. fts3tokEofMethod, /* xEof */
  113610. fts3tokColumnMethod, /* xColumn */
  113611. fts3tokRowidMethod, /* xRowid */
  113612. 0, /* xUpdate */
  113613. 0, /* xBegin */
  113614. 0, /* xSync */
  113615. 0, /* xCommit */
  113616. 0, /* xRollback */
  113617. 0, /* xFindFunction */
  113618. 0, /* xRename */
  113619. 0, /* xSavepoint */
  113620. 0, /* xRelease */
  113621. 0 /* xRollbackTo */
  113622. };
  113623. int rc; /* Return code */
  113624. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  113625. return rc;
  113626. }
  113627. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  113628. /************** End of fts3_tokenize_vtab.c **********************************/
  113629. /************** Begin file fts3_write.c **************************************/
  113630. /*
  113631. ** 2009 Oct 23
  113632. **
  113633. ** The author disclaims copyright to this source code. In place of
  113634. ** a legal notice, here is a blessing:
  113635. **
  113636. ** May you do good and not evil.
  113637. ** May you find forgiveness for yourself and forgive others.
  113638. ** May you share freely, never taking more than you give.
  113639. **
  113640. ******************************************************************************
  113641. **
  113642. ** This file is part of the SQLite FTS3 extension module. Specifically,
  113643. ** this file contains code to insert, update and delete rows from FTS3
  113644. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  113645. ** of the sub-routines used to merge segments are also used by the query
  113646. ** code in fts3.c.
  113647. */
  113648. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  113649. /* #include <string.h> */
  113650. /* #include <assert.h> */
  113651. /* #include <stdlib.h> */
  113652. #define FTS_MAX_APPENDABLE_HEIGHT 16
  113653. /*
  113654. ** When full-text index nodes are loaded from disk, the buffer that they
  113655. ** are loaded into has the following number of bytes of padding at the end
  113656. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  113657. ** of 920 bytes is allocated for it.
  113658. **
  113659. ** This means that if we have a pointer into a buffer containing node data,
  113660. ** it is always safe to read up to two varints from it without risking an
  113661. ** overread, even if the node data is corrupted.
  113662. */
  113663. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  113664. /*
  113665. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  113666. ** memory incrementally instead of all at once. This can be a big performance
  113667. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  113668. ** method before retrieving all query results (as may happen, for example,
  113669. ** if a query has a LIMIT clause).
  113670. **
  113671. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  113672. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  113673. ** The code is written so that the hard lower-limit for each of these values
  113674. ** is 1. Clearly such small values would be inefficient, but can be useful
  113675. ** for testing purposes.
  113676. **
  113677. ** If this module is built with SQLITE_TEST defined, these constants may
  113678. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  113679. ** a Tcl interface to read and write the values.
  113680. */
  113681. #ifdef SQLITE_TEST
  113682. int test_fts3_node_chunksize = (4*1024);
  113683. int test_fts3_node_chunk_threshold = (4*1024)*4;
  113684. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  113685. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  113686. #else
  113687. # define FTS3_NODE_CHUNKSIZE (4*1024)
  113688. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  113689. #endif
  113690. /*
  113691. ** The two values that may be meaningfully bound to the :1 parameter in
  113692. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  113693. */
  113694. #define FTS_STAT_DOCTOTAL 0
  113695. #define FTS_STAT_INCRMERGEHINT 1
  113696. #define FTS_STAT_AUTOINCRMERGE 2
  113697. /*
  113698. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  113699. ** and incremental merge operation that takes place. This is used for
  113700. ** debugging FTS only, it should not usually be turned on in production
  113701. ** systems.
  113702. */
  113703. #ifdef FTS3_LOG_MERGES
  113704. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  113705. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  113706. }
  113707. #else
  113708. #define fts3LogMerge(x, y)
  113709. #endif
  113710. typedef struct PendingList PendingList;
  113711. typedef struct SegmentNode SegmentNode;
  113712. typedef struct SegmentWriter SegmentWriter;
  113713. /*
  113714. ** An instance of the following data structure is used to build doclists
  113715. ** incrementally. See function fts3PendingListAppend() for details.
  113716. */
  113717. struct PendingList {
  113718. int nData;
  113719. char *aData;
  113720. int nSpace;
  113721. sqlite3_int64 iLastDocid;
  113722. sqlite3_int64 iLastCol;
  113723. sqlite3_int64 iLastPos;
  113724. };
  113725. /*
  113726. ** Each cursor has a (possibly empty) linked list of the following objects.
  113727. */
  113728. struct Fts3DeferredToken {
  113729. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  113730. int iCol; /* Column token must occur in */
  113731. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  113732. PendingList *pList; /* Doclist is assembled here */
  113733. };
  113734. /*
  113735. ** An instance of this structure is used to iterate through the terms on
  113736. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  113737. ** this structure are only manipulated by code in this file, opaque handles
  113738. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  113739. ** terms when querying the full-text index. See functions:
  113740. **
  113741. ** sqlite3Fts3SegReaderNew()
  113742. ** sqlite3Fts3SegReaderFree()
  113743. ** sqlite3Fts3SegReaderIterate()
  113744. **
  113745. ** Methods used to manipulate Fts3SegReader structures:
  113746. **
  113747. ** fts3SegReaderNext()
  113748. ** fts3SegReaderFirstDocid()
  113749. ** fts3SegReaderNextDocid()
  113750. */
  113751. struct Fts3SegReader {
  113752. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  113753. u8 bLookup; /* True for a lookup only */
  113754. u8 rootOnly; /* True for a root-only reader */
  113755. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  113756. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  113757. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  113758. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  113759. char *aNode; /* Pointer to node data (or NULL) */
  113760. int nNode; /* Size of buffer at aNode (or 0) */
  113761. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  113762. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  113763. Fts3HashElem **ppNextElem;
  113764. /* Variables set by fts3SegReaderNext(). These may be read directly
  113765. ** by the caller. They are valid from the time SegmentReaderNew() returns
  113766. ** until SegmentReaderNext() returns something other than SQLITE_OK
  113767. ** (i.e. SQLITE_DONE).
  113768. */
  113769. int nTerm; /* Number of bytes in current term */
  113770. char *zTerm; /* Pointer to current term */
  113771. int nTermAlloc; /* Allocated size of zTerm buffer */
  113772. char *aDoclist; /* Pointer to doclist of current entry */
  113773. int nDoclist; /* Size of doclist in current entry */
  113774. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  113775. ** through the current doclist (aDoclist/nDoclist).
  113776. */
  113777. char *pOffsetList;
  113778. int nOffsetList; /* For descending pending seg-readers only */
  113779. sqlite3_int64 iDocid;
  113780. };
  113781. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  113782. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  113783. /*
  113784. ** An instance of this structure is used to create a segment b-tree in the
  113785. ** database. The internal details of this type are only accessed by the
  113786. ** following functions:
  113787. **
  113788. ** fts3SegWriterAdd()
  113789. ** fts3SegWriterFlush()
  113790. ** fts3SegWriterFree()
  113791. */
  113792. struct SegmentWriter {
  113793. SegmentNode *pTree; /* Pointer to interior tree structure */
  113794. sqlite3_int64 iFirst; /* First slot in %_segments written */
  113795. sqlite3_int64 iFree; /* Next free slot in %_segments */
  113796. char *zTerm; /* Pointer to previous term buffer */
  113797. int nTerm; /* Number of bytes in zTerm */
  113798. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  113799. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  113800. int nSize; /* Size of allocation at aData */
  113801. int nData; /* Bytes of data in aData */
  113802. char *aData; /* Pointer to block from malloc() */
  113803. };
  113804. /*
  113805. ** Type SegmentNode is used by the following three functions to create
  113806. ** the interior part of the segment b+-tree structures (everything except
  113807. ** the leaf nodes). These functions and type are only ever used by code
  113808. ** within the fts3SegWriterXXX() family of functions described above.
  113809. **
  113810. ** fts3NodeAddTerm()
  113811. ** fts3NodeWrite()
  113812. ** fts3NodeFree()
  113813. **
  113814. ** When a b+tree is written to the database (either as a result of a merge
  113815. ** or the pending-terms table being flushed), leaves are written into the
  113816. ** database file as soon as they are completely populated. The interior of
  113817. ** the tree is assembled in memory and written out only once all leaves have
  113818. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  113819. ** very large, meaning that the interior of the tree consumes relatively
  113820. ** little memory.
  113821. */
  113822. struct SegmentNode {
  113823. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  113824. SegmentNode *pRight; /* Pointer to right-sibling */
  113825. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  113826. int nEntry; /* Number of terms written to node so far */
  113827. char *zTerm; /* Pointer to previous term buffer */
  113828. int nTerm; /* Number of bytes in zTerm */
  113829. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  113830. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  113831. int nData; /* Bytes of valid data so far */
  113832. char *aData; /* Node data */
  113833. };
  113834. /*
  113835. ** Valid values for the second argument to fts3SqlStmt().
  113836. */
  113837. #define SQL_DELETE_CONTENT 0
  113838. #define SQL_IS_EMPTY 1
  113839. #define SQL_DELETE_ALL_CONTENT 2
  113840. #define SQL_DELETE_ALL_SEGMENTS 3
  113841. #define SQL_DELETE_ALL_SEGDIR 4
  113842. #define SQL_DELETE_ALL_DOCSIZE 5
  113843. #define SQL_DELETE_ALL_STAT 6
  113844. #define SQL_SELECT_CONTENT_BY_ROWID 7
  113845. #define SQL_NEXT_SEGMENT_INDEX 8
  113846. #define SQL_INSERT_SEGMENTS 9
  113847. #define SQL_NEXT_SEGMENTS_ID 10
  113848. #define SQL_INSERT_SEGDIR 11
  113849. #define SQL_SELECT_LEVEL 12
  113850. #define SQL_SELECT_LEVEL_RANGE 13
  113851. #define SQL_SELECT_LEVEL_COUNT 14
  113852. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  113853. #define SQL_DELETE_SEGDIR_LEVEL 16
  113854. #define SQL_DELETE_SEGMENTS_RANGE 17
  113855. #define SQL_CONTENT_INSERT 18
  113856. #define SQL_DELETE_DOCSIZE 19
  113857. #define SQL_REPLACE_DOCSIZE 20
  113858. #define SQL_SELECT_DOCSIZE 21
  113859. #define SQL_SELECT_STAT 22
  113860. #define SQL_REPLACE_STAT 23
  113861. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  113862. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  113863. #define SQL_DELETE_SEGDIR_RANGE 26
  113864. #define SQL_SELECT_ALL_LANGID 27
  113865. #define SQL_FIND_MERGE_LEVEL 28
  113866. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  113867. #define SQL_DELETE_SEGDIR_ENTRY 30
  113868. #define SQL_SHIFT_SEGDIR_ENTRY 31
  113869. #define SQL_SELECT_SEGDIR 32
  113870. #define SQL_CHOMP_SEGDIR 33
  113871. #define SQL_SEGMENT_IS_APPENDABLE 34
  113872. #define SQL_SELECT_INDEXES 35
  113873. #define SQL_SELECT_MXLEVEL 36
  113874. /*
  113875. ** This function is used to obtain an SQLite prepared statement handle
  113876. ** for the statement identified by the second argument. If successful,
  113877. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  113878. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  113879. **
  113880. ** If argument apVal is not NULL, then it must point to an array with
  113881. ** at least as many entries as the requested statement has bound
  113882. ** parameters. The values are bound to the statements parameters before
  113883. ** returning.
  113884. */
  113885. static int fts3SqlStmt(
  113886. Fts3Table *p, /* Virtual table handle */
  113887. int eStmt, /* One of the SQL_XXX constants above */
  113888. sqlite3_stmt **pp, /* OUT: Statement handle */
  113889. sqlite3_value **apVal /* Values to bind to statement */
  113890. ){
  113891. const char *azSql[] = {
  113892. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  113893. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  113894. /* 2 */ "DELETE FROM %Q.'%q_content'",
  113895. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  113896. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  113897. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  113898. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  113899. /* 7 */ "SELECT %s WHERE rowid=?",
  113900. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  113901. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  113902. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  113903. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  113904. /* Return segments in order from oldest to newest.*/
  113905. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113906. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  113907. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113908. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  113909. "ORDER BY level DESC, idx ASC",
  113910. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  113911. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  113912. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  113913. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  113914. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  113915. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  113916. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  113917. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  113918. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  113919. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  113920. /* 24 */ "",
  113921. /* 25 */ "",
  113922. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  113923. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  113924. /* This statement is used to determine which level to read the input from
  113925. ** when performing an incremental merge. It returns the absolute level number
  113926. ** of the oldest level in the db that contains at least ? segments. Or,
  113927. ** if no level in the FTS index contains more than ? segments, the statement
  113928. ** returns zero rows. */
  113929. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  113930. " ORDER BY (level %% 1024) ASC LIMIT 1",
  113931. /* Estimate the upper limit on the number of leaf nodes in a new segment
  113932. ** created by merging the oldest :2 segments from absolute level :1. See
  113933. ** function sqlite3Fts3Incrmerge() for details. */
  113934. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  113935. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  113936. /* SQL_DELETE_SEGDIR_ENTRY
  113937. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  113938. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  113939. /* SQL_SHIFT_SEGDIR_ENTRY
  113940. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  113941. ** to :1. */
  113942. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  113943. /* SQL_SELECT_SEGDIR
  113944. ** Read a single entry from the %_segdir table. The entry from absolute
  113945. ** level :1 with index value :2. */
  113946. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  113947. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  113948. /* SQL_CHOMP_SEGDIR
  113949. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  113950. ** entry located on absolute level :3 with index :4. */
  113951. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  113952. "WHERE level = ? AND idx = ?",
  113953. /* SQL_SEGMENT_IS_APPENDABLE
  113954. ** Return a single row if the segment with end_block=? is appendable. Or
  113955. ** no rows otherwise. */
  113956. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  113957. /* SQL_SELECT_INDEXES
  113958. ** Return the list of valid segment indexes for absolute level ? */
  113959. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  113960. /* SQL_SELECT_MXLEVEL
  113961. ** Return the largest relative level in the FTS index or indexes. */
  113962. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  113963. };
  113964. int rc = SQLITE_OK;
  113965. sqlite3_stmt *pStmt;
  113966. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  113967. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  113968. pStmt = p->aStmt[eStmt];
  113969. if( !pStmt ){
  113970. char *zSql;
  113971. if( eStmt==SQL_CONTENT_INSERT ){
  113972. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  113973. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  113974. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  113975. }else{
  113976. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  113977. }
  113978. if( !zSql ){
  113979. rc = SQLITE_NOMEM;
  113980. }else{
  113981. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  113982. sqlite3_free(zSql);
  113983. assert( rc==SQLITE_OK || pStmt==0 );
  113984. p->aStmt[eStmt] = pStmt;
  113985. }
  113986. }
  113987. if( apVal ){
  113988. int i;
  113989. int nParam = sqlite3_bind_parameter_count(pStmt);
  113990. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  113991. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  113992. }
  113993. }
  113994. *pp = pStmt;
  113995. return rc;
  113996. }
  113997. static int fts3SelectDocsize(
  113998. Fts3Table *pTab, /* FTS3 table handle */
  113999. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  114000. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  114001. ){
  114002. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  114003. int rc; /* Return code */
  114004. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  114005. if( rc==SQLITE_OK ){
  114006. sqlite3_bind_int64(pStmt, 1, iDocid);
  114007. rc = sqlite3_step(pStmt);
  114008. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  114009. rc = sqlite3_reset(pStmt);
  114010. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  114011. pStmt = 0;
  114012. }else{
  114013. rc = SQLITE_OK;
  114014. }
  114015. }
  114016. *ppStmt = pStmt;
  114017. return rc;
  114018. }
  114019. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  114020. Fts3Table *pTab, /* Fts3 table handle */
  114021. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  114022. ){
  114023. sqlite3_stmt *pStmt = 0;
  114024. int rc;
  114025. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  114026. if( rc==SQLITE_OK ){
  114027. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  114028. if( sqlite3_step(pStmt)!=SQLITE_ROW
  114029. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  114030. ){
  114031. rc = sqlite3_reset(pStmt);
  114032. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  114033. pStmt = 0;
  114034. }
  114035. }
  114036. *ppStmt = pStmt;
  114037. return rc;
  114038. }
  114039. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  114040. Fts3Table *pTab, /* Fts3 table handle */
  114041. sqlite3_int64 iDocid, /* Docid to read size data for */
  114042. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  114043. ){
  114044. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  114045. }
  114046. /*
  114047. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  114048. ** array apVal[] to the SQL statement identified by eStmt, the statement
  114049. ** is executed.
  114050. **
  114051. ** Returns SQLITE_OK if the statement is successfully executed, or an
  114052. ** SQLite error code otherwise.
  114053. */
  114054. static void fts3SqlExec(
  114055. int *pRC, /* Result code */
  114056. Fts3Table *p, /* The FTS3 table */
  114057. int eStmt, /* Index of statement to evaluate */
  114058. sqlite3_value **apVal /* Parameters to bind */
  114059. ){
  114060. sqlite3_stmt *pStmt;
  114061. int rc;
  114062. if( *pRC ) return;
  114063. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  114064. if( rc==SQLITE_OK ){
  114065. sqlite3_step(pStmt);
  114066. rc = sqlite3_reset(pStmt);
  114067. }
  114068. *pRC = rc;
  114069. }
  114070. /*
  114071. ** This function ensures that the caller has obtained an exclusive
  114072. ** shared-cache table-lock on the %_segdir table. This is required before
  114073. ** writing data to the fts3 table. If this lock is not acquired first, then
  114074. ** the caller may end up attempting to take this lock as part of committing
  114075. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  114076. ** LOCKED_SHAREDCACHEto a COMMIT command.
  114077. **
  114078. ** It is best to avoid this because if FTS3 returns any error when
  114079. ** committing a transaction, the whole transaction will be rolled back.
  114080. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  114081. ** It can still happen if the user locks the underlying tables directly
  114082. ** instead of accessing them via FTS.
  114083. */
  114084. static int fts3Writelock(Fts3Table *p){
  114085. int rc = SQLITE_OK;
  114086. if( p->nPendingData==0 ){
  114087. sqlite3_stmt *pStmt;
  114088. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  114089. if( rc==SQLITE_OK ){
  114090. sqlite3_bind_null(pStmt, 1);
  114091. sqlite3_step(pStmt);
  114092. rc = sqlite3_reset(pStmt);
  114093. }
  114094. }
  114095. return rc;
  114096. }
  114097. /*
  114098. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  114099. ** Within each language id, a separate index is maintained to store the
  114100. ** document terms, and each configured prefix size (configured the FTS
  114101. ** "prefix=" option). And each index consists of multiple levels ("relative
  114102. ** levels").
  114103. **
  114104. ** All three of these values (the language id, the specific index and the
  114105. ** level within the index) are encoded in 64-bit integer values stored
  114106. ** in the %_segdir table on disk. This function is used to convert three
  114107. ** separate component values into the single 64-bit integer value that
  114108. ** can be used to query the %_segdir table.
  114109. **
  114110. ** Specifically, each language-id/index combination is allocated 1024
  114111. ** 64-bit integer level values ("absolute levels"). The main terms index
  114112. ** for language-id 0 is allocate values 0-1023. The first prefix index
  114113. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  114114. ** Language 1 indexes are allocated immediately following language 0.
  114115. **
  114116. ** So, for a system with nPrefix prefix indexes configured, the block of
  114117. ** absolute levels that corresponds to language-id iLangid and index
  114118. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  114119. */
  114120. static sqlite3_int64 getAbsoluteLevel(
  114121. Fts3Table *p, /* FTS3 table handle */
  114122. int iLangid, /* Language id */
  114123. int iIndex, /* Index in p->aIndex[] */
  114124. int iLevel /* Level of segments */
  114125. ){
  114126. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  114127. assert( iLangid>=0 );
  114128. assert( p->nIndex>0 );
  114129. assert( iIndex>=0 && iIndex<p->nIndex );
  114130. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  114131. return iBase + iLevel;
  114132. }
  114133. /*
  114134. ** Set *ppStmt to a statement handle that may be used to iterate through
  114135. ** all rows in the %_segdir table, from oldest to newest. If successful,
  114136. ** return SQLITE_OK. If an error occurs while preparing the statement,
  114137. ** return an SQLite error code.
  114138. **
  114139. ** There is only ever one instance of this SQL statement compiled for
  114140. ** each FTS3 table.
  114141. **
  114142. ** The statement returns the following columns from the %_segdir table:
  114143. **
  114144. ** 0: idx
  114145. ** 1: start_block
  114146. ** 2: leaves_end_block
  114147. ** 3: end_block
  114148. ** 4: root
  114149. */
  114150. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  114151. Fts3Table *p, /* FTS3 table */
  114152. int iLangid, /* Language being queried */
  114153. int iIndex, /* Index for p->aIndex[] */
  114154. int iLevel, /* Level to select (relative level) */
  114155. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  114156. ){
  114157. int rc;
  114158. sqlite3_stmt *pStmt = 0;
  114159. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  114160. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  114161. assert( iIndex>=0 && iIndex<p->nIndex );
  114162. if( iLevel<0 ){
  114163. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  114164. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  114165. if( rc==SQLITE_OK ){
  114166. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  114167. sqlite3_bind_int64(pStmt, 2,
  114168. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  114169. );
  114170. }
  114171. }else{
  114172. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  114173. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  114174. if( rc==SQLITE_OK ){
  114175. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  114176. }
  114177. }
  114178. *ppStmt = pStmt;
  114179. return rc;
  114180. }
  114181. /*
  114182. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  114183. ** if successful, or an SQLite error code otherwise.
  114184. **
  114185. ** This function also serves to allocate the PendingList structure itself.
  114186. ** For example, to create a new PendingList structure containing two
  114187. ** varints:
  114188. **
  114189. ** PendingList *p = 0;
  114190. ** fts3PendingListAppendVarint(&p, 1);
  114191. ** fts3PendingListAppendVarint(&p, 2);
  114192. */
  114193. static int fts3PendingListAppendVarint(
  114194. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  114195. sqlite3_int64 i /* Value to append to data */
  114196. ){
  114197. PendingList *p = *pp;
  114198. /* Allocate or grow the PendingList as required. */
  114199. if( !p ){
  114200. p = sqlite3_malloc(sizeof(*p) + 100);
  114201. if( !p ){
  114202. return SQLITE_NOMEM;
  114203. }
  114204. p->nSpace = 100;
  114205. p->aData = (char *)&p[1];
  114206. p->nData = 0;
  114207. }
  114208. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  114209. int nNew = p->nSpace * 2;
  114210. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  114211. if( !p ){
  114212. sqlite3_free(*pp);
  114213. *pp = 0;
  114214. return SQLITE_NOMEM;
  114215. }
  114216. p->nSpace = nNew;
  114217. p->aData = (char *)&p[1];
  114218. }
  114219. /* Append the new serialized varint to the end of the list. */
  114220. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  114221. p->aData[p->nData] = '\0';
  114222. *pp = p;
  114223. return SQLITE_OK;
  114224. }
  114225. /*
  114226. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  114227. ** is returned if the structure is sqlite3_realloced as part of adding
  114228. ** the entry. Otherwise, zero.
  114229. **
  114230. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  114231. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  114232. ** it is set to SQLITE_OK.
  114233. */
  114234. static int fts3PendingListAppend(
  114235. PendingList **pp, /* IN/OUT: PendingList structure */
  114236. sqlite3_int64 iDocid, /* Docid for entry to add */
  114237. sqlite3_int64 iCol, /* Column for entry to add */
  114238. sqlite3_int64 iPos, /* Position of term for entry to add */
  114239. int *pRc /* OUT: Return code */
  114240. ){
  114241. PendingList *p = *pp;
  114242. int rc = SQLITE_OK;
  114243. assert( !p || p->iLastDocid<=iDocid );
  114244. if( !p || p->iLastDocid!=iDocid ){
  114245. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  114246. if( p ){
  114247. assert( p->nData<p->nSpace );
  114248. assert( p->aData[p->nData]==0 );
  114249. p->nData++;
  114250. }
  114251. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  114252. goto pendinglistappend_out;
  114253. }
  114254. p->iLastCol = -1;
  114255. p->iLastPos = 0;
  114256. p->iLastDocid = iDocid;
  114257. }
  114258. if( iCol>0 && p->iLastCol!=iCol ){
  114259. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  114260. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  114261. ){
  114262. goto pendinglistappend_out;
  114263. }
  114264. p->iLastCol = iCol;
  114265. p->iLastPos = 0;
  114266. }
  114267. if( iCol>=0 ){
  114268. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  114269. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  114270. if( rc==SQLITE_OK ){
  114271. p->iLastPos = iPos;
  114272. }
  114273. }
  114274. pendinglistappend_out:
  114275. *pRc = rc;
  114276. if( p!=*pp ){
  114277. *pp = p;
  114278. return 1;
  114279. }
  114280. return 0;
  114281. }
  114282. /*
  114283. ** Free a PendingList object allocated by fts3PendingListAppend().
  114284. */
  114285. static void fts3PendingListDelete(PendingList *pList){
  114286. sqlite3_free(pList);
  114287. }
  114288. /*
  114289. ** Add an entry to one of the pending-terms hash tables.
  114290. */
  114291. static int fts3PendingTermsAddOne(
  114292. Fts3Table *p,
  114293. int iCol,
  114294. int iPos,
  114295. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  114296. const char *zToken,
  114297. int nToken
  114298. ){
  114299. PendingList *pList;
  114300. int rc = SQLITE_OK;
  114301. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  114302. if( pList ){
  114303. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  114304. }
  114305. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  114306. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  114307. /* Malloc failed while inserting the new entry. This can only
  114308. ** happen if there was no previous entry for this token.
  114309. */
  114310. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  114311. sqlite3_free(pList);
  114312. rc = SQLITE_NOMEM;
  114313. }
  114314. }
  114315. if( rc==SQLITE_OK ){
  114316. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  114317. }
  114318. return rc;
  114319. }
  114320. /*
  114321. ** Tokenize the nul-terminated string zText and add all tokens to the
  114322. ** pending-terms hash-table. The docid used is that currently stored in
  114323. ** p->iPrevDocid, and the column is specified by argument iCol.
  114324. **
  114325. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  114326. */
  114327. static int fts3PendingTermsAdd(
  114328. Fts3Table *p, /* Table into which text will be inserted */
  114329. int iLangid, /* Language id to use */
  114330. const char *zText, /* Text of document to be inserted */
  114331. int iCol, /* Column into which text is being inserted */
  114332. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  114333. ){
  114334. int rc;
  114335. int iStart = 0;
  114336. int iEnd = 0;
  114337. int iPos = 0;
  114338. int nWord = 0;
  114339. char const *zToken;
  114340. int nToken = 0;
  114341. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  114342. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  114343. sqlite3_tokenizer_cursor *pCsr;
  114344. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  114345. const char**,int*,int*,int*,int*);
  114346. assert( pTokenizer && pModule );
  114347. /* If the user has inserted a NULL value, this function may be called with
  114348. ** zText==0. In this case, add zero token entries to the hash table and
  114349. ** return early. */
  114350. if( zText==0 ){
  114351. *pnWord = 0;
  114352. return SQLITE_OK;
  114353. }
  114354. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  114355. if( rc!=SQLITE_OK ){
  114356. return rc;
  114357. }
  114358. xNext = pModule->xNext;
  114359. while( SQLITE_OK==rc
  114360. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  114361. ){
  114362. int i;
  114363. if( iPos>=nWord ) nWord = iPos+1;
  114364. /* Positions cannot be negative; we use -1 as a terminator internally.
  114365. ** Tokens must have a non-zero length.
  114366. */
  114367. if( iPos<0 || !zToken || nToken<=0 ){
  114368. rc = SQLITE_ERROR;
  114369. break;
  114370. }
  114371. /* Add the term to the terms index */
  114372. rc = fts3PendingTermsAddOne(
  114373. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  114374. );
  114375. /* Add the term to each of the prefix indexes that it is not too
  114376. ** short for. */
  114377. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  114378. struct Fts3Index *pIndex = &p->aIndex[i];
  114379. if( nToken<pIndex->nPrefix ) continue;
  114380. rc = fts3PendingTermsAddOne(
  114381. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  114382. );
  114383. }
  114384. }
  114385. pModule->xClose(pCsr);
  114386. *pnWord += nWord;
  114387. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  114388. }
  114389. /*
  114390. ** Calling this function indicates that subsequent calls to
  114391. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  114392. ** contents of the document with docid iDocid.
  114393. */
  114394. static int fts3PendingTermsDocid(
  114395. Fts3Table *p, /* Full-text table handle */
  114396. int iLangid, /* Language id of row being written */
  114397. sqlite_int64 iDocid /* Docid of row being written */
  114398. ){
  114399. assert( iLangid>=0 );
  114400. /* TODO(shess) Explore whether partially flushing the buffer on
  114401. ** forced-flush would provide better performance. I suspect that if
  114402. ** we ordered the doclists by size and flushed the largest until the
  114403. ** buffer was half empty, that would let the less frequent terms
  114404. ** generate longer doclists.
  114405. */
  114406. if( iDocid<=p->iPrevDocid
  114407. || p->iPrevLangid!=iLangid
  114408. || p->nPendingData>p->nMaxPendingData
  114409. ){
  114410. int rc = sqlite3Fts3PendingTermsFlush(p);
  114411. if( rc!=SQLITE_OK ) return rc;
  114412. }
  114413. p->iPrevDocid = iDocid;
  114414. p->iPrevLangid = iLangid;
  114415. return SQLITE_OK;
  114416. }
  114417. /*
  114418. ** Discard the contents of the pending-terms hash tables.
  114419. */
  114420. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  114421. int i;
  114422. for(i=0; i<p->nIndex; i++){
  114423. Fts3HashElem *pElem;
  114424. Fts3Hash *pHash = &p->aIndex[i].hPending;
  114425. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  114426. PendingList *pList = (PendingList *)fts3HashData(pElem);
  114427. fts3PendingListDelete(pList);
  114428. }
  114429. fts3HashClear(pHash);
  114430. }
  114431. p->nPendingData = 0;
  114432. }
  114433. /*
  114434. ** This function is called by the xUpdate() method as part of an INSERT
  114435. ** operation. It adds entries for each term in the new record to the
  114436. ** pendingTerms hash table.
  114437. **
  114438. ** Argument apVal is the same as the similarly named argument passed to
  114439. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  114440. */
  114441. static int fts3InsertTerms(
  114442. Fts3Table *p,
  114443. int iLangid,
  114444. sqlite3_value **apVal,
  114445. u32 *aSz
  114446. ){
  114447. int i; /* Iterator variable */
  114448. for(i=2; i<p->nColumn+2; i++){
  114449. int iCol = i-2;
  114450. if( p->abNotindexed[iCol]==0 ){
  114451. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  114452. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  114453. if( rc!=SQLITE_OK ){
  114454. return rc;
  114455. }
  114456. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  114457. }
  114458. }
  114459. return SQLITE_OK;
  114460. }
  114461. /*
  114462. ** This function is called by the xUpdate() method for an INSERT operation.
  114463. ** The apVal parameter is passed a copy of the apVal argument passed by
  114464. ** SQLite to the xUpdate() method. i.e:
  114465. **
  114466. ** apVal[0] Not used for INSERT.
  114467. ** apVal[1] rowid
  114468. ** apVal[2] Left-most user-defined column
  114469. ** ...
  114470. ** apVal[p->nColumn+1] Right-most user-defined column
  114471. ** apVal[p->nColumn+2] Hidden column with same name as table
  114472. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  114473. ** apVal[p->nColumn+4] Hidden languageid column
  114474. */
  114475. static int fts3InsertData(
  114476. Fts3Table *p, /* Full-text table */
  114477. sqlite3_value **apVal, /* Array of values to insert */
  114478. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  114479. ){
  114480. int rc; /* Return code */
  114481. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  114482. if( p->zContentTbl ){
  114483. sqlite3_value *pRowid = apVal[p->nColumn+3];
  114484. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  114485. pRowid = apVal[1];
  114486. }
  114487. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  114488. return SQLITE_CONSTRAINT;
  114489. }
  114490. *piDocid = sqlite3_value_int64(pRowid);
  114491. return SQLITE_OK;
  114492. }
  114493. /* Locate the statement handle used to insert data into the %_content
  114494. ** table. The SQL for this statement is:
  114495. **
  114496. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  114497. **
  114498. ** The statement features N '?' variables, where N is the number of user
  114499. ** defined columns in the FTS3 table, plus one for the docid field.
  114500. */
  114501. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  114502. if( rc==SQLITE_OK && p->zLanguageid ){
  114503. rc = sqlite3_bind_int(
  114504. pContentInsert, p->nColumn+2,
  114505. sqlite3_value_int(apVal[p->nColumn+4])
  114506. );
  114507. }
  114508. if( rc!=SQLITE_OK ) return rc;
  114509. /* There is a quirk here. The users INSERT statement may have specified
  114510. ** a value for the "rowid" field, for the "docid" field, or for both.
  114511. ** Which is a problem, since "rowid" and "docid" are aliases for the
  114512. ** same value. For example:
  114513. **
  114514. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  114515. **
  114516. ** In FTS3, this is an error. It is an error to specify non-NULL values
  114517. ** for both docid and some other rowid alias.
  114518. */
  114519. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  114520. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  114521. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  114522. ){
  114523. /* A rowid/docid conflict. */
  114524. return SQLITE_ERROR;
  114525. }
  114526. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  114527. if( rc!=SQLITE_OK ) return rc;
  114528. }
  114529. /* Execute the statement to insert the record. Set *piDocid to the
  114530. ** new docid value.
  114531. */
  114532. sqlite3_step(pContentInsert);
  114533. rc = sqlite3_reset(pContentInsert);
  114534. *piDocid = sqlite3_last_insert_rowid(p->db);
  114535. return rc;
  114536. }
  114537. /*
  114538. ** Remove all data from the FTS3 table. Clear the hash table containing
  114539. ** pending terms.
  114540. */
  114541. static int fts3DeleteAll(Fts3Table *p, int bContent){
  114542. int rc = SQLITE_OK; /* Return code */
  114543. /* Discard the contents of the pending-terms hash table. */
  114544. sqlite3Fts3PendingTermsClear(p);
  114545. /* Delete everything from the shadow tables. Except, leave %_content as
  114546. ** is if bContent is false. */
  114547. assert( p->zContentTbl==0 || bContent==0 );
  114548. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  114549. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  114550. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  114551. if( p->bHasDocsize ){
  114552. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  114553. }
  114554. if( p->bHasStat ){
  114555. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  114556. }
  114557. return rc;
  114558. }
  114559. /*
  114560. **
  114561. */
  114562. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  114563. int iLangid = 0;
  114564. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  114565. return iLangid;
  114566. }
  114567. /*
  114568. ** The first element in the apVal[] array is assumed to contain the docid
  114569. ** (an integer) of a row about to be deleted. Remove all terms from the
  114570. ** full-text index.
  114571. */
  114572. static void fts3DeleteTerms(
  114573. int *pRC, /* Result code */
  114574. Fts3Table *p, /* The FTS table to delete from */
  114575. sqlite3_value *pRowid, /* The docid to be deleted */
  114576. u32 *aSz, /* Sizes of deleted document written here */
  114577. int *pbFound /* OUT: Set to true if row really does exist */
  114578. ){
  114579. int rc;
  114580. sqlite3_stmt *pSelect;
  114581. assert( *pbFound==0 );
  114582. if( *pRC ) return;
  114583. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  114584. if( rc==SQLITE_OK ){
  114585. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  114586. int i;
  114587. int iLangid = langidFromSelect(p, pSelect);
  114588. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  114589. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  114590. int iCol = i-1;
  114591. if( p->abNotindexed[iCol]==0 ){
  114592. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  114593. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  114594. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  114595. }
  114596. }
  114597. if( rc!=SQLITE_OK ){
  114598. sqlite3_reset(pSelect);
  114599. *pRC = rc;
  114600. return;
  114601. }
  114602. *pbFound = 1;
  114603. }
  114604. rc = sqlite3_reset(pSelect);
  114605. }else{
  114606. sqlite3_reset(pSelect);
  114607. }
  114608. *pRC = rc;
  114609. }
  114610. /*
  114611. ** Forward declaration to account for the circular dependency between
  114612. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  114613. */
  114614. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  114615. /*
  114616. ** This function allocates a new level iLevel index in the segdir table.
  114617. ** Usually, indexes are allocated within a level sequentially starting
  114618. ** with 0, so the allocated index is one greater than the value returned
  114619. ** by:
  114620. **
  114621. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  114622. **
  114623. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  114624. ** level, they are merged into a single level (iLevel+1) segment and the
  114625. ** allocated index is 0.
  114626. **
  114627. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  114628. ** returned. Otherwise, an SQLite error code is returned.
  114629. */
  114630. static int fts3AllocateSegdirIdx(
  114631. Fts3Table *p,
  114632. int iLangid, /* Language id */
  114633. int iIndex, /* Index for p->aIndex */
  114634. int iLevel,
  114635. int *piIdx
  114636. ){
  114637. int rc; /* Return Code */
  114638. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  114639. int iNext = 0; /* Result of query pNextIdx */
  114640. assert( iLangid>=0 );
  114641. assert( p->nIndex>=1 );
  114642. /* Set variable iNext to the next available segdir index at level iLevel. */
  114643. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  114644. if( rc==SQLITE_OK ){
  114645. sqlite3_bind_int64(
  114646. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  114647. );
  114648. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  114649. iNext = sqlite3_column_int(pNextIdx, 0);
  114650. }
  114651. rc = sqlite3_reset(pNextIdx);
  114652. }
  114653. if( rc==SQLITE_OK ){
  114654. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  114655. ** full, merge all segments in level iLevel into a single iLevel+1
  114656. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  114657. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  114658. */
  114659. if( iNext>=FTS3_MERGE_COUNT ){
  114660. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  114661. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  114662. *piIdx = 0;
  114663. }else{
  114664. *piIdx = iNext;
  114665. }
  114666. }
  114667. return rc;
  114668. }
  114669. /*
  114670. ** The %_segments table is declared as follows:
  114671. **
  114672. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  114673. **
  114674. ** This function reads data from a single row of the %_segments table. The
  114675. ** specific row is identified by the iBlockid parameter. If paBlob is not
  114676. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  114677. ** with the contents of the blob stored in the "block" column of the
  114678. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  114679. ** to the size of the blob in bytes before returning.
  114680. **
  114681. ** If an error occurs, or the table does not contain the specified row,
  114682. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  114683. ** paBlob is non-NULL, then it is the responsibility of the caller to
  114684. ** eventually free the returned buffer.
  114685. **
  114686. ** This function may leave an open sqlite3_blob* handle in the
  114687. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  114688. ** to this function. The handle may be closed by calling the
  114689. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  114690. ** performance improvement, but the blob handle should always be closed
  114691. ** before control is returned to the user (to prevent a lock being held
  114692. ** on the database file for longer than necessary). Thus, any virtual table
  114693. ** method (xFilter etc.) that may directly or indirectly call this function
  114694. ** must call sqlite3Fts3SegmentsClose() before returning.
  114695. */
  114696. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  114697. Fts3Table *p, /* FTS3 table handle */
  114698. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  114699. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  114700. int *pnBlob, /* OUT: Size of blob data */
  114701. int *pnLoad /* OUT: Bytes actually loaded */
  114702. ){
  114703. int rc; /* Return code */
  114704. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  114705. assert( pnBlob );
  114706. if( p->pSegments ){
  114707. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  114708. }else{
  114709. if( 0==p->zSegmentsTbl ){
  114710. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  114711. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  114712. }
  114713. rc = sqlite3_blob_open(
  114714. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  114715. );
  114716. }
  114717. if( rc==SQLITE_OK ){
  114718. int nByte = sqlite3_blob_bytes(p->pSegments);
  114719. *pnBlob = nByte;
  114720. if( paBlob ){
  114721. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  114722. if( !aByte ){
  114723. rc = SQLITE_NOMEM;
  114724. }else{
  114725. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  114726. nByte = FTS3_NODE_CHUNKSIZE;
  114727. *pnLoad = nByte;
  114728. }
  114729. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  114730. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  114731. if( rc!=SQLITE_OK ){
  114732. sqlite3_free(aByte);
  114733. aByte = 0;
  114734. }
  114735. }
  114736. *paBlob = aByte;
  114737. }
  114738. }
  114739. return rc;
  114740. }
  114741. /*
  114742. ** Close the blob handle at p->pSegments, if it is open. See comments above
  114743. ** the sqlite3Fts3ReadBlock() function for details.
  114744. */
  114745. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  114746. sqlite3_blob_close(p->pSegments);
  114747. p->pSegments = 0;
  114748. }
  114749. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  114750. int nRead; /* Number of bytes to read */
  114751. int rc; /* Return code */
  114752. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  114753. rc = sqlite3_blob_read(
  114754. pReader->pBlob,
  114755. &pReader->aNode[pReader->nPopulate],
  114756. nRead,
  114757. pReader->nPopulate
  114758. );
  114759. if( rc==SQLITE_OK ){
  114760. pReader->nPopulate += nRead;
  114761. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  114762. if( pReader->nPopulate==pReader->nNode ){
  114763. sqlite3_blob_close(pReader->pBlob);
  114764. pReader->pBlob = 0;
  114765. pReader->nPopulate = 0;
  114766. }
  114767. }
  114768. return rc;
  114769. }
  114770. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  114771. int rc = SQLITE_OK;
  114772. assert( !pReader->pBlob
  114773. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  114774. );
  114775. while( pReader->pBlob && rc==SQLITE_OK
  114776. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  114777. ){
  114778. rc = fts3SegReaderIncrRead(pReader);
  114779. }
  114780. return rc;
  114781. }
  114782. /*
  114783. ** Set an Fts3SegReader cursor to point at EOF.
  114784. */
  114785. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  114786. if( !fts3SegReaderIsRootOnly(pSeg) ){
  114787. sqlite3_free(pSeg->aNode);
  114788. sqlite3_blob_close(pSeg->pBlob);
  114789. pSeg->pBlob = 0;
  114790. }
  114791. pSeg->aNode = 0;
  114792. }
  114793. /*
  114794. ** Move the iterator passed as the first argument to the next term in the
  114795. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  114796. ** SQLITE_DONE. Otherwise, an SQLite error code.
  114797. */
  114798. static int fts3SegReaderNext(
  114799. Fts3Table *p,
  114800. Fts3SegReader *pReader,
  114801. int bIncr
  114802. ){
  114803. int rc; /* Return code of various sub-routines */
  114804. char *pNext; /* Cursor variable */
  114805. int nPrefix; /* Number of bytes in term prefix */
  114806. int nSuffix; /* Number of bytes in term suffix */
  114807. if( !pReader->aDoclist ){
  114808. pNext = pReader->aNode;
  114809. }else{
  114810. pNext = &pReader->aDoclist[pReader->nDoclist];
  114811. }
  114812. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  114813. if( fts3SegReaderIsPending(pReader) ){
  114814. Fts3HashElem *pElem = *(pReader->ppNextElem);
  114815. if( pElem==0 ){
  114816. pReader->aNode = 0;
  114817. }else{
  114818. PendingList *pList = (PendingList *)fts3HashData(pElem);
  114819. pReader->zTerm = (char *)fts3HashKey(pElem);
  114820. pReader->nTerm = fts3HashKeysize(pElem);
  114821. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  114822. pReader->aNode = pReader->aDoclist = pList->aData;
  114823. pReader->ppNextElem++;
  114824. assert( pReader->aNode );
  114825. }
  114826. return SQLITE_OK;
  114827. }
  114828. fts3SegReaderSetEof(pReader);
  114829. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  114830. ** blocks have already been traversed. */
  114831. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  114832. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  114833. return SQLITE_OK;
  114834. }
  114835. rc = sqlite3Fts3ReadBlock(
  114836. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  114837. (bIncr ? &pReader->nPopulate : 0)
  114838. );
  114839. if( rc!=SQLITE_OK ) return rc;
  114840. assert( pReader->pBlob==0 );
  114841. if( bIncr && pReader->nPopulate<pReader->nNode ){
  114842. pReader->pBlob = p->pSegments;
  114843. p->pSegments = 0;
  114844. }
  114845. pNext = pReader->aNode;
  114846. }
  114847. assert( !fts3SegReaderIsPending(pReader) );
  114848. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  114849. if( rc!=SQLITE_OK ) return rc;
  114850. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  114851. ** safe (no risk of overread) even if the node data is corrupted. */
  114852. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  114853. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  114854. if( nPrefix<0 || nSuffix<=0
  114855. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  114856. ){
  114857. return FTS_CORRUPT_VTAB;
  114858. }
  114859. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  114860. int nNew = (nPrefix+nSuffix)*2;
  114861. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  114862. if( !zNew ){
  114863. return SQLITE_NOMEM;
  114864. }
  114865. pReader->zTerm = zNew;
  114866. pReader->nTermAlloc = nNew;
  114867. }
  114868. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  114869. if( rc!=SQLITE_OK ) return rc;
  114870. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  114871. pReader->nTerm = nPrefix+nSuffix;
  114872. pNext += nSuffix;
  114873. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  114874. pReader->aDoclist = pNext;
  114875. pReader->pOffsetList = 0;
  114876. /* Check that the doclist does not appear to extend past the end of the
  114877. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  114878. ** of these statements is untrue, then the data structure is corrupt.
  114879. */
  114880. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  114881. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  114882. ){
  114883. return FTS_CORRUPT_VTAB;
  114884. }
  114885. return SQLITE_OK;
  114886. }
  114887. /*
  114888. ** Set the SegReader to point to the first docid in the doclist associated
  114889. ** with the current term.
  114890. */
  114891. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  114892. int rc = SQLITE_OK;
  114893. assert( pReader->aDoclist );
  114894. assert( !pReader->pOffsetList );
  114895. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  114896. u8 bEof = 0;
  114897. pReader->iDocid = 0;
  114898. pReader->nOffsetList = 0;
  114899. sqlite3Fts3DoclistPrev(0,
  114900. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  114901. &pReader->iDocid, &pReader->nOffsetList, &bEof
  114902. );
  114903. }else{
  114904. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  114905. if( rc==SQLITE_OK ){
  114906. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  114907. pReader->pOffsetList = &pReader->aDoclist[n];
  114908. }
  114909. }
  114910. return rc;
  114911. }
  114912. /*
  114913. ** Advance the SegReader to point to the next docid in the doclist
  114914. ** associated with the current term.
  114915. **
  114916. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  114917. ** *ppOffsetList is set to point to the first column-offset list
  114918. ** in the doclist entry (i.e. immediately past the docid varint).
  114919. ** *pnOffsetList is set to the length of the set of column-offset
  114920. ** lists, not including the nul-terminator byte. For example:
  114921. */
  114922. static int fts3SegReaderNextDocid(
  114923. Fts3Table *pTab,
  114924. Fts3SegReader *pReader, /* Reader to advance to next docid */
  114925. char **ppOffsetList, /* OUT: Pointer to current position-list */
  114926. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  114927. ){
  114928. int rc = SQLITE_OK;
  114929. char *p = pReader->pOffsetList;
  114930. char c = 0;
  114931. assert( p );
  114932. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  114933. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  114934. ** Pending-terms doclists are always built up in ascending order, so
  114935. ** we have to iterate through them backwards here. */
  114936. u8 bEof = 0;
  114937. if( ppOffsetList ){
  114938. *ppOffsetList = pReader->pOffsetList;
  114939. *pnOffsetList = pReader->nOffsetList - 1;
  114940. }
  114941. sqlite3Fts3DoclistPrev(0,
  114942. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  114943. &pReader->nOffsetList, &bEof
  114944. );
  114945. if( bEof ){
  114946. pReader->pOffsetList = 0;
  114947. }else{
  114948. pReader->pOffsetList = p;
  114949. }
  114950. }else{
  114951. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  114952. /* Pointer p currently points at the first byte of an offset list. The
  114953. ** following block advances it to point one byte past the end of
  114954. ** the same offset list. */
  114955. while( 1 ){
  114956. /* The following line of code (and the "p++" below the while() loop) is
  114957. ** normally all that is required to move pointer p to the desired
  114958. ** position. The exception is if this node is being loaded from disk
  114959. ** incrementally and pointer "p" now points to the first byte past
  114960. ** the populated part of pReader->aNode[].
  114961. */
  114962. while( *p | c ) c = *p++ & 0x80;
  114963. assert( *p==0 );
  114964. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  114965. rc = fts3SegReaderIncrRead(pReader);
  114966. if( rc!=SQLITE_OK ) return rc;
  114967. }
  114968. p++;
  114969. /* If required, populate the output variables with a pointer to and the
  114970. ** size of the previous offset-list.
  114971. */
  114972. if( ppOffsetList ){
  114973. *ppOffsetList = pReader->pOffsetList;
  114974. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  114975. }
  114976. /* List may have been edited in place by fts3EvalNearTrim() */
  114977. while( p<pEnd && *p==0 ) p++;
  114978. /* If there are no more entries in the doclist, set pOffsetList to
  114979. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  114980. ** Fts3SegReader.pOffsetList to point to the next offset list before
  114981. ** returning.
  114982. */
  114983. if( p>=pEnd ){
  114984. pReader->pOffsetList = 0;
  114985. }else{
  114986. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  114987. if( rc==SQLITE_OK ){
  114988. sqlite3_int64 iDelta;
  114989. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  114990. if( pTab->bDescIdx ){
  114991. pReader->iDocid -= iDelta;
  114992. }else{
  114993. pReader->iDocid += iDelta;
  114994. }
  114995. }
  114996. }
  114997. }
  114998. return SQLITE_OK;
  114999. }
  115000. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  115001. Fts3Cursor *pCsr,
  115002. Fts3MultiSegReader *pMsr,
  115003. int *pnOvfl
  115004. ){
  115005. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  115006. int nOvfl = 0;
  115007. int ii;
  115008. int rc = SQLITE_OK;
  115009. int pgsz = p->nPgsz;
  115010. assert( p->bFts4 );
  115011. assert( pgsz>0 );
  115012. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  115013. Fts3SegReader *pReader = pMsr->apSegment[ii];
  115014. if( !fts3SegReaderIsPending(pReader)
  115015. && !fts3SegReaderIsRootOnly(pReader)
  115016. ){
  115017. sqlite3_int64 jj;
  115018. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  115019. int nBlob;
  115020. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  115021. if( rc!=SQLITE_OK ) break;
  115022. if( (nBlob+35)>pgsz ){
  115023. nOvfl += (nBlob + 34)/pgsz;
  115024. }
  115025. }
  115026. }
  115027. }
  115028. *pnOvfl = nOvfl;
  115029. return rc;
  115030. }
  115031. /*
  115032. ** Free all allocations associated with the iterator passed as the
  115033. ** second argument.
  115034. */
  115035. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  115036. if( pReader && !fts3SegReaderIsPending(pReader) ){
  115037. sqlite3_free(pReader->zTerm);
  115038. if( !fts3SegReaderIsRootOnly(pReader) ){
  115039. sqlite3_free(pReader->aNode);
  115040. sqlite3_blob_close(pReader->pBlob);
  115041. }
  115042. }
  115043. sqlite3_free(pReader);
  115044. }
  115045. /*
  115046. ** Allocate a new SegReader object.
  115047. */
  115048. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  115049. int iAge, /* Segment "age". */
  115050. int bLookup, /* True for a lookup only */
  115051. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  115052. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  115053. sqlite3_int64 iEndBlock, /* Final block of segment */
  115054. const char *zRoot, /* Buffer containing root node */
  115055. int nRoot, /* Size of buffer containing root node */
  115056. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  115057. ){
  115058. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  115059. int nExtra = 0; /* Bytes to allocate segment root node */
  115060. assert( iStartLeaf<=iEndLeaf );
  115061. if( iStartLeaf==0 ){
  115062. nExtra = nRoot + FTS3_NODE_PADDING;
  115063. }
  115064. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  115065. if( !pReader ){
  115066. return SQLITE_NOMEM;
  115067. }
  115068. memset(pReader, 0, sizeof(Fts3SegReader));
  115069. pReader->iIdx = iAge;
  115070. pReader->bLookup = bLookup!=0;
  115071. pReader->iStartBlock = iStartLeaf;
  115072. pReader->iLeafEndBlock = iEndLeaf;
  115073. pReader->iEndBlock = iEndBlock;
  115074. if( nExtra ){
  115075. /* The entire segment is stored in the root node. */
  115076. pReader->aNode = (char *)&pReader[1];
  115077. pReader->rootOnly = 1;
  115078. pReader->nNode = nRoot;
  115079. memcpy(pReader->aNode, zRoot, nRoot);
  115080. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  115081. }else{
  115082. pReader->iCurrentBlock = iStartLeaf-1;
  115083. }
  115084. *ppReader = pReader;
  115085. return SQLITE_OK;
  115086. }
  115087. /*
  115088. ** This is a comparison function used as a qsort() callback when sorting
  115089. ** an array of pending terms by term. This occurs as part of flushing
  115090. ** the contents of the pending-terms hash table to the database.
  115091. */
  115092. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  115093. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  115094. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  115095. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  115096. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  115097. int n = (n1<n2 ? n1 : n2);
  115098. int c = memcmp(z1, z2, n);
  115099. if( c==0 ){
  115100. c = n1 - n2;
  115101. }
  115102. return c;
  115103. }
  115104. /*
  115105. ** This function is used to allocate an Fts3SegReader that iterates through
  115106. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  115107. **
  115108. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  115109. ** through each term in the pending-terms table. Or, if isPrefixIter is
  115110. ** non-zero, it iterates through each term and its prefixes. For example, if
  115111. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  115112. ** "firebird", then the iterator visits the following 'terms' (in the order
  115113. ** shown):
  115114. **
  115115. ** f fi fir fire fireb firebi firebir firebird
  115116. ** m my mys mysq mysql
  115117. ** s sq sql sqli sqlit sqlite
  115118. **
  115119. ** Whereas if isPrefixIter is zero, the terms visited are:
  115120. **
  115121. ** firebird mysql sqlite
  115122. */
  115123. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  115124. Fts3Table *p, /* Virtual table handle */
  115125. int iIndex, /* Index for p->aIndex */
  115126. const char *zTerm, /* Term to search for */
  115127. int nTerm, /* Size of buffer zTerm */
  115128. int bPrefix, /* True for a prefix iterator */
  115129. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  115130. ){
  115131. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  115132. Fts3HashElem *pE; /* Iterator variable */
  115133. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  115134. int nElem = 0; /* Size of array at aElem */
  115135. int rc = SQLITE_OK; /* Return Code */
  115136. Fts3Hash *pHash;
  115137. pHash = &p->aIndex[iIndex].hPending;
  115138. if( bPrefix ){
  115139. int nAlloc = 0; /* Size of allocated array at aElem */
  115140. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  115141. char *zKey = (char *)fts3HashKey(pE);
  115142. int nKey = fts3HashKeysize(pE);
  115143. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  115144. if( nElem==nAlloc ){
  115145. Fts3HashElem **aElem2;
  115146. nAlloc += 16;
  115147. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  115148. aElem, nAlloc*sizeof(Fts3HashElem *)
  115149. );
  115150. if( !aElem2 ){
  115151. rc = SQLITE_NOMEM;
  115152. nElem = 0;
  115153. break;
  115154. }
  115155. aElem = aElem2;
  115156. }
  115157. aElem[nElem++] = pE;
  115158. }
  115159. }
  115160. /* If more than one term matches the prefix, sort the Fts3HashElem
  115161. ** objects in term order using qsort(). This uses the same comparison
  115162. ** callback as is used when flushing terms to disk.
  115163. */
  115164. if( nElem>1 ){
  115165. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  115166. }
  115167. }else{
  115168. /* The query is a simple term lookup that matches at most one term in
  115169. ** the index. All that is required is a straight hash-lookup.
  115170. **
  115171. ** Because the stack address of pE may be accessed via the aElem pointer
  115172. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  115173. ** within this entire function, not just this "else{...}" block.
  115174. */
  115175. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  115176. if( pE ){
  115177. aElem = &pE;
  115178. nElem = 1;
  115179. }
  115180. }
  115181. if( nElem>0 ){
  115182. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  115183. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  115184. if( !pReader ){
  115185. rc = SQLITE_NOMEM;
  115186. }else{
  115187. memset(pReader, 0, nByte);
  115188. pReader->iIdx = 0x7FFFFFFF;
  115189. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  115190. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  115191. }
  115192. }
  115193. if( bPrefix ){
  115194. sqlite3_free(aElem);
  115195. }
  115196. *ppReader = pReader;
  115197. return rc;
  115198. }
  115199. /*
  115200. ** Compare the entries pointed to by two Fts3SegReader structures.
  115201. ** Comparison is as follows:
  115202. **
  115203. ** 1) EOF is greater than not EOF.
  115204. **
  115205. ** 2) The current terms (if any) are compared using memcmp(). If one
  115206. ** term is a prefix of another, the longer term is considered the
  115207. ** larger.
  115208. **
  115209. ** 3) By segment age. An older segment is considered larger.
  115210. */
  115211. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115212. int rc;
  115213. if( pLhs->aNode && pRhs->aNode ){
  115214. int rc2 = pLhs->nTerm - pRhs->nTerm;
  115215. if( rc2<0 ){
  115216. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  115217. }else{
  115218. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  115219. }
  115220. if( rc==0 ){
  115221. rc = rc2;
  115222. }
  115223. }else{
  115224. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  115225. }
  115226. if( rc==0 ){
  115227. rc = pRhs->iIdx - pLhs->iIdx;
  115228. }
  115229. assert( rc!=0 );
  115230. return rc;
  115231. }
  115232. /*
  115233. ** A different comparison function for SegReader structures. In this
  115234. ** version, it is assumed that each SegReader points to an entry in
  115235. ** a doclist for identical terms. Comparison is made as follows:
  115236. **
  115237. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  115238. **
  115239. ** 2) By current docid.
  115240. **
  115241. ** 3) By segment age. An older segment is considered larger.
  115242. */
  115243. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115244. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  115245. if( rc==0 ){
  115246. if( pLhs->iDocid==pRhs->iDocid ){
  115247. rc = pRhs->iIdx - pLhs->iIdx;
  115248. }else{
  115249. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  115250. }
  115251. }
  115252. assert( pLhs->aNode && pRhs->aNode );
  115253. return rc;
  115254. }
  115255. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  115256. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  115257. if( rc==0 ){
  115258. if( pLhs->iDocid==pRhs->iDocid ){
  115259. rc = pRhs->iIdx - pLhs->iIdx;
  115260. }else{
  115261. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  115262. }
  115263. }
  115264. assert( pLhs->aNode && pRhs->aNode );
  115265. return rc;
  115266. }
  115267. /*
  115268. ** Compare the term that the Fts3SegReader object passed as the first argument
  115269. ** points to with the term specified by arguments zTerm and nTerm.
  115270. **
  115271. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  115272. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  115273. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  115274. */
  115275. static int fts3SegReaderTermCmp(
  115276. Fts3SegReader *pSeg, /* Segment reader object */
  115277. const char *zTerm, /* Term to compare to */
  115278. int nTerm /* Size of term zTerm in bytes */
  115279. ){
  115280. int res = 0;
  115281. if( pSeg->aNode ){
  115282. if( pSeg->nTerm>nTerm ){
  115283. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  115284. }else{
  115285. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  115286. }
  115287. if( res==0 ){
  115288. res = pSeg->nTerm-nTerm;
  115289. }
  115290. }
  115291. return res;
  115292. }
  115293. /*
  115294. ** Argument apSegment is an array of nSegment elements. It is known that
  115295. ** the final (nSegment-nSuspect) members are already in sorted order
  115296. ** (according to the comparison function provided). This function shuffles
  115297. ** the array around until all entries are in sorted order.
  115298. */
  115299. static void fts3SegReaderSort(
  115300. Fts3SegReader **apSegment, /* Array to sort entries of */
  115301. int nSegment, /* Size of apSegment array */
  115302. int nSuspect, /* Unsorted entry count */
  115303. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  115304. ){
  115305. int i; /* Iterator variable */
  115306. assert( nSuspect<=nSegment );
  115307. if( nSuspect==nSegment ) nSuspect--;
  115308. for(i=nSuspect-1; i>=0; i--){
  115309. int j;
  115310. for(j=i; j<(nSegment-1); j++){
  115311. Fts3SegReader *pTmp;
  115312. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  115313. pTmp = apSegment[j+1];
  115314. apSegment[j+1] = apSegment[j];
  115315. apSegment[j] = pTmp;
  115316. }
  115317. }
  115318. #ifndef NDEBUG
  115319. /* Check that the list really is sorted now. */
  115320. for(i=0; i<(nSuspect-1); i++){
  115321. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  115322. }
  115323. #endif
  115324. }
  115325. /*
  115326. ** Insert a record into the %_segments table.
  115327. */
  115328. static int fts3WriteSegment(
  115329. Fts3Table *p, /* Virtual table handle */
  115330. sqlite3_int64 iBlock, /* Block id for new block */
  115331. char *z, /* Pointer to buffer containing block data */
  115332. int n /* Size of buffer z in bytes */
  115333. ){
  115334. sqlite3_stmt *pStmt;
  115335. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  115336. if( rc==SQLITE_OK ){
  115337. sqlite3_bind_int64(pStmt, 1, iBlock);
  115338. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  115339. sqlite3_step(pStmt);
  115340. rc = sqlite3_reset(pStmt);
  115341. }
  115342. return rc;
  115343. }
  115344. /*
  115345. ** Find the largest relative level number in the table. If successful, set
  115346. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  115347. ** set *pnMax to zero and return an SQLite error code.
  115348. */
  115349. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  115350. int rc;
  115351. int mxLevel = 0;
  115352. sqlite3_stmt *pStmt = 0;
  115353. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  115354. if( rc==SQLITE_OK ){
  115355. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115356. mxLevel = sqlite3_column_int(pStmt, 0);
  115357. }
  115358. rc = sqlite3_reset(pStmt);
  115359. }
  115360. *pnMax = mxLevel;
  115361. return rc;
  115362. }
  115363. /*
  115364. ** Insert a record into the %_segdir table.
  115365. */
  115366. static int fts3WriteSegdir(
  115367. Fts3Table *p, /* Virtual table handle */
  115368. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  115369. int iIdx, /* Value for "idx" field */
  115370. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  115371. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  115372. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  115373. char *zRoot, /* Blob value for "root" field */
  115374. int nRoot /* Number of bytes in buffer zRoot */
  115375. ){
  115376. sqlite3_stmt *pStmt;
  115377. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  115378. if( rc==SQLITE_OK ){
  115379. sqlite3_bind_int64(pStmt, 1, iLevel);
  115380. sqlite3_bind_int(pStmt, 2, iIdx);
  115381. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  115382. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  115383. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  115384. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  115385. sqlite3_step(pStmt);
  115386. rc = sqlite3_reset(pStmt);
  115387. }
  115388. return rc;
  115389. }
  115390. /*
  115391. ** Return the size of the common prefix (if any) shared by zPrev and
  115392. ** zNext, in bytes. For example,
  115393. **
  115394. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  115395. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  115396. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  115397. */
  115398. static int fts3PrefixCompress(
  115399. const char *zPrev, /* Buffer containing previous term */
  115400. int nPrev, /* Size of buffer zPrev in bytes */
  115401. const char *zNext, /* Buffer containing next term */
  115402. int nNext /* Size of buffer zNext in bytes */
  115403. ){
  115404. int n;
  115405. UNUSED_PARAMETER(nNext);
  115406. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  115407. return n;
  115408. }
  115409. /*
  115410. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  115411. ** (according to memcmp) than the previous term.
  115412. */
  115413. static int fts3NodeAddTerm(
  115414. Fts3Table *p, /* Virtual table handle */
  115415. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  115416. int isCopyTerm, /* True if zTerm/nTerm is transient */
  115417. const char *zTerm, /* Pointer to buffer containing term */
  115418. int nTerm /* Size of term in bytes */
  115419. ){
  115420. SegmentNode *pTree = *ppTree;
  115421. int rc;
  115422. SegmentNode *pNew;
  115423. /* First try to append the term to the current node. Return early if
  115424. ** this is possible.
  115425. */
  115426. if( pTree ){
  115427. int nData = pTree->nData; /* Current size of node in bytes */
  115428. int nReq = nData; /* Required space after adding zTerm */
  115429. int nPrefix; /* Number of bytes of prefix compression */
  115430. int nSuffix; /* Suffix length */
  115431. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  115432. nSuffix = nTerm-nPrefix;
  115433. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  115434. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  115435. if( nReq>p->nNodeSize ){
  115436. /* An unusual case: this is the first term to be added to the node
  115437. ** and the static node buffer (p->nNodeSize bytes) is not large
  115438. ** enough. Use a separately malloced buffer instead This wastes
  115439. ** p->nNodeSize bytes, but since this scenario only comes about when
  115440. ** the database contain two terms that share a prefix of almost 2KB,
  115441. ** this is not expected to be a serious problem.
  115442. */
  115443. assert( pTree->aData==(char *)&pTree[1] );
  115444. pTree->aData = (char *)sqlite3_malloc(nReq);
  115445. if( !pTree->aData ){
  115446. return SQLITE_NOMEM;
  115447. }
  115448. }
  115449. if( pTree->zTerm ){
  115450. /* There is no prefix-length field for first term in a node */
  115451. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  115452. }
  115453. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  115454. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  115455. pTree->nData = nData + nSuffix;
  115456. pTree->nEntry++;
  115457. if( isCopyTerm ){
  115458. if( pTree->nMalloc<nTerm ){
  115459. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  115460. if( !zNew ){
  115461. return SQLITE_NOMEM;
  115462. }
  115463. pTree->nMalloc = nTerm*2;
  115464. pTree->zMalloc = zNew;
  115465. }
  115466. pTree->zTerm = pTree->zMalloc;
  115467. memcpy(pTree->zTerm, zTerm, nTerm);
  115468. pTree->nTerm = nTerm;
  115469. }else{
  115470. pTree->zTerm = (char *)zTerm;
  115471. pTree->nTerm = nTerm;
  115472. }
  115473. return SQLITE_OK;
  115474. }
  115475. }
  115476. /* If control flows to here, it was not possible to append zTerm to the
  115477. ** current node. Create a new node (a right-sibling of the current node).
  115478. ** If this is the first node in the tree, the term is added to it.
  115479. **
  115480. ** Otherwise, the term is not added to the new node, it is left empty for
  115481. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  115482. ** has no parent, one is created here.
  115483. */
  115484. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  115485. if( !pNew ){
  115486. return SQLITE_NOMEM;
  115487. }
  115488. memset(pNew, 0, sizeof(SegmentNode));
  115489. pNew->nData = 1 + FTS3_VARINT_MAX;
  115490. pNew->aData = (char *)&pNew[1];
  115491. if( pTree ){
  115492. SegmentNode *pParent = pTree->pParent;
  115493. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  115494. if( pTree->pParent==0 ){
  115495. pTree->pParent = pParent;
  115496. }
  115497. pTree->pRight = pNew;
  115498. pNew->pLeftmost = pTree->pLeftmost;
  115499. pNew->pParent = pParent;
  115500. pNew->zMalloc = pTree->zMalloc;
  115501. pNew->nMalloc = pTree->nMalloc;
  115502. pTree->zMalloc = 0;
  115503. }else{
  115504. pNew->pLeftmost = pNew;
  115505. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  115506. }
  115507. *ppTree = pNew;
  115508. return rc;
  115509. }
  115510. /*
  115511. ** Helper function for fts3NodeWrite().
  115512. */
  115513. static int fts3TreeFinishNode(
  115514. SegmentNode *pTree,
  115515. int iHeight,
  115516. sqlite3_int64 iLeftChild
  115517. ){
  115518. int nStart;
  115519. assert( iHeight>=1 && iHeight<128 );
  115520. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  115521. pTree->aData[nStart] = (char)iHeight;
  115522. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  115523. return nStart;
  115524. }
  115525. /*
  115526. ** Write the buffer for the segment node pTree and all of its peers to the
  115527. ** database. Then call this function recursively to write the parent of
  115528. ** pTree and its peers to the database.
  115529. **
  115530. ** Except, if pTree is a root node, do not write it to the database. Instead,
  115531. ** set output variables *paRoot and *pnRoot to contain the root node.
  115532. **
  115533. ** If successful, SQLITE_OK is returned and output variable *piLast is
  115534. ** set to the largest blockid written to the database (or zero if no
  115535. ** blocks were written to the db). Otherwise, an SQLite error code is
  115536. ** returned.
  115537. */
  115538. static int fts3NodeWrite(
  115539. Fts3Table *p, /* Virtual table handle */
  115540. SegmentNode *pTree, /* SegmentNode handle */
  115541. int iHeight, /* Height of this node in tree */
  115542. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  115543. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  115544. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  115545. char **paRoot, /* OUT: Data for root node */
  115546. int *pnRoot /* OUT: Size of root node in bytes */
  115547. ){
  115548. int rc = SQLITE_OK;
  115549. if( !pTree->pParent ){
  115550. /* Root node of the tree. */
  115551. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  115552. *piLast = iFree-1;
  115553. *pnRoot = pTree->nData - nStart;
  115554. *paRoot = &pTree->aData[nStart];
  115555. }else{
  115556. SegmentNode *pIter;
  115557. sqlite3_int64 iNextFree = iFree;
  115558. sqlite3_int64 iNextLeaf = iLeaf;
  115559. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  115560. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  115561. int nWrite = pIter->nData - nStart;
  115562. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  115563. iNextFree++;
  115564. iNextLeaf += (pIter->nEntry+1);
  115565. }
  115566. if( rc==SQLITE_OK ){
  115567. assert( iNextLeaf==iFree );
  115568. rc = fts3NodeWrite(
  115569. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  115570. );
  115571. }
  115572. }
  115573. return rc;
  115574. }
  115575. /*
  115576. ** Free all memory allocations associated with the tree pTree.
  115577. */
  115578. static void fts3NodeFree(SegmentNode *pTree){
  115579. if( pTree ){
  115580. SegmentNode *p = pTree->pLeftmost;
  115581. fts3NodeFree(p->pParent);
  115582. while( p ){
  115583. SegmentNode *pRight = p->pRight;
  115584. if( p->aData!=(char *)&p[1] ){
  115585. sqlite3_free(p->aData);
  115586. }
  115587. assert( pRight==0 || p->zMalloc==0 );
  115588. sqlite3_free(p->zMalloc);
  115589. sqlite3_free(p);
  115590. p = pRight;
  115591. }
  115592. }
  115593. }
  115594. /*
  115595. ** Add a term to the segment being constructed by the SegmentWriter object
  115596. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  115597. ** be passed NULL. This function will allocate a new SegmentWriter object
  115598. ** and return it via the input/output variable *ppWriter in this case.
  115599. **
  115600. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  115601. */
  115602. static int fts3SegWriterAdd(
  115603. Fts3Table *p, /* Virtual table handle */
  115604. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  115605. int isCopyTerm, /* True if buffer zTerm must be copied */
  115606. const char *zTerm, /* Pointer to buffer containing term */
  115607. int nTerm, /* Size of term in bytes */
  115608. const char *aDoclist, /* Pointer to buffer containing doclist */
  115609. int nDoclist /* Size of doclist in bytes */
  115610. ){
  115611. int nPrefix; /* Size of term prefix in bytes */
  115612. int nSuffix; /* Size of term suffix in bytes */
  115613. int nReq; /* Number of bytes required on leaf page */
  115614. int nData;
  115615. SegmentWriter *pWriter = *ppWriter;
  115616. if( !pWriter ){
  115617. int rc;
  115618. sqlite3_stmt *pStmt;
  115619. /* Allocate the SegmentWriter structure */
  115620. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  115621. if( !pWriter ) return SQLITE_NOMEM;
  115622. memset(pWriter, 0, sizeof(SegmentWriter));
  115623. *ppWriter = pWriter;
  115624. /* Allocate a buffer in which to accumulate data */
  115625. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  115626. if( !pWriter->aData ) return SQLITE_NOMEM;
  115627. pWriter->nSize = p->nNodeSize;
  115628. /* Find the next free blockid in the %_segments table */
  115629. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  115630. if( rc!=SQLITE_OK ) return rc;
  115631. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115632. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  115633. pWriter->iFirst = pWriter->iFree;
  115634. }
  115635. rc = sqlite3_reset(pStmt);
  115636. if( rc!=SQLITE_OK ) return rc;
  115637. }
  115638. nData = pWriter->nData;
  115639. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  115640. nSuffix = nTerm-nPrefix;
  115641. /* Figure out how many bytes are required by this new entry */
  115642. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  115643. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  115644. nSuffix + /* Term suffix */
  115645. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  115646. nDoclist; /* Doclist data */
  115647. if( nData>0 && nData+nReq>p->nNodeSize ){
  115648. int rc;
  115649. /* The current leaf node is full. Write it out to the database. */
  115650. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  115651. if( rc!=SQLITE_OK ) return rc;
  115652. p->nLeafAdd++;
  115653. /* Add the current term to the interior node tree. The term added to
  115654. ** the interior tree must:
  115655. **
  115656. ** a) be greater than the largest term on the leaf node just written
  115657. ** to the database (still available in pWriter->zTerm), and
  115658. **
  115659. ** b) be less than or equal to the term about to be added to the new
  115660. ** leaf node (zTerm/nTerm).
  115661. **
  115662. ** In other words, it must be the prefix of zTerm 1 byte longer than
  115663. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  115664. */
  115665. assert( nPrefix<nTerm );
  115666. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  115667. if( rc!=SQLITE_OK ) return rc;
  115668. nData = 0;
  115669. pWriter->nTerm = 0;
  115670. nPrefix = 0;
  115671. nSuffix = nTerm;
  115672. nReq = 1 + /* varint containing prefix size */
  115673. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  115674. nTerm + /* Term suffix */
  115675. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  115676. nDoclist; /* Doclist data */
  115677. }
  115678. /* If the buffer currently allocated is too small for this entry, realloc
  115679. ** the buffer to make it large enough.
  115680. */
  115681. if( nReq>pWriter->nSize ){
  115682. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  115683. if( !aNew ) return SQLITE_NOMEM;
  115684. pWriter->aData = aNew;
  115685. pWriter->nSize = nReq;
  115686. }
  115687. assert( nData+nReq<=pWriter->nSize );
  115688. /* Append the prefix-compressed term and doclist to the buffer. */
  115689. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  115690. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  115691. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  115692. nData += nSuffix;
  115693. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  115694. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  115695. pWriter->nData = nData + nDoclist;
  115696. /* Save the current term so that it can be used to prefix-compress the next.
  115697. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  115698. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  115699. ** store a copy of the pointer.
  115700. */
  115701. if( isCopyTerm ){
  115702. if( nTerm>pWriter->nMalloc ){
  115703. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  115704. if( !zNew ){
  115705. return SQLITE_NOMEM;
  115706. }
  115707. pWriter->nMalloc = nTerm*2;
  115708. pWriter->zMalloc = zNew;
  115709. pWriter->zTerm = zNew;
  115710. }
  115711. assert( pWriter->zTerm==pWriter->zMalloc );
  115712. memcpy(pWriter->zTerm, zTerm, nTerm);
  115713. }else{
  115714. pWriter->zTerm = (char *)zTerm;
  115715. }
  115716. pWriter->nTerm = nTerm;
  115717. return SQLITE_OK;
  115718. }
  115719. /*
  115720. ** Flush all data associated with the SegmentWriter object pWriter to the
  115721. ** database. This function must be called after all terms have been added
  115722. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  115723. ** returned. Otherwise, an SQLite error code.
  115724. */
  115725. static int fts3SegWriterFlush(
  115726. Fts3Table *p, /* Virtual table handle */
  115727. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  115728. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  115729. int iIdx /* Value for 'idx' column of %_segdir */
  115730. ){
  115731. int rc; /* Return code */
  115732. if( pWriter->pTree ){
  115733. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  115734. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  115735. char *zRoot = NULL; /* Pointer to buffer containing root node */
  115736. int nRoot = 0; /* Size of buffer zRoot */
  115737. iLastLeaf = pWriter->iFree;
  115738. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  115739. if( rc==SQLITE_OK ){
  115740. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  115741. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  115742. }
  115743. if( rc==SQLITE_OK ){
  115744. rc = fts3WriteSegdir(
  115745. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  115746. }
  115747. }else{
  115748. /* The entire tree fits on the root node. Write it to the segdir table. */
  115749. rc = fts3WriteSegdir(
  115750. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  115751. }
  115752. p->nLeafAdd++;
  115753. return rc;
  115754. }
  115755. /*
  115756. ** Release all memory held by the SegmentWriter object passed as the
  115757. ** first argument.
  115758. */
  115759. static void fts3SegWriterFree(SegmentWriter *pWriter){
  115760. if( pWriter ){
  115761. sqlite3_free(pWriter->aData);
  115762. sqlite3_free(pWriter->zMalloc);
  115763. fts3NodeFree(pWriter->pTree);
  115764. sqlite3_free(pWriter);
  115765. }
  115766. }
  115767. /*
  115768. ** The first value in the apVal[] array is assumed to contain an integer.
  115769. ** This function tests if there exist any documents with docid values that
  115770. ** are different from that integer. i.e. if deleting the document with docid
  115771. ** pRowid would mean the FTS3 table were empty.
  115772. **
  115773. ** If successful, *pisEmpty is set to true if the table is empty except for
  115774. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  115775. ** error occurs, an SQLite error code is returned.
  115776. */
  115777. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  115778. sqlite3_stmt *pStmt;
  115779. int rc;
  115780. if( p->zContentTbl ){
  115781. /* If using the content=xxx option, assume the table is never empty */
  115782. *pisEmpty = 0;
  115783. rc = SQLITE_OK;
  115784. }else{
  115785. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  115786. if( rc==SQLITE_OK ){
  115787. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115788. *pisEmpty = sqlite3_column_int(pStmt, 0);
  115789. }
  115790. rc = sqlite3_reset(pStmt);
  115791. }
  115792. }
  115793. return rc;
  115794. }
  115795. /*
  115796. ** Set *pnMax to the largest segment level in the database for the index
  115797. ** iIndex.
  115798. **
  115799. ** Segment levels are stored in the 'level' column of the %_segdir table.
  115800. **
  115801. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  115802. */
  115803. static int fts3SegmentMaxLevel(
  115804. Fts3Table *p,
  115805. int iLangid,
  115806. int iIndex,
  115807. sqlite3_int64 *pnMax
  115808. ){
  115809. sqlite3_stmt *pStmt;
  115810. int rc;
  115811. assert( iIndex>=0 && iIndex<p->nIndex );
  115812. /* Set pStmt to the compiled version of:
  115813. **
  115814. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  115815. **
  115816. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  115817. */
  115818. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  115819. if( rc!=SQLITE_OK ) return rc;
  115820. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  115821. sqlite3_bind_int64(pStmt, 2,
  115822. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  115823. );
  115824. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  115825. *pnMax = sqlite3_column_int64(pStmt, 0);
  115826. }
  115827. return sqlite3_reset(pStmt);
  115828. }
  115829. /*
  115830. ** Delete all entries in the %_segments table associated with the segment
  115831. ** opened with seg-reader pSeg. This function does not affect the contents
  115832. ** of the %_segdir table.
  115833. */
  115834. static int fts3DeleteSegment(
  115835. Fts3Table *p, /* FTS table handle */
  115836. Fts3SegReader *pSeg /* Segment to delete */
  115837. ){
  115838. int rc = SQLITE_OK; /* Return code */
  115839. if( pSeg->iStartBlock ){
  115840. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  115841. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  115842. if( rc==SQLITE_OK ){
  115843. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  115844. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  115845. sqlite3_step(pDelete);
  115846. rc = sqlite3_reset(pDelete);
  115847. }
  115848. }
  115849. return rc;
  115850. }
  115851. /*
  115852. ** This function is used after merging multiple segments into a single large
  115853. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  115854. ** it:
  115855. **
  115856. ** 1) Deletes all %_segments entries for the segments associated with
  115857. ** each of the SegReader objects in the array passed as the third
  115858. ** argument, and
  115859. **
  115860. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  115861. ** entries regardless of level if (iLevel<0).
  115862. **
  115863. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  115864. */
  115865. static int fts3DeleteSegdir(
  115866. Fts3Table *p, /* Virtual table handle */
  115867. int iLangid, /* Language id */
  115868. int iIndex, /* Index for p->aIndex */
  115869. int iLevel, /* Level of %_segdir entries to delete */
  115870. Fts3SegReader **apSegment, /* Array of SegReader objects */
  115871. int nReader /* Size of array apSegment */
  115872. ){
  115873. int rc = SQLITE_OK; /* Return Code */
  115874. int i; /* Iterator variable */
  115875. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  115876. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  115877. rc = fts3DeleteSegment(p, apSegment[i]);
  115878. }
  115879. if( rc!=SQLITE_OK ){
  115880. return rc;
  115881. }
  115882. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  115883. if( iLevel==FTS3_SEGCURSOR_ALL ){
  115884. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  115885. if( rc==SQLITE_OK ){
  115886. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  115887. sqlite3_bind_int64(pDelete, 2,
  115888. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  115889. );
  115890. }
  115891. }else{
  115892. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  115893. if( rc==SQLITE_OK ){
  115894. sqlite3_bind_int64(
  115895. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  115896. );
  115897. }
  115898. }
  115899. if( rc==SQLITE_OK ){
  115900. sqlite3_step(pDelete);
  115901. rc = sqlite3_reset(pDelete);
  115902. }
  115903. return rc;
  115904. }
  115905. /*
  115906. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  115907. ** a position list that may (or may not) feature multiple columns. This
  115908. ** function adjusts the pointer *ppList and the length *pnList so that they
  115909. ** identify the subset of the position list that corresponds to column iCol.
  115910. **
  115911. ** If there are no entries in the input position list for column iCol, then
  115912. ** *pnList is set to zero before returning.
  115913. **
  115914. ** If parameter bZero is non-zero, then any part of the input list following
  115915. ** the end of the output list is zeroed before returning.
  115916. */
  115917. static void fts3ColumnFilter(
  115918. int iCol, /* Column to filter on */
  115919. int bZero, /* Zero out anything following *ppList */
  115920. char **ppList, /* IN/OUT: Pointer to position list */
  115921. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  115922. ){
  115923. char *pList = *ppList;
  115924. int nList = *pnList;
  115925. char *pEnd = &pList[nList];
  115926. int iCurrent = 0;
  115927. char *p = pList;
  115928. assert( iCol>=0 );
  115929. while( 1 ){
  115930. char c = 0;
  115931. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  115932. if( iCol==iCurrent ){
  115933. nList = (int)(p - pList);
  115934. break;
  115935. }
  115936. nList -= (int)(p - pList);
  115937. pList = p;
  115938. if( nList==0 ){
  115939. break;
  115940. }
  115941. p = &pList[1];
  115942. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  115943. }
  115944. if( bZero && &pList[nList]!=pEnd ){
  115945. memset(&pList[nList], 0, pEnd - &pList[nList]);
  115946. }
  115947. *ppList = pList;
  115948. *pnList = nList;
  115949. }
  115950. /*
  115951. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  115952. ** existing data). Grow the buffer if required.
  115953. **
  115954. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  115955. ** trying to resize the buffer, return SQLITE_NOMEM.
  115956. */
  115957. static int fts3MsrBufferData(
  115958. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  115959. char *pList,
  115960. int nList
  115961. ){
  115962. if( nList>pMsr->nBuffer ){
  115963. char *pNew;
  115964. pMsr->nBuffer = nList*2;
  115965. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  115966. if( !pNew ) return SQLITE_NOMEM;
  115967. pMsr->aBuffer = pNew;
  115968. }
  115969. memcpy(pMsr->aBuffer, pList, nList);
  115970. return SQLITE_OK;
  115971. }
  115972. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  115973. Fts3Table *p, /* Virtual table handle */
  115974. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  115975. sqlite3_int64 *piDocid, /* OUT: Docid value */
  115976. char **paPoslist, /* OUT: Pointer to position list */
  115977. int *pnPoslist /* OUT: Size of position list in bytes */
  115978. ){
  115979. int nMerge = pMsr->nAdvance;
  115980. Fts3SegReader **apSegment = pMsr->apSegment;
  115981. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  115982. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  115983. );
  115984. if( nMerge==0 ){
  115985. *paPoslist = 0;
  115986. return SQLITE_OK;
  115987. }
  115988. while( 1 ){
  115989. Fts3SegReader *pSeg;
  115990. pSeg = pMsr->apSegment[0];
  115991. if( pSeg->pOffsetList==0 ){
  115992. *paPoslist = 0;
  115993. break;
  115994. }else{
  115995. int rc;
  115996. char *pList;
  115997. int nList;
  115998. int j;
  115999. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  116000. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  116001. j = 1;
  116002. while( rc==SQLITE_OK
  116003. && j<nMerge
  116004. && apSegment[j]->pOffsetList
  116005. && apSegment[j]->iDocid==iDocid
  116006. ){
  116007. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  116008. j++;
  116009. }
  116010. if( rc!=SQLITE_OK ) return rc;
  116011. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  116012. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  116013. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  116014. if( rc!=SQLITE_OK ) return rc;
  116015. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  116016. pList = pMsr->aBuffer;
  116017. }
  116018. if( pMsr->iColFilter>=0 ){
  116019. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  116020. }
  116021. if( nList>0 ){
  116022. *paPoslist = pList;
  116023. *piDocid = iDocid;
  116024. *pnPoslist = nList;
  116025. break;
  116026. }
  116027. }
  116028. }
  116029. return SQLITE_OK;
  116030. }
  116031. static int fts3SegReaderStart(
  116032. Fts3Table *p, /* Virtual table handle */
  116033. Fts3MultiSegReader *pCsr, /* Cursor object */
  116034. const char *zTerm, /* Term searched for (or NULL) */
  116035. int nTerm /* Length of zTerm in bytes */
  116036. ){
  116037. int i;
  116038. int nSeg = pCsr->nSegment;
  116039. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  116040. ** for, then advance each segment iterator until it points to a term of
  116041. ** equal or greater value than the specified term. This prevents many
  116042. ** unnecessary merge/sort operations for the case where single segment
  116043. ** b-tree leaf nodes contain more than one term.
  116044. */
  116045. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  116046. int res = 0;
  116047. Fts3SegReader *pSeg = pCsr->apSegment[i];
  116048. do {
  116049. int rc = fts3SegReaderNext(p, pSeg, 0);
  116050. if( rc!=SQLITE_OK ) return rc;
  116051. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  116052. if( pSeg->bLookup && res!=0 ){
  116053. fts3SegReaderSetEof(pSeg);
  116054. }
  116055. }
  116056. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  116057. return SQLITE_OK;
  116058. }
  116059. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  116060. Fts3Table *p, /* Virtual table handle */
  116061. Fts3MultiSegReader *pCsr, /* Cursor object */
  116062. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  116063. ){
  116064. pCsr->pFilter = pFilter;
  116065. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  116066. }
  116067. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  116068. Fts3Table *p, /* Virtual table handle */
  116069. Fts3MultiSegReader *pCsr, /* Cursor object */
  116070. int iCol, /* Column to match on. */
  116071. const char *zTerm, /* Term to iterate through a doclist for */
  116072. int nTerm /* Number of bytes in zTerm */
  116073. ){
  116074. int i;
  116075. int rc;
  116076. int nSegment = pCsr->nSegment;
  116077. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  116078. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  116079. );
  116080. assert( pCsr->pFilter==0 );
  116081. assert( zTerm && nTerm>0 );
  116082. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  116083. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  116084. if( rc!=SQLITE_OK ) return rc;
  116085. /* Determine how many of the segments actually point to zTerm/nTerm. */
  116086. for(i=0; i<nSegment; i++){
  116087. Fts3SegReader *pSeg = pCsr->apSegment[i];
  116088. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  116089. break;
  116090. }
  116091. }
  116092. pCsr->nAdvance = i;
  116093. /* Advance each of the segments to point to the first docid. */
  116094. for(i=0; i<pCsr->nAdvance; i++){
  116095. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  116096. if( rc!=SQLITE_OK ) return rc;
  116097. }
  116098. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  116099. assert( iCol<0 || iCol<p->nColumn );
  116100. pCsr->iColFilter = iCol;
  116101. return SQLITE_OK;
  116102. }
  116103. /*
  116104. ** This function is called on a MultiSegReader that has been started using
  116105. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  116106. ** have been made. Calling this function puts the MultiSegReader in such
  116107. ** a state that if the next two calls are:
  116108. **
  116109. ** sqlite3Fts3SegReaderStart()
  116110. ** sqlite3Fts3SegReaderStep()
  116111. **
  116112. ** then the entire doclist for the term is available in
  116113. ** MultiSegReader.aDoclist/nDoclist.
  116114. */
  116115. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  116116. int i; /* Used to iterate through segment-readers */
  116117. assert( pCsr->zTerm==0 );
  116118. assert( pCsr->nTerm==0 );
  116119. assert( pCsr->aDoclist==0 );
  116120. assert( pCsr->nDoclist==0 );
  116121. pCsr->nAdvance = 0;
  116122. pCsr->bRestart = 1;
  116123. for(i=0; i<pCsr->nSegment; i++){
  116124. pCsr->apSegment[i]->pOffsetList = 0;
  116125. pCsr->apSegment[i]->nOffsetList = 0;
  116126. pCsr->apSegment[i]->iDocid = 0;
  116127. }
  116128. return SQLITE_OK;
  116129. }
  116130. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  116131. Fts3Table *p, /* Virtual table handle */
  116132. Fts3MultiSegReader *pCsr /* Cursor object */
  116133. ){
  116134. int rc = SQLITE_OK;
  116135. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  116136. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  116137. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  116138. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  116139. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  116140. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  116141. Fts3SegReader **apSegment = pCsr->apSegment;
  116142. int nSegment = pCsr->nSegment;
  116143. Fts3SegFilter *pFilter = pCsr->pFilter;
  116144. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  116145. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  116146. );
  116147. if( pCsr->nSegment==0 ) return SQLITE_OK;
  116148. do {
  116149. int nMerge;
  116150. int i;
  116151. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  116152. ** forward. Then sort the list in order of current term again.
  116153. */
  116154. for(i=0; i<pCsr->nAdvance; i++){
  116155. Fts3SegReader *pSeg = apSegment[i];
  116156. if( pSeg->bLookup ){
  116157. fts3SegReaderSetEof(pSeg);
  116158. }else{
  116159. rc = fts3SegReaderNext(p, pSeg, 0);
  116160. }
  116161. if( rc!=SQLITE_OK ) return rc;
  116162. }
  116163. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  116164. pCsr->nAdvance = 0;
  116165. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  116166. assert( rc==SQLITE_OK );
  116167. if( apSegment[0]->aNode==0 ) break;
  116168. pCsr->nTerm = apSegment[0]->nTerm;
  116169. pCsr->zTerm = apSegment[0]->zTerm;
  116170. /* If this is a prefix-search, and if the term that apSegment[0] points
  116171. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  116172. ** required callbacks have been made. In this case exit early.
  116173. **
  116174. ** Similarly, if this is a search for an exact match, and the first term
  116175. ** of segment apSegment[0] is not a match, exit early.
  116176. */
  116177. if( pFilter->zTerm && !isScan ){
  116178. if( pCsr->nTerm<pFilter->nTerm
  116179. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  116180. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  116181. ){
  116182. break;
  116183. }
  116184. }
  116185. nMerge = 1;
  116186. while( nMerge<nSegment
  116187. && apSegment[nMerge]->aNode
  116188. && apSegment[nMerge]->nTerm==pCsr->nTerm
  116189. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  116190. ){
  116191. nMerge++;
  116192. }
  116193. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  116194. if( nMerge==1
  116195. && !isIgnoreEmpty
  116196. && !isFirst
  116197. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  116198. ){
  116199. pCsr->nDoclist = apSegment[0]->nDoclist;
  116200. if( fts3SegReaderIsPending(apSegment[0]) ){
  116201. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  116202. pCsr->aDoclist = pCsr->aBuffer;
  116203. }else{
  116204. pCsr->aDoclist = apSegment[0]->aDoclist;
  116205. }
  116206. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  116207. }else{
  116208. int nDoclist = 0; /* Size of doclist */
  116209. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  116210. /* The current term of the first nMerge entries in the array
  116211. ** of Fts3SegReader objects is the same. The doclists must be merged
  116212. ** and a single term returned with the merged doclist.
  116213. */
  116214. for(i=0; i<nMerge; i++){
  116215. fts3SegReaderFirstDocid(p, apSegment[i]);
  116216. }
  116217. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  116218. while( apSegment[0]->pOffsetList ){
  116219. int j; /* Number of segments that share a docid */
  116220. char *pList = 0;
  116221. int nList = 0;
  116222. int nByte;
  116223. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  116224. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  116225. j = 1;
  116226. while( j<nMerge
  116227. && apSegment[j]->pOffsetList
  116228. && apSegment[j]->iDocid==iDocid
  116229. ){
  116230. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  116231. j++;
  116232. }
  116233. if( isColFilter ){
  116234. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  116235. }
  116236. if( !isIgnoreEmpty || nList>0 ){
  116237. /* Calculate the 'docid' delta value to write into the merged
  116238. ** doclist. */
  116239. sqlite3_int64 iDelta;
  116240. if( p->bDescIdx && nDoclist>0 ){
  116241. iDelta = iPrev - iDocid;
  116242. }else{
  116243. iDelta = iDocid - iPrev;
  116244. }
  116245. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  116246. assert( nDoclist>0 || iDelta==iDocid );
  116247. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  116248. if( nDoclist+nByte>pCsr->nBuffer ){
  116249. char *aNew;
  116250. pCsr->nBuffer = (nDoclist+nByte)*2;
  116251. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  116252. if( !aNew ){
  116253. return SQLITE_NOMEM;
  116254. }
  116255. pCsr->aBuffer = aNew;
  116256. }
  116257. if( isFirst ){
  116258. char *a = &pCsr->aBuffer[nDoclist];
  116259. int nWrite;
  116260. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  116261. if( nWrite ){
  116262. iPrev = iDocid;
  116263. nDoclist += nWrite;
  116264. }
  116265. }else{
  116266. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  116267. iPrev = iDocid;
  116268. if( isRequirePos ){
  116269. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  116270. nDoclist += nList;
  116271. pCsr->aBuffer[nDoclist++] = '\0';
  116272. }
  116273. }
  116274. }
  116275. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  116276. }
  116277. if( nDoclist>0 ){
  116278. pCsr->aDoclist = pCsr->aBuffer;
  116279. pCsr->nDoclist = nDoclist;
  116280. rc = SQLITE_ROW;
  116281. }
  116282. }
  116283. pCsr->nAdvance = nMerge;
  116284. }while( rc==SQLITE_OK );
  116285. return rc;
  116286. }
  116287. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  116288. Fts3MultiSegReader *pCsr /* Cursor object */
  116289. ){
  116290. if( pCsr ){
  116291. int i;
  116292. for(i=0; i<pCsr->nSegment; i++){
  116293. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  116294. }
  116295. sqlite3_free(pCsr->apSegment);
  116296. sqlite3_free(pCsr->aBuffer);
  116297. pCsr->nSegment = 0;
  116298. pCsr->apSegment = 0;
  116299. pCsr->aBuffer = 0;
  116300. }
  116301. }
  116302. /*
  116303. ** Merge all level iLevel segments in the database into a single
  116304. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  116305. ** single segment with a level equal to the numerically largest level
  116306. ** currently present in the database.
  116307. **
  116308. ** If this function is called with iLevel<0, but there is only one
  116309. ** segment in the database, SQLITE_DONE is returned immediately.
  116310. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  116311. ** an SQLite error code is returned.
  116312. */
  116313. static int fts3SegmentMerge(
  116314. Fts3Table *p,
  116315. int iLangid, /* Language id to merge */
  116316. int iIndex, /* Index in p->aIndex[] to merge */
  116317. int iLevel /* Level to merge */
  116318. ){
  116319. int rc; /* Return code */
  116320. int iIdx = 0; /* Index of new segment */
  116321. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  116322. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  116323. Fts3SegFilter filter; /* Segment term filter condition */
  116324. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  116325. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  116326. assert( iLevel==FTS3_SEGCURSOR_ALL
  116327. || iLevel==FTS3_SEGCURSOR_PENDING
  116328. || iLevel>=0
  116329. );
  116330. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  116331. assert( iIndex>=0 && iIndex<p->nIndex );
  116332. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  116333. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  116334. if( iLevel==FTS3_SEGCURSOR_ALL ){
  116335. /* This call is to merge all segments in the database to a single
  116336. ** segment. The level of the new segment is equal to the numerically
  116337. ** greatest segment level currently present in the database for this
  116338. ** index. The idx of the new segment is always 0. */
  116339. if( csr.nSegment==1 ){
  116340. rc = SQLITE_DONE;
  116341. goto finished;
  116342. }
  116343. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  116344. bIgnoreEmpty = 1;
  116345. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  116346. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  116347. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  116348. }else{
  116349. /* This call is to merge all segments at level iLevel. find the next
  116350. ** available segment index at level iLevel+1. The call to
  116351. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  116352. ** a single iLevel+2 segment if necessary. */
  116353. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  116354. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  116355. }
  116356. if( rc!=SQLITE_OK ) goto finished;
  116357. assert( csr.nSegment>0 );
  116358. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  116359. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  116360. memset(&filter, 0, sizeof(Fts3SegFilter));
  116361. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  116362. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  116363. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  116364. while( SQLITE_OK==rc ){
  116365. rc = sqlite3Fts3SegReaderStep(p, &csr);
  116366. if( rc!=SQLITE_ROW ) break;
  116367. rc = fts3SegWriterAdd(p, &pWriter, 1,
  116368. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  116369. }
  116370. if( rc!=SQLITE_OK ) goto finished;
  116371. assert( pWriter );
  116372. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  116373. rc = fts3DeleteSegdir(
  116374. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  116375. );
  116376. if( rc!=SQLITE_OK ) goto finished;
  116377. }
  116378. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  116379. finished:
  116380. fts3SegWriterFree(pWriter);
  116381. sqlite3Fts3SegReaderFinish(&csr);
  116382. return rc;
  116383. }
  116384. /*
  116385. ** Flush the contents of pendingTerms to level 0 segments.
  116386. */
  116387. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  116388. int rc = SQLITE_OK;
  116389. int i;
  116390. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  116391. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  116392. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  116393. }
  116394. sqlite3Fts3PendingTermsClear(p);
  116395. /* Determine the auto-incr-merge setting if unknown. If enabled,
  116396. ** estimate the number of leaf blocks of content to be written
  116397. */
  116398. if( rc==SQLITE_OK && p->bHasStat
  116399. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  116400. ){
  116401. sqlite3_stmt *pStmt = 0;
  116402. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  116403. if( rc==SQLITE_OK ){
  116404. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  116405. rc = sqlite3_step(pStmt);
  116406. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  116407. rc = sqlite3_reset(pStmt);
  116408. }
  116409. }
  116410. return rc;
  116411. }
  116412. /*
  116413. ** Encode N integers as varints into a blob.
  116414. */
  116415. static void fts3EncodeIntArray(
  116416. int N, /* The number of integers to encode */
  116417. u32 *a, /* The integer values */
  116418. char *zBuf, /* Write the BLOB here */
  116419. int *pNBuf /* Write number of bytes if zBuf[] used here */
  116420. ){
  116421. int i, j;
  116422. for(i=j=0; i<N; i++){
  116423. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  116424. }
  116425. *pNBuf = j;
  116426. }
  116427. /*
  116428. ** Decode a blob of varints into N integers
  116429. */
  116430. static void fts3DecodeIntArray(
  116431. int N, /* The number of integers to decode */
  116432. u32 *a, /* Write the integer values */
  116433. const char *zBuf, /* The BLOB containing the varints */
  116434. int nBuf /* size of the BLOB */
  116435. ){
  116436. int i, j;
  116437. UNUSED_PARAMETER(nBuf);
  116438. for(i=j=0; i<N; i++){
  116439. sqlite3_int64 x;
  116440. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  116441. assert(j<=nBuf);
  116442. a[i] = (u32)(x & 0xffffffff);
  116443. }
  116444. }
  116445. /*
  116446. ** Insert the sizes (in tokens) for each column of the document
  116447. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  116448. ** a blob of varints.
  116449. */
  116450. static void fts3InsertDocsize(
  116451. int *pRC, /* Result code */
  116452. Fts3Table *p, /* Table into which to insert */
  116453. u32 *aSz /* Sizes of each column, in tokens */
  116454. ){
  116455. char *pBlob; /* The BLOB encoding of the document size */
  116456. int nBlob; /* Number of bytes in the BLOB */
  116457. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  116458. int rc; /* Result code from subfunctions */
  116459. if( *pRC ) return;
  116460. pBlob = sqlite3_malloc( 10*p->nColumn );
  116461. if( pBlob==0 ){
  116462. *pRC = SQLITE_NOMEM;
  116463. return;
  116464. }
  116465. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  116466. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  116467. if( rc ){
  116468. sqlite3_free(pBlob);
  116469. *pRC = rc;
  116470. return;
  116471. }
  116472. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  116473. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  116474. sqlite3_step(pStmt);
  116475. *pRC = sqlite3_reset(pStmt);
  116476. }
  116477. /*
  116478. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  116479. ** where N is the number of user defined columns in the fts3 table plus
  116480. ** two. If nCol is the number of user defined columns, then values of the
  116481. ** varints are set as follows:
  116482. **
  116483. ** Varint 0: Total number of rows in the table.
  116484. **
  116485. ** Varint 1..nCol: For each column, the total number of tokens stored in
  116486. ** the column for all rows of the table.
  116487. **
  116488. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  116489. ** columns of all rows of the table.
  116490. **
  116491. */
  116492. static void fts3UpdateDocTotals(
  116493. int *pRC, /* The result code */
  116494. Fts3Table *p, /* Table being updated */
  116495. u32 *aSzIns, /* Size increases */
  116496. u32 *aSzDel, /* Size decreases */
  116497. int nChng /* Change in the number of documents */
  116498. ){
  116499. char *pBlob; /* Storage for BLOB written into %_stat */
  116500. int nBlob; /* Size of BLOB written into %_stat */
  116501. u32 *a; /* Array of integers that becomes the BLOB */
  116502. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  116503. int i; /* Loop counter */
  116504. int rc; /* Result code from subfunctions */
  116505. const int nStat = p->nColumn+2;
  116506. if( *pRC ) return;
  116507. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  116508. if( a==0 ){
  116509. *pRC = SQLITE_NOMEM;
  116510. return;
  116511. }
  116512. pBlob = (char*)&a[nStat];
  116513. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  116514. if( rc ){
  116515. sqlite3_free(a);
  116516. *pRC = rc;
  116517. return;
  116518. }
  116519. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  116520. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  116521. fts3DecodeIntArray(nStat, a,
  116522. sqlite3_column_blob(pStmt, 0),
  116523. sqlite3_column_bytes(pStmt, 0));
  116524. }else{
  116525. memset(a, 0, sizeof(u32)*(nStat) );
  116526. }
  116527. rc = sqlite3_reset(pStmt);
  116528. if( rc!=SQLITE_OK ){
  116529. sqlite3_free(a);
  116530. *pRC = rc;
  116531. return;
  116532. }
  116533. if( nChng<0 && a[0]<(u32)(-nChng) ){
  116534. a[0] = 0;
  116535. }else{
  116536. a[0] += nChng;
  116537. }
  116538. for(i=0; i<p->nColumn+1; i++){
  116539. u32 x = a[i+1];
  116540. if( x+aSzIns[i] < aSzDel[i] ){
  116541. x = 0;
  116542. }else{
  116543. x = x + aSzIns[i] - aSzDel[i];
  116544. }
  116545. a[i+1] = x;
  116546. }
  116547. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  116548. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  116549. if( rc ){
  116550. sqlite3_free(a);
  116551. *pRC = rc;
  116552. return;
  116553. }
  116554. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  116555. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  116556. sqlite3_step(pStmt);
  116557. *pRC = sqlite3_reset(pStmt);
  116558. sqlite3_free(a);
  116559. }
  116560. /*
  116561. ** Merge the entire database so that there is one segment for each
  116562. ** iIndex/iLangid combination.
  116563. */
  116564. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  116565. int bSeenDone = 0;
  116566. int rc;
  116567. sqlite3_stmt *pAllLangid = 0;
  116568. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  116569. if( rc==SQLITE_OK ){
  116570. int rc2;
  116571. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  116572. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  116573. int i;
  116574. int iLangid = sqlite3_column_int(pAllLangid, 0);
  116575. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  116576. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  116577. if( rc==SQLITE_DONE ){
  116578. bSeenDone = 1;
  116579. rc = SQLITE_OK;
  116580. }
  116581. }
  116582. }
  116583. rc2 = sqlite3_reset(pAllLangid);
  116584. if( rc==SQLITE_OK ) rc = rc2;
  116585. }
  116586. sqlite3Fts3SegmentsClose(p);
  116587. sqlite3Fts3PendingTermsClear(p);
  116588. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  116589. }
  116590. /*
  116591. ** This function is called when the user executes the following statement:
  116592. **
  116593. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  116594. **
  116595. ** The entire FTS index is discarded and rebuilt. If the table is one
  116596. ** created using the content=xxx option, then the new index is based on
  116597. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  116598. ** on the contents of the %_content table.
  116599. */
  116600. static int fts3DoRebuild(Fts3Table *p){
  116601. int rc; /* Return Code */
  116602. rc = fts3DeleteAll(p, 0);
  116603. if( rc==SQLITE_OK ){
  116604. u32 *aSz = 0;
  116605. u32 *aSzIns = 0;
  116606. u32 *aSzDel = 0;
  116607. sqlite3_stmt *pStmt = 0;
  116608. int nEntry = 0;
  116609. /* Compose and prepare an SQL statement to loop through the content table */
  116610. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  116611. if( !zSql ){
  116612. rc = SQLITE_NOMEM;
  116613. }else{
  116614. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  116615. sqlite3_free(zSql);
  116616. }
  116617. if( rc==SQLITE_OK ){
  116618. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  116619. aSz = (u32 *)sqlite3_malloc(nByte);
  116620. if( aSz==0 ){
  116621. rc = SQLITE_NOMEM;
  116622. }else{
  116623. memset(aSz, 0, nByte);
  116624. aSzIns = &aSz[p->nColumn+1];
  116625. aSzDel = &aSzIns[p->nColumn+1];
  116626. }
  116627. }
  116628. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  116629. int iCol;
  116630. int iLangid = langidFromSelect(p, pStmt);
  116631. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  116632. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  116633. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  116634. if( p->abNotindexed[iCol]==0 ){
  116635. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  116636. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  116637. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  116638. }
  116639. }
  116640. if( p->bHasDocsize ){
  116641. fts3InsertDocsize(&rc, p, aSz);
  116642. }
  116643. if( rc!=SQLITE_OK ){
  116644. sqlite3_finalize(pStmt);
  116645. pStmt = 0;
  116646. }else{
  116647. nEntry++;
  116648. for(iCol=0; iCol<=p->nColumn; iCol++){
  116649. aSzIns[iCol] += aSz[iCol];
  116650. }
  116651. }
  116652. }
  116653. if( p->bFts4 ){
  116654. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  116655. }
  116656. sqlite3_free(aSz);
  116657. if( pStmt ){
  116658. int rc2 = sqlite3_finalize(pStmt);
  116659. if( rc==SQLITE_OK ){
  116660. rc = rc2;
  116661. }
  116662. }
  116663. }
  116664. return rc;
  116665. }
  116666. /*
  116667. ** This function opens a cursor used to read the input data for an
  116668. ** incremental merge operation. Specifically, it opens a cursor to scan
  116669. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  116670. ** level iAbsLevel.
  116671. */
  116672. static int fts3IncrmergeCsr(
  116673. Fts3Table *p, /* FTS3 table handle */
  116674. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  116675. int nSeg, /* Number of segments to merge */
  116676. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  116677. ){
  116678. int rc; /* Return Code */
  116679. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  116680. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  116681. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  116682. memset(pCsr, 0, sizeof(*pCsr));
  116683. nByte = sizeof(Fts3SegReader *) * nSeg;
  116684. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  116685. if( pCsr->apSegment==0 ){
  116686. rc = SQLITE_NOMEM;
  116687. }else{
  116688. memset(pCsr->apSegment, 0, nByte);
  116689. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  116690. }
  116691. if( rc==SQLITE_OK ){
  116692. int i;
  116693. int rc2;
  116694. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  116695. assert( pCsr->nSegment==0 );
  116696. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  116697. rc = sqlite3Fts3SegReaderNew(i, 0,
  116698. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  116699. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  116700. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  116701. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  116702. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  116703. &pCsr->apSegment[i]
  116704. );
  116705. pCsr->nSegment++;
  116706. }
  116707. rc2 = sqlite3_reset(pStmt);
  116708. if( rc==SQLITE_OK ) rc = rc2;
  116709. }
  116710. return rc;
  116711. }
  116712. typedef struct IncrmergeWriter IncrmergeWriter;
  116713. typedef struct NodeWriter NodeWriter;
  116714. typedef struct Blob Blob;
  116715. typedef struct NodeReader NodeReader;
  116716. /*
  116717. ** An instance of the following structure is used as a dynamic buffer
  116718. ** to build up nodes or other blobs of data in.
  116719. **
  116720. ** The function blobGrowBuffer() is used to extend the allocation.
  116721. */
  116722. struct Blob {
  116723. char *a; /* Pointer to allocation */
  116724. int n; /* Number of valid bytes of data in a[] */
  116725. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  116726. };
  116727. /*
  116728. ** This structure is used to build up buffers containing segment b-tree
  116729. ** nodes (blocks).
  116730. */
  116731. struct NodeWriter {
  116732. sqlite3_int64 iBlock; /* Current block id */
  116733. Blob key; /* Last key written to the current block */
  116734. Blob block; /* Current block image */
  116735. };
  116736. /*
  116737. ** An object of this type contains the state required to create or append
  116738. ** to an appendable b-tree segment.
  116739. */
  116740. struct IncrmergeWriter {
  116741. int nLeafEst; /* Space allocated for leaf blocks */
  116742. int nWork; /* Number of leaf pages flushed */
  116743. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  116744. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  116745. sqlite3_int64 iStart; /* Block number of first allocated block */
  116746. sqlite3_int64 iEnd; /* Block number of last allocated block */
  116747. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  116748. };
  116749. /*
  116750. ** An object of the following type is used to read data from a single
  116751. ** FTS segment node. See the following functions:
  116752. **
  116753. ** nodeReaderInit()
  116754. ** nodeReaderNext()
  116755. ** nodeReaderRelease()
  116756. */
  116757. struct NodeReader {
  116758. const char *aNode;
  116759. int nNode;
  116760. int iOff; /* Current offset within aNode[] */
  116761. /* Output variables. Containing the current node entry. */
  116762. sqlite3_int64 iChild; /* Pointer to child node */
  116763. Blob term; /* Current term */
  116764. const char *aDoclist; /* Pointer to doclist */
  116765. int nDoclist; /* Size of doclist in bytes */
  116766. };
  116767. /*
  116768. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  116769. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  116770. ** bytes in size, extend (realloc) it to be so.
  116771. **
  116772. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  116773. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  116774. ** to reflect the new size of the pBlob->a[] buffer.
  116775. */
  116776. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  116777. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  116778. int nAlloc = nMin;
  116779. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  116780. if( a ){
  116781. pBlob->nAlloc = nAlloc;
  116782. pBlob->a = a;
  116783. }else{
  116784. *pRc = SQLITE_NOMEM;
  116785. }
  116786. }
  116787. }
  116788. /*
  116789. ** Attempt to advance the node-reader object passed as the first argument to
  116790. ** the next entry on the node.
  116791. **
  116792. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  116793. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  116794. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  116795. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  116796. ** variables for the new entry.
  116797. */
  116798. static int nodeReaderNext(NodeReader *p){
  116799. int bFirst = (p->term.n==0); /* True for first term on the node */
  116800. int nPrefix = 0; /* Bytes to copy from previous term */
  116801. int nSuffix = 0; /* Bytes to append to the prefix */
  116802. int rc = SQLITE_OK; /* Return code */
  116803. assert( p->aNode );
  116804. if( p->iChild && bFirst==0 ) p->iChild++;
  116805. if( p->iOff>=p->nNode ){
  116806. /* EOF */
  116807. p->aNode = 0;
  116808. }else{
  116809. if( bFirst==0 ){
  116810. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  116811. }
  116812. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  116813. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  116814. if( rc==SQLITE_OK ){
  116815. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  116816. p->term.n = nPrefix+nSuffix;
  116817. p->iOff += nSuffix;
  116818. if( p->iChild==0 ){
  116819. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  116820. p->aDoclist = &p->aNode[p->iOff];
  116821. p->iOff += p->nDoclist;
  116822. }
  116823. }
  116824. }
  116825. assert( p->iOff<=p->nNode );
  116826. return rc;
  116827. }
  116828. /*
  116829. ** Release all dynamic resources held by node-reader object *p.
  116830. */
  116831. static void nodeReaderRelease(NodeReader *p){
  116832. sqlite3_free(p->term.a);
  116833. }
  116834. /*
  116835. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  116836. **
  116837. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  116838. ** point to the first entry on the node (if any). Otherwise, an SQLite
  116839. ** error code is returned.
  116840. */
  116841. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  116842. memset(p, 0, sizeof(NodeReader));
  116843. p->aNode = aNode;
  116844. p->nNode = nNode;
  116845. /* Figure out if this is a leaf or an internal node. */
  116846. if( p->aNode[0] ){
  116847. /* An internal node. */
  116848. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  116849. }else{
  116850. p->iOff = 1;
  116851. }
  116852. return nodeReaderNext(p);
  116853. }
  116854. /*
  116855. ** This function is called while writing an FTS segment each time a leaf o
  116856. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  116857. ** to be greater than the largest key on the node just written, but smaller
  116858. ** than or equal to the first key that will be written to the next leaf
  116859. ** node.
  116860. **
  116861. ** The block id of the leaf node just written to disk may be found in
  116862. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  116863. */
  116864. static int fts3IncrmergePush(
  116865. Fts3Table *p, /* Fts3 table handle */
  116866. IncrmergeWriter *pWriter, /* Writer object */
  116867. const char *zTerm, /* Term to write to internal node */
  116868. int nTerm /* Bytes at zTerm */
  116869. ){
  116870. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  116871. int iLayer;
  116872. assert( nTerm>0 );
  116873. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  116874. sqlite3_int64 iNextPtr = 0;
  116875. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  116876. int rc = SQLITE_OK;
  116877. int nPrefix;
  116878. int nSuffix;
  116879. int nSpace;
  116880. /* Figure out how much space the key will consume if it is written to
  116881. ** the current node of layer iLayer. Due to the prefix compression,
  116882. ** the space required changes depending on which node the key is to
  116883. ** be added to. */
  116884. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  116885. nSuffix = nTerm - nPrefix;
  116886. nSpace = sqlite3Fts3VarintLen(nPrefix);
  116887. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  116888. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  116889. /* If the current node of layer iLayer contains zero keys, or if adding
  116890. ** the key to it will not cause it to grow to larger than nNodeSize
  116891. ** bytes in size, write the key here. */
  116892. Blob *pBlk = &pNode->block;
  116893. if( pBlk->n==0 ){
  116894. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  116895. if( rc==SQLITE_OK ){
  116896. pBlk->a[0] = (char)iLayer;
  116897. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  116898. }
  116899. }
  116900. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  116901. blobGrowBuffer(&pNode->key, nTerm, &rc);
  116902. if( rc==SQLITE_OK ){
  116903. if( pNode->key.n ){
  116904. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  116905. }
  116906. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  116907. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  116908. pBlk->n += nSuffix;
  116909. memcpy(pNode->key.a, zTerm, nTerm);
  116910. pNode->key.n = nTerm;
  116911. }
  116912. }else{
  116913. /* Otherwise, flush the current node of layer iLayer to disk.
  116914. ** Then allocate a new, empty sibling node. The key will be written
  116915. ** into the parent of this node. */
  116916. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  116917. assert( pNode->block.nAlloc>=p->nNodeSize );
  116918. pNode->block.a[0] = (char)iLayer;
  116919. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  116920. iNextPtr = pNode->iBlock;
  116921. pNode->iBlock++;
  116922. pNode->key.n = 0;
  116923. }
  116924. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  116925. iPtr = iNextPtr;
  116926. }
  116927. assert( 0 );
  116928. return 0;
  116929. }
  116930. /*
  116931. ** Append a term and (optionally) doclist to the FTS segment node currently
  116932. ** stored in blob *pNode. The node need not contain any terms, but the
  116933. ** header must be written before this function is called.
  116934. **
  116935. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  116936. ** followed by the left-hand-child varint for an internal node.
  116937. **
  116938. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  116939. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  116940. ** node, both aDoclist and nDoclist must be passed 0.
  116941. **
  116942. ** If the size of the value in blob pPrev is zero, then this is the first
  116943. ** term written to the node. Otherwise, pPrev contains a copy of the
  116944. ** previous term. Before this function returns, it is updated to contain a
  116945. ** copy of zTerm/nTerm.
  116946. **
  116947. ** It is assumed that the buffer associated with pNode is already large
  116948. ** enough to accommodate the new entry. The buffer associated with pPrev
  116949. ** is extended by this function if requrired.
  116950. **
  116951. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  116952. ** returned. Otherwise, SQLITE_OK.
  116953. */
  116954. static int fts3AppendToNode(
  116955. Blob *pNode, /* Current node image to append to */
  116956. Blob *pPrev, /* Buffer containing previous term written */
  116957. const char *zTerm, /* New term to write */
  116958. int nTerm, /* Size of zTerm in bytes */
  116959. const char *aDoclist, /* Doclist (or NULL) to write */
  116960. int nDoclist /* Size of aDoclist in bytes */
  116961. ){
  116962. int rc = SQLITE_OK; /* Return code */
  116963. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  116964. int nPrefix; /* Size of term prefix in bytes */
  116965. int nSuffix; /* Size of term suffix in bytes */
  116966. /* Node must have already been started. There must be a doclist for a
  116967. ** leaf node, and there must not be a doclist for an internal node. */
  116968. assert( pNode->n>0 );
  116969. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  116970. blobGrowBuffer(pPrev, nTerm, &rc);
  116971. if( rc!=SQLITE_OK ) return rc;
  116972. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  116973. nSuffix = nTerm - nPrefix;
  116974. memcpy(pPrev->a, zTerm, nTerm);
  116975. pPrev->n = nTerm;
  116976. if( bFirst==0 ){
  116977. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  116978. }
  116979. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  116980. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  116981. pNode->n += nSuffix;
  116982. if( aDoclist ){
  116983. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  116984. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  116985. pNode->n += nDoclist;
  116986. }
  116987. assert( pNode->n<=pNode->nAlloc );
  116988. return SQLITE_OK;
  116989. }
  116990. /*
  116991. ** Append the current term and doclist pointed to by cursor pCsr to the
  116992. ** appendable b-tree segment opened for writing by pWriter.
  116993. **
  116994. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  116995. */
  116996. static int fts3IncrmergeAppend(
  116997. Fts3Table *p, /* Fts3 table handle */
  116998. IncrmergeWriter *pWriter, /* Writer object */
  116999. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  117000. ){
  117001. const char *zTerm = pCsr->zTerm;
  117002. int nTerm = pCsr->nTerm;
  117003. const char *aDoclist = pCsr->aDoclist;
  117004. int nDoclist = pCsr->nDoclist;
  117005. int rc = SQLITE_OK; /* Return code */
  117006. int nSpace; /* Total space in bytes required on leaf */
  117007. int nPrefix; /* Size of prefix shared with previous term */
  117008. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  117009. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  117010. pLeaf = &pWriter->aNodeWriter[0];
  117011. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  117012. nSuffix = nTerm - nPrefix;
  117013. nSpace = sqlite3Fts3VarintLen(nPrefix);
  117014. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  117015. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  117016. /* If the current block is not empty, and if adding this term/doclist
  117017. ** to the current block would make it larger than Fts3Table.nNodeSize
  117018. ** bytes, write this block out to the database. */
  117019. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  117020. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  117021. pWriter->nWork++;
  117022. /* Add the current term to the parent node. The term added to the
  117023. ** parent must:
  117024. **
  117025. ** a) be greater than the largest term on the leaf node just written
  117026. ** to the database (still available in pLeaf->key), and
  117027. **
  117028. ** b) be less than or equal to the term about to be added to the new
  117029. ** leaf node (zTerm/nTerm).
  117030. **
  117031. ** In other words, it must be the prefix of zTerm 1 byte longer than
  117032. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  117033. */
  117034. if( rc==SQLITE_OK ){
  117035. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  117036. }
  117037. /* Advance to the next output block */
  117038. pLeaf->iBlock++;
  117039. pLeaf->key.n = 0;
  117040. pLeaf->block.n = 0;
  117041. nSuffix = nTerm;
  117042. nSpace = 1;
  117043. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  117044. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  117045. }
  117046. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  117047. if( rc==SQLITE_OK ){
  117048. if( pLeaf->block.n==0 ){
  117049. pLeaf->block.n = 1;
  117050. pLeaf->block.a[0] = '\0';
  117051. }
  117052. rc = fts3AppendToNode(
  117053. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  117054. );
  117055. }
  117056. return rc;
  117057. }
  117058. /*
  117059. ** This function is called to release all dynamic resources held by the
  117060. ** merge-writer object pWriter, and if no error has occurred, to flush
  117061. ** all outstanding node buffers held by pWriter to disk.
  117062. **
  117063. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  117064. ** is made to write any data to disk. Instead, this function serves only
  117065. ** to release outstanding resources.
  117066. **
  117067. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  117068. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  117069. ** returning.
  117070. */
  117071. static void fts3IncrmergeRelease(
  117072. Fts3Table *p, /* FTS3 table handle */
  117073. IncrmergeWriter *pWriter, /* Merge-writer object */
  117074. int *pRc /* IN/OUT: Error code */
  117075. ){
  117076. int i; /* Used to iterate through non-root layers */
  117077. int iRoot; /* Index of root in pWriter->aNodeWriter */
  117078. NodeWriter *pRoot; /* NodeWriter for root node */
  117079. int rc = *pRc; /* Error code */
  117080. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  117081. ** root node. If the segment fits entirely on a single leaf node, iRoot
  117082. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  117083. ** will be 1. And so on. */
  117084. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  117085. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  117086. if( pNode->block.n>0 ) break;
  117087. assert( *pRc || pNode->block.nAlloc==0 );
  117088. assert( *pRc || pNode->key.nAlloc==0 );
  117089. sqlite3_free(pNode->block.a);
  117090. sqlite3_free(pNode->key.a);
  117091. }
  117092. /* Empty output segment. This is a no-op. */
  117093. if( iRoot<0 ) return;
  117094. /* The entire output segment fits on a single node. Normally, this means
  117095. ** the node would be stored as a blob in the "root" column of the %_segdir
  117096. ** table. However, this is not permitted in this case. The problem is that
  117097. ** space has already been reserved in the %_segments table, and so the
  117098. ** start_block and end_block fields of the %_segdir table must be populated.
  117099. ** And, by design or by accident, released versions of FTS cannot handle
  117100. ** segments that fit entirely on the root node with start_block!=0.
  117101. **
  117102. ** Instead, create a synthetic root node that contains nothing but a
  117103. ** pointer to the single content node. So that the segment consists of a
  117104. ** single leaf and a single interior (root) node.
  117105. **
  117106. ** Todo: Better might be to defer allocating space in the %_segments
  117107. ** table until we are sure it is needed.
  117108. */
  117109. if( iRoot==0 ){
  117110. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  117111. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  117112. if( rc==SQLITE_OK ){
  117113. pBlock->a[0] = 0x01;
  117114. pBlock->n = 1 + sqlite3Fts3PutVarint(
  117115. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  117116. );
  117117. }
  117118. iRoot = 1;
  117119. }
  117120. pRoot = &pWriter->aNodeWriter[iRoot];
  117121. /* Flush all currently outstanding nodes to disk. */
  117122. for(i=0; i<iRoot; i++){
  117123. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  117124. if( pNode->block.n>0 && rc==SQLITE_OK ){
  117125. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  117126. }
  117127. sqlite3_free(pNode->block.a);
  117128. sqlite3_free(pNode->key.a);
  117129. }
  117130. /* Write the %_segdir record. */
  117131. if( rc==SQLITE_OK ){
  117132. rc = fts3WriteSegdir(p,
  117133. pWriter->iAbsLevel+1, /* level */
  117134. pWriter->iIdx, /* idx */
  117135. pWriter->iStart, /* start_block */
  117136. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  117137. pWriter->iEnd, /* end_block */
  117138. pRoot->block.a, pRoot->block.n /* root */
  117139. );
  117140. }
  117141. sqlite3_free(pRoot->block.a);
  117142. sqlite3_free(pRoot->key.a);
  117143. *pRc = rc;
  117144. }
  117145. /*
  117146. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  117147. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  117148. ** the other, it is considered to be smaller than the other.
  117149. **
  117150. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  117151. ** if it is greater.
  117152. */
  117153. static int fts3TermCmp(
  117154. const char *zLhs, int nLhs, /* LHS of comparison */
  117155. const char *zRhs, int nRhs /* RHS of comparison */
  117156. ){
  117157. int nCmp = MIN(nLhs, nRhs);
  117158. int res;
  117159. res = memcmp(zLhs, zRhs, nCmp);
  117160. if( res==0 ) res = nLhs - nRhs;
  117161. return res;
  117162. }
  117163. /*
  117164. ** Query to see if the entry in the %_segments table with blockid iEnd is
  117165. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  117166. ** returning. Otherwise, set *pbRes to 0.
  117167. **
  117168. ** Or, if an error occurs while querying the database, return an SQLite
  117169. ** error code. The final value of *pbRes is undefined in this case.
  117170. **
  117171. ** This is used to test if a segment is an "appendable" segment. If it
  117172. ** is, then a NULL entry has been inserted into the %_segments table
  117173. ** with blockid %_segdir.end_block.
  117174. */
  117175. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  117176. int bRes = 0; /* Result to set *pbRes to */
  117177. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  117178. int rc; /* Return code */
  117179. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  117180. if( rc==SQLITE_OK ){
  117181. sqlite3_bind_int64(pCheck, 1, iEnd);
  117182. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  117183. rc = sqlite3_reset(pCheck);
  117184. }
  117185. *pbRes = bRes;
  117186. return rc;
  117187. }
  117188. /*
  117189. ** This function is called when initializing an incremental-merge operation.
  117190. ** It checks if the existing segment with index value iIdx at absolute level
  117191. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  117192. ** merge-writer object *pWriter is initialized to write to it.
  117193. **
  117194. ** An existing segment can be appended to by an incremental merge if:
  117195. **
  117196. ** * It was initially created as an appendable segment (with all required
  117197. ** space pre-allocated), and
  117198. **
  117199. ** * The first key read from the input (arguments zKey and nKey) is
  117200. ** greater than the largest key currently stored in the potential
  117201. ** output segment.
  117202. */
  117203. static int fts3IncrmergeLoad(
  117204. Fts3Table *p, /* Fts3 table handle */
  117205. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  117206. int iIdx, /* Index of candidate output segment */
  117207. const char *zKey, /* First key to write */
  117208. int nKey, /* Number of bytes in nKey */
  117209. IncrmergeWriter *pWriter /* Populate this object */
  117210. ){
  117211. int rc; /* Return code */
  117212. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  117213. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  117214. if( rc==SQLITE_OK ){
  117215. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  117216. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  117217. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  117218. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  117219. int nRoot = 0; /* Size of aRoot[] in bytes */
  117220. int rc2; /* Return code from sqlite3_reset() */
  117221. int bAppendable = 0; /* Set to true if segment is appendable */
  117222. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  117223. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  117224. sqlite3_bind_int(pSelect, 2, iIdx);
  117225. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  117226. iStart = sqlite3_column_int64(pSelect, 1);
  117227. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  117228. iEnd = sqlite3_column_int64(pSelect, 3);
  117229. nRoot = sqlite3_column_bytes(pSelect, 4);
  117230. aRoot = sqlite3_column_blob(pSelect, 4);
  117231. }else{
  117232. return sqlite3_reset(pSelect);
  117233. }
  117234. /* Check for the zero-length marker in the %_segments table */
  117235. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  117236. /* Check that zKey/nKey is larger than the largest key the candidate */
  117237. if( rc==SQLITE_OK && bAppendable ){
  117238. char *aLeaf = 0;
  117239. int nLeaf = 0;
  117240. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  117241. if( rc==SQLITE_OK ){
  117242. NodeReader reader;
  117243. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  117244. rc==SQLITE_OK && reader.aNode;
  117245. rc = nodeReaderNext(&reader)
  117246. ){
  117247. assert( reader.aNode );
  117248. }
  117249. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  117250. bAppendable = 0;
  117251. }
  117252. nodeReaderRelease(&reader);
  117253. }
  117254. sqlite3_free(aLeaf);
  117255. }
  117256. if( rc==SQLITE_OK && bAppendable ){
  117257. /* It is possible to append to this segment. Set up the IncrmergeWriter
  117258. ** object to do so. */
  117259. int i;
  117260. int nHeight = (int)aRoot[0];
  117261. NodeWriter *pNode;
  117262. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  117263. pWriter->iStart = iStart;
  117264. pWriter->iEnd = iEnd;
  117265. pWriter->iAbsLevel = iAbsLevel;
  117266. pWriter->iIdx = iIdx;
  117267. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  117268. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  117269. }
  117270. pNode = &pWriter->aNodeWriter[nHeight];
  117271. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  117272. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  117273. if( rc==SQLITE_OK ){
  117274. memcpy(pNode->block.a, aRoot, nRoot);
  117275. pNode->block.n = nRoot;
  117276. }
  117277. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  117278. NodeReader reader;
  117279. pNode = &pWriter->aNodeWriter[i];
  117280. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  117281. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  117282. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  117283. if( rc==SQLITE_OK ){
  117284. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  117285. pNode->key.n = reader.term.n;
  117286. if( i>0 ){
  117287. char *aBlock = 0;
  117288. int nBlock = 0;
  117289. pNode = &pWriter->aNodeWriter[i-1];
  117290. pNode->iBlock = reader.iChild;
  117291. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  117292. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  117293. if( rc==SQLITE_OK ){
  117294. memcpy(pNode->block.a, aBlock, nBlock);
  117295. pNode->block.n = nBlock;
  117296. }
  117297. sqlite3_free(aBlock);
  117298. }
  117299. }
  117300. nodeReaderRelease(&reader);
  117301. }
  117302. }
  117303. rc2 = sqlite3_reset(pSelect);
  117304. if( rc==SQLITE_OK ) rc = rc2;
  117305. }
  117306. return rc;
  117307. }
  117308. /*
  117309. ** Determine the largest segment index value that exists within absolute
  117310. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  117311. ** one before returning SQLITE_OK. Or, if there are no segments at all
  117312. ** within level iAbsLevel, set *piIdx to zero.
  117313. **
  117314. ** If an error occurs, return an SQLite error code. The final value of
  117315. ** *piIdx is undefined in this case.
  117316. */
  117317. static int fts3IncrmergeOutputIdx(
  117318. Fts3Table *p, /* FTS Table handle */
  117319. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  117320. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  117321. ){
  117322. int rc;
  117323. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  117324. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  117325. if( rc==SQLITE_OK ){
  117326. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  117327. sqlite3_step(pOutputIdx);
  117328. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  117329. rc = sqlite3_reset(pOutputIdx);
  117330. }
  117331. return rc;
  117332. }
  117333. /*
  117334. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  117335. ** with idx value iIdx.
  117336. **
  117337. ** In the %_segdir table, a segment is defined by the values in three
  117338. ** columns:
  117339. **
  117340. ** start_block
  117341. ** leaves_end_block
  117342. ** end_block
  117343. **
  117344. ** When an appendable segment is allocated, it is estimated that the
  117345. ** maximum number of leaf blocks that may be required is the sum of the
  117346. ** number of leaf blocks consumed by the input segments, plus the number
  117347. ** of input segments, multiplied by two. This value is stored in stack
  117348. ** variable nLeafEst.
  117349. **
  117350. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  117351. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  117352. ** array of leaf nodes starts at the first block allocated. The array
  117353. ** of interior nodes that are parents of the leaf nodes start at block
  117354. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  117355. **
  117356. ** In the actual code below, the value "16" is replaced with the
  117357. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  117358. */
  117359. static int fts3IncrmergeWriter(
  117360. Fts3Table *p, /* Fts3 table handle */
  117361. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  117362. int iIdx, /* Index of new output segment */
  117363. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  117364. IncrmergeWriter *pWriter /* Populate this object */
  117365. ){
  117366. int rc; /* Return Code */
  117367. int i; /* Iterator variable */
  117368. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  117369. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  117370. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  117371. /* Calculate nLeafEst. */
  117372. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  117373. if( rc==SQLITE_OK ){
  117374. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  117375. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  117376. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  117377. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  117378. }
  117379. rc = sqlite3_reset(pLeafEst);
  117380. }
  117381. if( rc!=SQLITE_OK ) return rc;
  117382. /* Calculate the first block to use in the output segment */
  117383. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  117384. if( rc==SQLITE_OK ){
  117385. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  117386. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  117387. pWriter->iEnd = pWriter->iStart - 1;
  117388. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  117389. }
  117390. rc = sqlite3_reset(pFirstBlock);
  117391. }
  117392. if( rc!=SQLITE_OK ) return rc;
  117393. /* Insert the marker in the %_segments table to make sure nobody tries
  117394. ** to steal the space just allocated. This is also used to identify
  117395. ** appendable segments. */
  117396. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  117397. if( rc!=SQLITE_OK ) return rc;
  117398. pWriter->iAbsLevel = iAbsLevel;
  117399. pWriter->nLeafEst = nLeafEst;
  117400. pWriter->iIdx = iIdx;
  117401. /* Set up the array of NodeWriter objects */
  117402. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  117403. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  117404. }
  117405. return SQLITE_OK;
  117406. }
  117407. /*
  117408. ** Remove an entry from the %_segdir table. This involves running the
  117409. ** following two statements:
  117410. **
  117411. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  117412. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  117413. **
  117414. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  117415. ** statement ensures that the remaining segments have contiguously allocated
  117416. ** idx values.
  117417. */
  117418. static int fts3RemoveSegdirEntry(
  117419. Fts3Table *p, /* FTS3 table handle */
  117420. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  117421. int iIdx /* Index of %_segdir entry to delete */
  117422. ){
  117423. int rc; /* Return code */
  117424. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  117425. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  117426. if( rc==SQLITE_OK ){
  117427. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  117428. sqlite3_bind_int(pDelete, 2, iIdx);
  117429. sqlite3_step(pDelete);
  117430. rc = sqlite3_reset(pDelete);
  117431. }
  117432. return rc;
  117433. }
  117434. /*
  117435. ** One or more segments have just been removed from absolute level iAbsLevel.
  117436. ** Update the 'idx' values of the remaining segments in the level so that
  117437. ** the idx values are a contiguous sequence starting from 0.
  117438. */
  117439. static int fts3RepackSegdirLevel(
  117440. Fts3Table *p, /* FTS3 table handle */
  117441. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  117442. ){
  117443. int rc; /* Return code */
  117444. int *aIdx = 0; /* Array of remaining idx values */
  117445. int nIdx = 0; /* Valid entries in aIdx[] */
  117446. int nAlloc = 0; /* Allocated size of aIdx[] */
  117447. int i; /* Iterator variable */
  117448. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  117449. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  117450. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  117451. if( rc==SQLITE_OK ){
  117452. int rc2;
  117453. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  117454. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  117455. if( nIdx>=nAlloc ){
  117456. int *aNew;
  117457. nAlloc += 16;
  117458. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  117459. if( !aNew ){
  117460. rc = SQLITE_NOMEM;
  117461. break;
  117462. }
  117463. aIdx = aNew;
  117464. }
  117465. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  117466. }
  117467. rc2 = sqlite3_reset(pSelect);
  117468. if( rc==SQLITE_OK ) rc = rc2;
  117469. }
  117470. if( rc==SQLITE_OK ){
  117471. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  117472. }
  117473. if( rc==SQLITE_OK ){
  117474. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  117475. }
  117476. assert( p->bIgnoreSavepoint==0 );
  117477. p->bIgnoreSavepoint = 1;
  117478. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  117479. if( aIdx[i]!=i ){
  117480. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  117481. sqlite3_bind_int(pUpdate, 1, i);
  117482. sqlite3_step(pUpdate);
  117483. rc = sqlite3_reset(pUpdate);
  117484. }
  117485. }
  117486. p->bIgnoreSavepoint = 0;
  117487. sqlite3_free(aIdx);
  117488. return rc;
  117489. }
  117490. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  117491. pNode->a[0] = (char)iHeight;
  117492. if( iChild ){
  117493. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  117494. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  117495. }else{
  117496. assert( pNode->nAlloc>=1 );
  117497. pNode->n = 1;
  117498. }
  117499. }
  117500. /*
  117501. ** The first two arguments are a pointer to and the size of a segment b-tree
  117502. ** node. The node may be a leaf or an internal node.
  117503. **
  117504. ** This function creates a new node image in blob object *pNew by copying
  117505. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  117506. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  117507. */
  117508. static int fts3TruncateNode(
  117509. const char *aNode, /* Current node image */
  117510. int nNode, /* Size of aNode in bytes */
  117511. Blob *pNew, /* OUT: Write new node image here */
  117512. const char *zTerm, /* Omit all terms smaller than this */
  117513. int nTerm, /* Size of zTerm in bytes */
  117514. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  117515. ){
  117516. NodeReader reader; /* Reader object */
  117517. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  117518. int rc = SQLITE_OK; /* Return code */
  117519. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  117520. /* Allocate required output space */
  117521. blobGrowBuffer(pNew, nNode, &rc);
  117522. if( rc!=SQLITE_OK ) return rc;
  117523. pNew->n = 0;
  117524. /* Populate new node buffer */
  117525. for(rc = nodeReaderInit(&reader, aNode, nNode);
  117526. rc==SQLITE_OK && reader.aNode;
  117527. rc = nodeReaderNext(&reader)
  117528. ){
  117529. if( pNew->n==0 ){
  117530. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  117531. if( res<0 || (bLeaf==0 && res==0) ) continue;
  117532. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  117533. *piBlock = reader.iChild;
  117534. }
  117535. rc = fts3AppendToNode(
  117536. pNew, &prev, reader.term.a, reader.term.n,
  117537. reader.aDoclist, reader.nDoclist
  117538. );
  117539. if( rc!=SQLITE_OK ) break;
  117540. }
  117541. if( pNew->n==0 ){
  117542. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  117543. *piBlock = reader.iChild;
  117544. }
  117545. assert( pNew->n<=pNew->nAlloc );
  117546. nodeReaderRelease(&reader);
  117547. sqlite3_free(prev.a);
  117548. return rc;
  117549. }
  117550. /*
  117551. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  117552. ** level iAbsLevel. This may involve deleting entries from the %_segments
  117553. ** table, and modifying existing entries in both the %_segments and %_segdir
  117554. ** tables.
  117555. **
  117556. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  117557. ** SQLite error code otherwise.
  117558. */
  117559. static int fts3TruncateSegment(
  117560. Fts3Table *p, /* FTS3 table handle */
  117561. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  117562. int iIdx, /* Index within level of segment to modify */
  117563. const char *zTerm, /* Remove terms smaller than this */
  117564. int nTerm /* Number of bytes in buffer zTerm */
  117565. ){
  117566. int rc = SQLITE_OK; /* Return code */
  117567. Blob root = {0,0,0}; /* New root page image */
  117568. Blob block = {0,0,0}; /* Buffer used for any other block */
  117569. sqlite3_int64 iBlock = 0; /* Block id */
  117570. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  117571. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  117572. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  117573. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  117574. if( rc==SQLITE_OK ){
  117575. int rc2; /* sqlite3_reset() return code */
  117576. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  117577. sqlite3_bind_int(pFetch, 2, iIdx);
  117578. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  117579. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  117580. int nRoot = sqlite3_column_bytes(pFetch, 4);
  117581. iOldStart = sqlite3_column_int64(pFetch, 1);
  117582. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  117583. }
  117584. rc2 = sqlite3_reset(pFetch);
  117585. if( rc==SQLITE_OK ) rc = rc2;
  117586. }
  117587. while( rc==SQLITE_OK && iBlock ){
  117588. char *aBlock = 0;
  117589. int nBlock = 0;
  117590. iNewStart = iBlock;
  117591. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  117592. if( rc==SQLITE_OK ){
  117593. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  117594. }
  117595. if( rc==SQLITE_OK ){
  117596. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  117597. }
  117598. sqlite3_free(aBlock);
  117599. }
  117600. /* Variable iNewStart now contains the first valid leaf node. */
  117601. if( rc==SQLITE_OK && iNewStart ){
  117602. sqlite3_stmt *pDel = 0;
  117603. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  117604. if( rc==SQLITE_OK ){
  117605. sqlite3_bind_int64(pDel, 1, iOldStart);
  117606. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  117607. sqlite3_step(pDel);
  117608. rc = sqlite3_reset(pDel);
  117609. }
  117610. }
  117611. if( rc==SQLITE_OK ){
  117612. sqlite3_stmt *pChomp = 0;
  117613. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  117614. if( rc==SQLITE_OK ){
  117615. sqlite3_bind_int64(pChomp, 1, iNewStart);
  117616. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  117617. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  117618. sqlite3_bind_int(pChomp, 4, iIdx);
  117619. sqlite3_step(pChomp);
  117620. rc = sqlite3_reset(pChomp);
  117621. }
  117622. }
  117623. sqlite3_free(root.a);
  117624. sqlite3_free(block.a);
  117625. return rc;
  117626. }
  117627. /*
  117628. ** This function is called after an incrmental-merge operation has run to
  117629. ** merge (or partially merge) two or more segments from absolute level
  117630. ** iAbsLevel.
  117631. **
  117632. ** Each input segment is either removed from the db completely (if all of
  117633. ** its data was copied to the output segment by the incrmerge operation)
  117634. ** or modified in place so that it no longer contains those entries that
  117635. ** have been duplicated in the output segment.
  117636. */
  117637. static int fts3IncrmergeChomp(
  117638. Fts3Table *p, /* FTS table handle */
  117639. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  117640. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  117641. int *pnRem /* Number of segments not deleted */
  117642. ){
  117643. int i;
  117644. int nRem = 0;
  117645. int rc = SQLITE_OK;
  117646. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  117647. Fts3SegReader *pSeg = 0;
  117648. int j;
  117649. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  117650. ** somewhere in the pCsr->apSegment[] array. */
  117651. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  117652. pSeg = pCsr->apSegment[j];
  117653. if( pSeg->iIdx==i ) break;
  117654. }
  117655. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  117656. if( pSeg->aNode==0 ){
  117657. /* Seg-reader is at EOF. Remove the entire input segment. */
  117658. rc = fts3DeleteSegment(p, pSeg);
  117659. if( rc==SQLITE_OK ){
  117660. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  117661. }
  117662. *pnRem = 0;
  117663. }else{
  117664. /* The incremental merge did not copy all the data from this
  117665. ** segment to the upper level. The segment is modified in place
  117666. ** so that it contains no keys smaller than zTerm/nTerm. */
  117667. const char *zTerm = pSeg->zTerm;
  117668. int nTerm = pSeg->nTerm;
  117669. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  117670. nRem++;
  117671. }
  117672. }
  117673. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  117674. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  117675. }
  117676. *pnRem = nRem;
  117677. return rc;
  117678. }
  117679. /*
  117680. ** Store an incr-merge hint in the database.
  117681. */
  117682. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  117683. sqlite3_stmt *pReplace = 0;
  117684. int rc; /* Return code */
  117685. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  117686. if( rc==SQLITE_OK ){
  117687. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  117688. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  117689. sqlite3_step(pReplace);
  117690. rc = sqlite3_reset(pReplace);
  117691. }
  117692. return rc;
  117693. }
  117694. /*
  117695. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  117696. ** exists, is stored in the rowid==1 row of the %_stat table.
  117697. **
  117698. ** If successful, populate blob *pHint with the value read from the %_stat
  117699. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  117700. ** SQLite error code.
  117701. */
  117702. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  117703. sqlite3_stmt *pSelect = 0;
  117704. int rc;
  117705. pHint->n = 0;
  117706. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  117707. if( rc==SQLITE_OK ){
  117708. int rc2;
  117709. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  117710. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  117711. const char *aHint = sqlite3_column_blob(pSelect, 0);
  117712. int nHint = sqlite3_column_bytes(pSelect, 0);
  117713. if( aHint ){
  117714. blobGrowBuffer(pHint, nHint, &rc);
  117715. if( rc==SQLITE_OK ){
  117716. memcpy(pHint->a, aHint, nHint);
  117717. pHint->n = nHint;
  117718. }
  117719. }
  117720. }
  117721. rc2 = sqlite3_reset(pSelect);
  117722. if( rc==SQLITE_OK ) rc = rc2;
  117723. }
  117724. return rc;
  117725. }
  117726. /*
  117727. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  117728. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  117729. ** consists of two varints, the absolute level number of the input segments
  117730. ** and the number of input segments.
  117731. **
  117732. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  117733. ** set *pRc to an SQLite error code before returning.
  117734. */
  117735. static void fts3IncrmergeHintPush(
  117736. Blob *pHint, /* Hint blob to append to */
  117737. i64 iAbsLevel, /* First varint to store in hint */
  117738. int nInput, /* Second varint to store in hint */
  117739. int *pRc /* IN/OUT: Error code */
  117740. ){
  117741. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  117742. if( *pRc==SQLITE_OK ){
  117743. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  117744. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  117745. }
  117746. }
  117747. /*
  117748. ** Read the last entry (most recently pushed) from the hint blob *pHint
  117749. ** and then remove the entry. Write the two values read to *piAbsLevel and
  117750. ** *pnInput before returning.
  117751. **
  117752. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  117753. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  117754. */
  117755. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  117756. const int nHint = pHint->n;
  117757. int i;
  117758. i = pHint->n-2;
  117759. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  117760. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  117761. pHint->n = i;
  117762. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  117763. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  117764. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  117765. return SQLITE_OK;
  117766. }
  117767. /*
  117768. ** Attempt an incremental merge that writes nMerge leaf blocks.
  117769. **
  117770. ** Incremental merges happen nMin segments at a time. The two
  117771. ** segments to be merged are the nMin oldest segments (the ones with
  117772. ** the smallest indexes) in the highest level that contains at least
  117773. ** nMin segments. Multiple merges might occur in an attempt to write the
  117774. ** quota of nMerge leaf blocks.
  117775. */
  117776. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  117777. int rc; /* Return code */
  117778. int nRem = nMerge; /* Number of leaf pages yet to be written */
  117779. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  117780. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  117781. IncrmergeWriter *pWriter; /* Writer object */
  117782. int nSeg = 0; /* Number of input segments */
  117783. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  117784. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  117785. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  117786. /* Allocate space for the cursor, filter and writer objects */
  117787. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  117788. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  117789. if( !pWriter ) return SQLITE_NOMEM;
  117790. pFilter = (Fts3SegFilter *)&pWriter[1];
  117791. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  117792. rc = fts3IncrmergeHintLoad(p, &hint);
  117793. while( rc==SQLITE_OK && nRem>0 ){
  117794. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  117795. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  117796. int bUseHint = 0; /* True if attempting to append */
  117797. /* Search the %_segdir table for the absolute level with the smallest
  117798. ** relative level number that contains at least nMin segments, if any.
  117799. ** If one is found, set iAbsLevel to the absolute level number and
  117800. ** nSeg to nMin. If no level with at least nMin segments can be found,
  117801. ** set nSeg to -1.
  117802. */
  117803. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  117804. sqlite3_bind_int(pFindLevel, 1, nMin);
  117805. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  117806. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  117807. nSeg = nMin;
  117808. }else{
  117809. nSeg = -1;
  117810. }
  117811. rc = sqlite3_reset(pFindLevel);
  117812. /* If the hint read from the %_stat table is not empty, check if the
  117813. ** last entry in it specifies a relative level smaller than or equal
  117814. ** to the level identified by the block above (if any). If so, this
  117815. ** iteration of the loop will work on merging at the hinted level.
  117816. */
  117817. if( rc==SQLITE_OK && hint.n ){
  117818. int nHint = hint.n;
  117819. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  117820. int nHintSeg = 0; /* Hint number of segments */
  117821. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  117822. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  117823. iAbsLevel = iHintAbsLevel;
  117824. nSeg = nHintSeg;
  117825. bUseHint = 1;
  117826. bDirtyHint = 1;
  117827. }else{
  117828. /* This undoes the effect of the HintPop() above - so that no entry
  117829. ** is removed from the hint blob. */
  117830. hint.n = nHint;
  117831. }
  117832. }
  117833. /* If nSeg is less that zero, then there is no level with at least
  117834. ** nMin segments and no hint in the %_stat table. No work to do.
  117835. ** Exit early in this case. */
  117836. if( nSeg<0 ) break;
  117837. /* Open a cursor to iterate through the contents of the oldest nSeg
  117838. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  117839. ** the 'hint' parameters, it is possible that there are less than nSeg
  117840. ** segments available in level iAbsLevel. In this case, no work is
  117841. ** done on iAbsLevel - fall through to the next iteration of the loop
  117842. ** to start work on some other level. */
  117843. memset(pWriter, 0, nAlloc);
  117844. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  117845. if( rc==SQLITE_OK ){
  117846. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  117847. }
  117848. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  117849. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  117850. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  117851. ){
  117852. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  117853. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  117854. if( rc==SQLITE_OK ){
  117855. if( bUseHint && iIdx>0 ){
  117856. const char *zKey = pCsr->zTerm;
  117857. int nKey = pCsr->nTerm;
  117858. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  117859. }else{
  117860. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  117861. }
  117862. }
  117863. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  117864. fts3LogMerge(nSeg, iAbsLevel);
  117865. do {
  117866. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  117867. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  117868. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  117869. }while( rc==SQLITE_ROW );
  117870. /* Update or delete the input segments */
  117871. if( rc==SQLITE_OK ){
  117872. nRem -= (1 + pWriter->nWork);
  117873. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  117874. if( nSeg!=0 ){
  117875. bDirtyHint = 1;
  117876. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  117877. }
  117878. }
  117879. }
  117880. fts3IncrmergeRelease(p, pWriter, &rc);
  117881. }
  117882. sqlite3Fts3SegReaderFinish(pCsr);
  117883. }
  117884. /* Write the hint values into the %_stat table for the next incr-merger */
  117885. if( bDirtyHint && rc==SQLITE_OK ){
  117886. rc = fts3IncrmergeHintStore(p, &hint);
  117887. }
  117888. sqlite3_free(pWriter);
  117889. sqlite3_free(hint.a);
  117890. return rc;
  117891. }
  117892. /*
  117893. ** Convert the text beginning at *pz into an integer and return
  117894. ** its value. Advance *pz to point to the first character past
  117895. ** the integer.
  117896. */
  117897. static int fts3Getint(const char **pz){
  117898. const char *z = *pz;
  117899. int i = 0;
  117900. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  117901. *pz = z;
  117902. return i;
  117903. }
  117904. /*
  117905. ** Process statements of the form:
  117906. **
  117907. ** INSERT INTO table(table) VALUES('merge=A,B');
  117908. **
  117909. ** A and B are integers that decode to be the number of leaf pages
  117910. ** written for the merge, and the minimum number of segments on a level
  117911. ** before it will be selected for a merge, respectively.
  117912. */
  117913. static int fts3DoIncrmerge(
  117914. Fts3Table *p, /* FTS3 table handle */
  117915. const char *zParam /* Nul-terminated string containing "A,B" */
  117916. ){
  117917. int rc;
  117918. int nMin = (FTS3_MERGE_COUNT / 2);
  117919. int nMerge = 0;
  117920. const char *z = zParam;
  117921. /* Read the first integer value */
  117922. nMerge = fts3Getint(&z);
  117923. /* If the first integer value is followed by a ',', read the second
  117924. ** integer value. */
  117925. if( z[0]==',' && z[1]!='\0' ){
  117926. z++;
  117927. nMin = fts3Getint(&z);
  117928. }
  117929. if( z[0]!='\0' || nMin<2 ){
  117930. rc = SQLITE_ERROR;
  117931. }else{
  117932. rc = SQLITE_OK;
  117933. if( !p->bHasStat ){
  117934. assert( p->bFts4==0 );
  117935. sqlite3Fts3CreateStatTable(&rc, p);
  117936. }
  117937. if( rc==SQLITE_OK ){
  117938. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  117939. }
  117940. sqlite3Fts3SegmentsClose(p);
  117941. }
  117942. return rc;
  117943. }
  117944. /*
  117945. ** Process statements of the form:
  117946. **
  117947. ** INSERT INTO table(table) VALUES('automerge=X');
  117948. **
  117949. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  117950. ** turn it on. The setting is persistent.
  117951. */
  117952. static int fts3DoAutoincrmerge(
  117953. Fts3Table *p, /* FTS3 table handle */
  117954. const char *zParam /* Nul-terminated string containing boolean */
  117955. ){
  117956. int rc = SQLITE_OK;
  117957. sqlite3_stmt *pStmt = 0;
  117958. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  117959. if( !p->bHasStat ){
  117960. assert( p->bFts4==0 );
  117961. sqlite3Fts3CreateStatTable(&rc, p);
  117962. if( rc ) return rc;
  117963. }
  117964. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  117965. if( rc ) return rc;
  117966. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  117967. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  117968. sqlite3_step(pStmt);
  117969. rc = sqlite3_reset(pStmt);
  117970. return rc;
  117971. }
  117972. /*
  117973. ** Return a 64-bit checksum for the FTS index entry specified by the
  117974. ** arguments to this function.
  117975. */
  117976. static u64 fts3ChecksumEntry(
  117977. const char *zTerm, /* Pointer to buffer containing term */
  117978. int nTerm, /* Size of zTerm in bytes */
  117979. int iLangid, /* Language id for current row */
  117980. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  117981. i64 iDocid, /* Docid for current row. */
  117982. int iCol, /* Column number */
  117983. int iPos /* Position */
  117984. ){
  117985. int i;
  117986. u64 ret = (u64)iDocid;
  117987. ret += (ret<<3) + iLangid;
  117988. ret += (ret<<3) + iIndex;
  117989. ret += (ret<<3) + iCol;
  117990. ret += (ret<<3) + iPos;
  117991. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  117992. return ret;
  117993. }
  117994. /*
  117995. ** Return a checksum of all entries in the FTS index that correspond to
  117996. ** language id iLangid. The checksum is calculated by XORing the checksums
  117997. ** of each individual entry (see fts3ChecksumEntry()) together.
  117998. **
  117999. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  118000. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  118001. ** return value is undefined in this case.
  118002. */
  118003. static u64 fts3ChecksumIndex(
  118004. Fts3Table *p, /* FTS3 table handle */
  118005. int iLangid, /* Language id to return cksum for */
  118006. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  118007. int *pRc /* OUT: Return code */
  118008. ){
  118009. Fts3SegFilter filter;
  118010. Fts3MultiSegReader csr;
  118011. int rc;
  118012. u64 cksum = 0;
  118013. assert( *pRc==SQLITE_OK );
  118014. memset(&filter, 0, sizeof(filter));
  118015. memset(&csr, 0, sizeof(csr));
  118016. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  118017. filter.flags |= FTS3_SEGMENT_SCAN;
  118018. rc = sqlite3Fts3SegReaderCursor(
  118019. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  118020. );
  118021. if( rc==SQLITE_OK ){
  118022. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  118023. }
  118024. if( rc==SQLITE_OK ){
  118025. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  118026. char *pCsr = csr.aDoclist;
  118027. char *pEnd = &pCsr[csr.nDoclist];
  118028. i64 iDocid = 0;
  118029. i64 iCol = 0;
  118030. i64 iPos = 0;
  118031. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  118032. while( pCsr<pEnd ){
  118033. i64 iVal = 0;
  118034. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  118035. if( pCsr<pEnd ){
  118036. if( iVal==0 || iVal==1 ){
  118037. iCol = 0;
  118038. iPos = 0;
  118039. if( iVal ){
  118040. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  118041. }else{
  118042. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  118043. iDocid += iVal;
  118044. }
  118045. }else{
  118046. iPos += (iVal - 2);
  118047. cksum = cksum ^ fts3ChecksumEntry(
  118048. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  118049. (int)iCol, (int)iPos
  118050. );
  118051. }
  118052. }
  118053. }
  118054. }
  118055. }
  118056. sqlite3Fts3SegReaderFinish(&csr);
  118057. *pRc = rc;
  118058. return cksum;
  118059. }
  118060. /*
  118061. ** Check if the contents of the FTS index match the current contents of the
  118062. ** content table. If no error occurs and the contents do match, set *pbOk
  118063. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  118064. ** to false before returning.
  118065. **
  118066. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  118067. ** code. The final value of *pbOk is undefined in this case.
  118068. */
  118069. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  118070. int rc = SQLITE_OK; /* Return code */
  118071. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  118072. u64 cksum2 = 0; /* Checksum based on %_content contents */
  118073. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  118074. /* This block calculates the checksum according to the FTS index. */
  118075. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  118076. if( rc==SQLITE_OK ){
  118077. int rc2;
  118078. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  118079. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  118080. int iLangid = sqlite3_column_int(pAllLangid, 0);
  118081. int i;
  118082. for(i=0; i<p->nIndex; i++){
  118083. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  118084. }
  118085. }
  118086. rc2 = sqlite3_reset(pAllLangid);
  118087. if( rc==SQLITE_OK ) rc = rc2;
  118088. }
  118089. /* This block calculates the checksum according to the %_content table */
  118090. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  118091. if( rc==SQLITE_OK ){
  118092. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  118093. sqlite3_stmt *pStmt = 0;
  118094. char *zSql;
  118095. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  118096. if( !zSql ){
  118097. rc = SQLITE_NOMEM;
  118098. }else{
  118099. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  118100. sqlite3_free(zSql);
  118101. }
  118102. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  118103. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  118104. int iLang = langidFromSelect(p, pStmt);
  118105. int iCol;
  118106. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  118107. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  118108. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  118109. sqlite3_tokenizer_cursor *pT = 0;
  118110. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  118111. while( rc==SQLITE_OK ){
  118112. char const *zToken; /* Buffer containing token */
  118113. int nToken = 0; /* Number of bytes in token */
  118114. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  118115. int iPos = 0; /* Position of token in zText */
  118116. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  118117. if( rc==SQLITE_OK ){
  118118. int i;
  118119. cksum2 = cksum2 ^ fts3ChecksumEntry(
  118120. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  118121. );
  118122. for(i=1; i<p->nIndex; i++){
  118123. if( p->aIndex[i].nPrefix<=nToken ){
  118124. cksum2 = cksum2 ^ fts3ChecksumEntry(
  118125. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  118126. );
  118127. }
  118128. }
  118129. }
  118130. }
  118131. if( pT ) pModule->xClose(pT);
  118132. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  118133. }
  118134. }
  118135. sqlite3_finalize(pStmt);
  118136. }
  118137. *pbOk = (cksum1==cksum2);
  118138. return rc;
  118139. }
  118140. /*
  118141. ** Run the integrity-check. If no error occurs and the current contents of
  118142. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  118143. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  118144. **
  118145. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  118146. ** error code.
  118147. **
  118148. ** The integrity-check works as follows. For each token and indexed token
  118149. ** prefix in the document set, a 64-bit checksum is calculated (by code
  118150. ** in fts3ChecksumEntry()) based on the following:
  118151. **
  118152. ** + The index number (0 for the main index, 1 for the first prefix
  118153. ** index etc.),
  118154. ** + The token (or token prefix) text itself,
  118155. ** + The language-id of the row it appears in,
  118156. ** + The docid of the row it appears in,
  118157. ** + The column it appears in, and
  118158. ** + The tokens position within that column.
  118159. **
  118160. ** The checksums for all entries in the index are XORed together to create
  118161. ** a single checksum for the entire index.
  118162. **
  118163. ** The integrity-check code calculates the same checksum in two ways:
  118164. **
  118165. ** 1. By scanning the contents of the FTS index, and
  118166. ** 2. By scanning and tokenizing the content table.
  118167. **
  118168. ** If the two checksums are identical, the integrity-check is deemed to have
  118169. ** passed.
  118170. */
  118171. static int fts3DoIntegrityCheck(
  118172. Fts3Table *p /* FTS3 table handle */
  118173. ){
  118174. int rc;
  118175. int bOk = 0;
  118176. rc = fts3IntegrityCheck(p, &bOk);
  118177. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  118178. return rc;
  118179. }
  118180. /*
  118181. ** Handle a 'special' INSERT of the form:
  118182. **
  118183. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  118184. **
  118185. ** Argument pVal contains the result of <expr>. Currently the only
  118186. ** meaningful value to insert is the text 'optimize'.
  118187. */
  118188. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  118189. int rc; /* Return Code */
  118190. const char *zVal = (const char *)sqlite3_value_text(pVal);
  118191. int nVal = sqlite3_value_bytes(pVal);
  118192. if( !zVal ){
  118193. return SQLITE_NOMEM;
  118194. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  118195. rc = fts3DoOptimize(p, 0);
  118196. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  118197. rc = fts3DoRebuild(p);
  118198. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  118199. rc = fts3DoIntegrityCheck(p);
  118200. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  118201. rc = fts3DoIncrmerge(p, &zVal[6]);
  118202. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  118203. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  118204. #ifdef SQLITE_TEST
  118205. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  118206. p->nNodeSize = atoi(&zVal[9]);
  118207. rc = SQLITE_OK;
  118208. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  118209. p->nMaxPendingData = atoi(&zVal[11]);
  118210. rc = SQLITE_OK;
  118211. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  118212. p->bNoIncrDoclist = atoi(&zVal[21]);
  118213. rc = SQLITE_OK;
  118214. #endif
  118215. }else{
  118216. rc = SQLITE_ERROR;
  118217. }
  118218. return rc;
  118219. }
  118220. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  118221. /*
  118222. ** Delete all cached deferred doclists. Deferred doclists are cached
  118223. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  118224. */
  118225. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  118226. Fts3DeferredToken *pDef;
  118227. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  118228. fts3PendingListDelete(pDef->pList);
  118229. pDef->pList = 0;
  118230. }
  118231. }
  118232. /*
  118233. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  118234. ** this list using sqlite3Fts3DeferToken().
  118235. */
  118236. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  118237. Fts3DeferredToken *pDef;
  118238. Fts3DeferredToken *pNext;
  118239. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  118240. pNext = pDef->pNext;
  118241. fts3PendingListDelete(pDef->pList);
  118242. sqlite3_free(pDef);
  118243. }
  118244. pCsr->pDeferred = 0;
  118245. }
  118246. /*
  118247. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  118248. ** based on the row that pCsr currently points to.
  118249. **
  118250. ** A deferred-doclist is like any other doclist with position information
  118251. ** included, except that it only contains entries for a single row of the
  118252. ** table, not for all rows.
  118253. */
  118254. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  118255. int rc = SQLITE_OK; /* Return code */
  118256. if( pCsr->pDeferred ){
  118257. int i; /* Used to iterate through table columns */
  118258. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  118259. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  118260. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  118261. sqlite3_tokenizer *pT = p->pTokenizer;
  118262. sqlite3_tokenizer_module const *pModule = pT->pModule;
  118263. assert( pCsr->isRequireSeek==0 );
  118264. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  118265. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  118266. if( p->abNotindexed[i]==0 ){
  118267. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  118268. sqlite3_tokenizer_cursor *pTC = 0;
  118269. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  118270. while( rc==SQLITE_OK ){
  118271. char const *zToken; /* Buffer containing token */
  118272. int nToken = 0; /* Number of bytes in token */
  118273. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  118274. int iPos = 0; /* Position of token in zText */
  118275. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  118276. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  118277. Fts3PhraseToken *pPT = pDef->pToken;
  118278. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  118279. && (pPT->bFirst==0 || iPos==0)
  118280. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  118281. && (0==memcmp(zToken, pPT->z, pPT->n))
  118282. ){
  118283. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  118284. }
  118285. }
  118286. }
  118287. if( pTC ) pModule->xClose(pTC);
  118288. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  118289. }
  118290. }
  118291. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  118292. if( pDef->pList ){
  118293. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  118294. }
  118295. }
  118296. }
  118297. return rc;
  118298. }
  118299. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  118300. Fts3DeferredToken *p,
  118301. char **ppData,
  118302. int *pnData
  118303. ){
  118304. char *pRet;
  118305. int nSkip;
  118306. sqlite3_int64 dummy;
  118307. *ppData = 0;
  118308. *pnData = 0;
  118309. if( p->pList==0 ){
  118310. return SQLITE_OK;
  118311. }
  118312. pRet = (char *)sqlite3_malloc(p->pList->nData);
  118313. if( !pRet ) return SQLITE_NOMEM;
  118314. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  118315. *pnData = p->pList->nData - nSkip;
  118316. *ppData = pRet;
  118317. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  118318. return SQLITE_OK;
  118319. }
  118320. /*
  118321. ** Add an entry for token pToken to the pCsr->pDeferred list.
  118322. */
  118323. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  118324. Fts3Cursor *pCsr, /* Fts3 table cursor */
  118325. Fts3PhraseToken *pToken, /* Token to defer */
  118326. int iCol /* Column that token must appear in (or -1) */
  118327. ){
  118328. Fts3DeferredToken *pDeferred;
  118329. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  118330. if( !pDeferred ){
  118331. return SQLITE_NOMEM;
  118332. }
  118333. memset(pDeferred, 0, sizeof(*pDeferred));
  118334. pDeferred->pToken = pToken;
  118335. pDeferred->pNext = pCsr->pDeferred;
  118336. pDeferred->iCol = iCol;
  118337. pCsr->pDeferred = pDeferred;
  118338. assert( pToken->pDeferred==0 );
  118339. pToken->pDeferred = pDeferred;
  118340. return SQLITE_OK;
  118341. }
  118342. #endif
  118343. /*
  118344. ** SQLite value pRowid contains the rowid of a row that may or may not be
  118345. ** present in the FTS3 table. If it is, delete it and adjust the contents
  118346. ** of subsiduary data structures accordingly.
  118347. */
  118348. static int fts3DeleteByRowid(
  118349. Fts3Table *p,
  118350. sqlite3_value *pRowid,
  118351. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  118352. u32 *aSzDel
  118353. ){
  118354. int rc = SQLITE_OK; /* Return code */
  118355. int bFound = 0; /* True if *pRowid really is in the table */
  118356. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  118357. if( bFound && rc==SQLITE_OK ){
  118358. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  118359. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  118360. if( rc==SQLITE_OK ){
  118361. if( isEmpty ){
  118362. /* Deleting this row means the whole table is empty. In this case
  118363. ** delete the contents of all three tables and throw away any
  118364. ** data in the pendingTerms hash table. */
  118365. rc = fts3DeleteAll(p, 1);
  118366. *pnChng = 0;
  118367. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  118368. }else{
  118369. *pnChng = *pnChng - 1;
  118370. if( p->zContentTbl==0 ){
  118371. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  118372. }
  118373. if( p->bHasDocsize ){
  118374. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  118375. }
  118376. }
  118377. }
  118378. }
  118379. return rc;
  118380. }
  118381. /*
  118382. ** This function does the work for the xUpdate method of FTS3 virtual
  118383. ** tables. The schema of the virtual table being:
  118384. **
  118385. ** CREATE TABLE <table name>(
  118386. ** <user columns>,
  118387. ** <table name> HIDDEN,
  118388. ** docid HIDDEN,
  118389. ** <langid> HIDDEN
  118390. ** );
  118391. **
  118392. **
  118393. */
  118394. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  118395. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  118396. int nArg, /* Size of argument array */
  118397. sqlite3_value **apVal, /* Array of arguments */
  118398. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  118399. ){
  118400. Fts3Table *p = (Fts3Table *)pVtab;
  118401. int rc = SQLITE_OK; /* Return Code */
  118402. int isRemove = 0; /* True for an UPDATE or DELETE */
  118403. u32 *aSzIns = 0; /* Sizes of inserted documents */
  118404. u32 *aSzDel = 0; /* Sizes of deleted documents */
  118405. int nChng = 0; /* Net change in number of documents */
  118406. int bInsertDone = 0;
  118407. assert( p->pSegments==0 );
  118408. assert(
  118409. nArg==1 /* DELETE operations */
  118410. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  118411. );
  118412. /* Check for a "special" INSERT operation. One of the form:
  118413. **
  118414. ** INSERT INTO xyz(xyz) VALUES('command');
  118415. */
  118416. if( nArg>1
  118417. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  118418. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  118419. ){
  118420. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  118421. goto update_out;
  118422. }
  118423. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  118424. rc = SQLITE_CONSTRAINT;
  118425. goto update_out;
  118426. }
  118427. /* Allocate space to hold the change in document sizes */
  118428. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  118429. if( aSzDel==0 ){
  118430. rc = SQLITE_NOMEM;
  118431. goto update_out;
  118432. }
  118433. aSzIns = &aSzDel[p->nColumn+1];
  118434. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  118435. rc = fts3Writelock(p);
  118436. if( rc!=SQLITE_OK ) goto update_out;
  118437. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  118438. ** value, then this operation requires constraint handling.
  118439. **
  118440. ** If the on-conflict mode is REPLACE, this means that the existing row
  118441. ** should be deleted from the database before inserting the new row. Or,
  118442. ** if the on-conflict mode is other than REPLACE, then this method must
  118443. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  118444. ** modify the database file.
  118445. */
  118446. if( nArg>1 && p->zContentTbl==0 ){
  118447. /* Find the value object that holds the new rowid value. */
  118448. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  118449. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  118450. pNewRowid = apVal[1];
  118451. }
  118452. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  118453. sqlite3_value_type(apVal[0])==SQLITE_NULL
  118454. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  118455. )){
  118456. /* The new rowid is not NULL (in this case the rowid will be
  118457. ** automatically assigned and there is no chance of a conflict), and
  118458. ** the statement is either an INSERT or an UPDATE that modifies the
  118459. ** rowid column. So if the conflict mode is REPLACE, then delete any
  118460. ** existing row with rowid=pNewRowid.
  118461. **
  118462. ** Or, if the conflict mode is not REPLACE, insert the new record into
  118463. ** the %_content table. If we hit the duplicate rowid constraint (or any
  118464. ** other error) while doing so, return immediately.
  118465. **
  118466. ** This branch may also run if pNewRowid contains a value that cannot
  118467. ** be losslessly converted to an integer. In this case, the eventual
  118468. ** call to fts3InsertData() (either just below or further on in this
  118469. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  118470. ** invoked, it will delete zero rows (since no row will have
  118471. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  118472. */
  118473. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  118474. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  118475. }else{
  118476. rc = fts3InsertData(p, apVal, pRowid);
  118477. bInsertDone = 1;
  118478. }
  118479. }
  118480. }
  118481. if( rc!=SQLITE_OK ){
  118482. goto update_out;
  118483. }
  118484. /* If this is a DELETE or UPDATE operation, remove the old record. */
  118485. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  118486. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  118487. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  118488. isRemove = 1;
  118489. }
  118490. /* If this is an INSERT or UPDATE operation, insert the new record. */
  118491. if( nArg>1 && rc==SQLITE_OK ){
  118492. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  118493. if( bInsertDone==0 ){
  118494. rc = fts3InsertData(p, apVal, pRowid);
  118495. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  118496. rc = FTS_CORRUPT_VTAB;
  118497. }
  118498. }
  118499. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  118500. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  118501. }
  118502. if( rc==SQLITE_OK ){
  118503. assert( p->iPrevDocid==*pRowid );
  118504. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  118505. }
  118506. if( p->bHasDocsize ){
  118507. fts3InsertDocsize(&rc, p, aSzIns);
  118508. }
  118509. nChng++;
  118510. }
  118511. if( p->bFts4 ){
  118512. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  118513. }
  118514. update_out:
  118515. sqlite3_free(aSzDel);
  118516. sqlite3Fts3SegmentsClose(p);
  118517. return rc;
  118518. }
  118519. /*
  118520. ** Flush any data in the pending-terms hash table to disk. If successful,
  118521. ** merge all segments in the database (including the new segment, if
  118522. ** there was any data to flush) into a single segment.
  118523. */
  118524. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  118525. int rc;
  118526. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  118527. if( rc==SQLITE_OK ){
  118528. rc = fts3DoOptimize(p, 1);
  118529. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  118530. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  118531. if( rc2!=SQLITE_OK ) rc = rc2;
  118532. }else{
  118533. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  118534. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  118535. }
  118536. }
  118537. sqlite3Fts3SegmentsClose(p);
  118538. return rc;
  118539. }
  118540. #endif
  118541. /************** End of fts3_write.c ******************************************/
  118542. /************** Begin file fts3_snippet.c ************************************/
  118543. /*
  118544. ** 2009 Oct 23
  118545. **
  118546. ** The author disclaims copyright to this source code. In place of
  118547. ** a legal notice, here is a blessing:
  118548. **
  118549. ** May you do good and not evil.
  118550. ** May you find forgiveness for yourself and forgive others.
  118551. ** May you share freely, never taking more than you give.
  118552. **
  118553. ******************************************************************************
  118554. */
  118555. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  118556. /* #include <string.h> */
  118557. /* #include <assert.h> */
  118558. /*
  118559. ** Characters that may appear in the second argument to matchinfo().
  118560. */
  118561. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  118562. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  118563. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  118564. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  118565. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  118566. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  118567. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  118568. /*
  118569. ** The default value for the second argument to matchinfo().
  118570. */
  118571. #define FTS3_MATCHINFO_DEFAULT "pcx"
  118572. /*
  118573. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  118574. ** Fts3Expr.aDoclist[]/nDoclist.
  118575. */
  118576. typedef struct LoadDoclistCtx LoadDoclistCtx;
  118577. struct LoadDoclistCtx {
  118578. Fts3Cursor *pCsr; /* FTS3 Cursor */
  118579. int nPhrase; /* Number of phrases seen so far */
  118580. int nToken; /* Number of tokens seen so far */
  118581. };
  118582. /*
  118583. ** The following types are used as part of the implementation of the
  118584. ** fts3BestSnippet() routine.
  118585. */
  118586. typedef struct SnippetIter SnippetIter;
  118587. typedef struct SnippetPhrase SnippetPhrase;
  118588. typedef struct SnippetFragment SnippetFragment;
  118589. struct SnippetIter {
  118590. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  118591. int iCol; /* Extract snippet from this column */
  118592. int nSnippet; /* Requested snippet length (in tokens) */
  118593. int nPhrase; /* Number of phrases in query */
  118594. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  118595. int iCurrent; /* First token of current snippet */
  118596. };
  118597. struct SnippetPhrase {
  118598. int nToken; /* Number of tokens in phrase */
  118599. char *pList; /* Pointer to start of phrase position list */
  118600. int iHead; /* Next value in position list */
  118601. char *pHead; /* Position list data following iHead */
  118602. int iTail; /* Next value in trailing position list */
  118603. char *pTail; /* Position list data following iTail */
  118604. };
  118605. struct SnippetFragment {
  118606. int iCol; /* Column snippet is extracted from */
  118607. int iPos; /* Index of first token in snippet */
  118608. u64 covered; /* Mask of query phrases covered */
  118609. u64 hlmask; /* Mask of snippet terms to highlight */
  118610. };
  118611. /*
  118612. ** This type is used as an fts3ExprIterate() context object while
  118613. ** accumulating the data returned by the matchinfo() function.
  118614. */
  118615. typedef struct MatchInfo MatchInfo;
  118616. struct MatchInfo {
  118617. Fts3Cursor *pCursor; /* FTS3 Cursor */
  118618. int nCol; /* Number of columns in table */
  118619. int nPhrase; /* Number of matchable phrases in query */
  118620. sqlite3_int64 nDoc; /* Number of docs in database */
  118621. u32 *aMatchinfo; /* Pre-allocated buffer */
  118622. };
  118623. /*
  118624. ** The snippet() and offsets() functions both return text values. An instance
  118625. ** of the following structure is used to accumulate those values while the
  118626. ** functions are running. See fts3StringAppend() for details.
  118627. */
  118628. typedef struct StrBuffer StrBuffer;
  118629. struct StrBuffer {
  118630. char *z; /* Pointer to buffer containing string */
  118631. int n; /* Length of z in bytes (excl. nul-term) */
  118632. int nAlloc; /* Allocated size of buffer z in bytes */
  118633. };
  118634. /*
  118635. ** This function is used to help iterate through a position-list. A position
  118636. ** list is a list of unique integers, sorted from smallest to largest. Each
  118637. ** element of the list is represented by an FTS3 varint that takes the value
  118638. ** of the difference between the current element and the previous one plus
  118639. ** two. For example, to store the position-list:
  118640. **
  118641. ** 4 9 113
  118642. **
  118643. ** the three varints:
  118644. **
  118645. ** 6 7 106
  118646. **
  118647. ** are encoded.
  118648. **
  118649. ** When this function is called, *pp points to the start of an element of
  118650. ** the list. *piPos contains the value of the previous entry in the list.
  118651. ** After it returns, *piPos contains the value of the next element of the
  118652. ** list and *pp is advanced to the following varint.
  118653. */
  118654. static void fts3GetDeltaPosition(char **pp, int *piPos){
  118655. int iVal;
  118656. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  118657. *piPos += (iVal-2);
  118658. }
  118659. /*
  118660. ** Helper function for fts3ExprIterate() (see below).
  118661. */
  118662. static int fts3ExprIterate2(
  118663. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  118664. int *piPhrase, /* Pointer to phrase counter */
  118665. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  118666. void *pCtx /* Second argument to pass to callback */
  118667. ){
  118668. int rc; /* Return code */
  118669. int eType = pExpr->eType; /* Type of expression node pExpr */
  118670. if( eType!=FTSQUERY_PHRASE ){
  118671. assert( pExpr->pLeft && pExpr->pRight );
  118672. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  118673. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  118674. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  118675. }
  118676. }else{
  118677. rc = x(pExpr, *piPhrase, pCtx);
  118678. (*piPhrase)++;
  118679. }
  118680. return rc;
  118681. }
  118682. /*
  118683. ** Iterate through all phrase nodes in an FTS3 query, except those that
  118684. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  118685. ** For each phrase node found, the supplied callback function is invoked.
  118686. **
  118687. ** If the callback function returns anything other than SQLITE_OK,
  118688. ** the iteration is abandoned and the error code returned immediately.
  118689. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  118690. ** all eligible phrase nodes.
  118691. */
  118692. static int fts3ExprIterate(
  118693. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  118694. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  118695. void *pCtx /* Second argument to pass to callback */
  118696. ){
  118697. int iPhrase = 0; /* Variable used as the phrase counter */
  118698. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  118699. }
  118700. /*
  118701. ** This is an fts3ExprIterate() callback used while loading the doclists
  118702. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  118703. ** fts3ExprLoadDoclists().
  118704. */
  118705. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118706. int rc = SQLITE_OK;
  118707. Fts3Phrase *pPhrase = pExpr->pPhrase;
  118708. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  118709. UNUSED_PARAMETER(iPhrase);
  118710. p->nPhrase++;
  118711. p->nToken += pPhrase->nToken;
  118712. return rc;
  118713. }
  118714. /*
  118715. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  118716. ** pCsr.
  118717. **
  118718. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  118719. ** phrases in the expression (all phrases except those directly or
  118720. ** indirectly descended from the right-hand-side of a NOT operator). If
  118721. ** pnToken is not NULL, then it is set to the number of tokens in all
  118722. ** matchable phrases of the expression.
  118723. */
  118724. static int fts3ExprLoadDoclists(
  118725. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  118726. int *pnPhrase, /* OUT: Number of phrases in query */
  118727. int *pnToken /* OUT: Number of tokens in query */
  118728. ){
  118729. int rc; /* Return Code */
  118730. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  118731. sCtx.pCsr = pCsr;
  118732. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  118733. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  118734. if( pnToken ) *pnToken = sCtx.nToken;
  118735. return rc;
  118736. }
  118737. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118738. (*(int *)ctx)++;
  118739. UNUSED_PARAMETER(pExpr);
  118740. UNUSED_PARAMETER(iPhrase);
  118741. return SQLITE_OK;
  118742. }
  118743. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  118744. int nPhrase = 0;
  118745. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  118746. return nPhrase;
  118747. }
  118748. /*
  118749. ** Advance the position list iterator specified by the first two
  118750. ** arguments so that it points to the first element with a value greater
  118751. ** than or equal to parameter iNext.
  118752. */
  118753. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  118754. char *pIter = *ppIter;
  118755. if( pIter ){
  118756. int iIter = *piIter;
  118757. while( iIter<iNext ){
  118758. if( 0==(*pIter & 0xFE) ){
  118759. iIter = -1;
  118760. pIter = 0;
  118761. break;
  118762. }
  118763. fts3GetDeltaPosition(&pIter, &iIter);
  118764. }
  118765. *piIter = iIter;
  118766. *ppIter = pIter;
  118767. }
  118768. }
  118769. /*
  118770. ** Advance the snippet iterator to the next candidate snippet.
  118771. */
  118772. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  118773. int i; /* Loop counter */
  118774. if( pIter->iCurrent<0 ){
  118775. /* The SnippetIter object has just been initialized. The first snippet
  118776. ** candidate always starts at offset 0 (even if this candidate has a
  118777. ** score of 0.0).
  118778. */
  118779. pIter->iCurrent = 0;
  118780. /* Advance the 'head' iterator of each phrase to the first offset that
  118781. ** is greater than or equal to (iNext+nSnippet).
  118782. */
  118783. for(i=0; i<pIter->nPhrase; i++){
  118784. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118785. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  118786. }
  118787. }else{
  118788. int iStart;
  118789. int iEnd = 0x7FFFFFFF;
  118790. for(i=0; i<pIter->nPhrase; i++){
  118791. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118792. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  118793. iEnd = pPhrase->iHead;
  118794. }
  118795. }
  118796. if( iEnd==0x7FFFFFFF ){
  118797. return 1;
  118798. }
  118799. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  118800. for(i=0; i<pIter->nPhrase; i++){
  118801. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118802. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  118803. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  118804. }
  118805. }
  118806. return 0;
  118807. }
  118808. /*
  118809. ** Retrieve information about the current candidate snippet of snippet
  118810. ** iterator pIter.
  118811. */
  118812. static void fts3SnippetDetails(
  118813. SnippetIter *pIter, /* Snippet iterator */
  118814. u64 mCovered, /* Bitmask of phrases already covered */
  118815. int *piToken, /* OUT: First token of proposed snippet */
  118816. int *piScore, /* OUT: "Score" for this snippet */
  118817. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  118818. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  118819. ){
  118820. int iStart = pIter->iCurrent; /* First token of snippet */
  118821. int iScore = 0; /* Score of this snippet */
  118822. int i; /* Loop counter */
  118823. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  118824. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  118825. for(i=0; i<pIter->nPhrase; i++){
  118826. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  118827. if( pPhrase->pTail ){
  118828. char *pCsr = pPhrase->pTail;
  118829. int iCsr = pPhrase->iTail;
  118830. while( iCsr<(iStart+pIter->nSnippet) ){
  118831. int j;
  118832. u64 mPhrase = (u64)1 << i;
  118833. u64 mPos = (u64)1 << (iCsr - iStart);
  118834. assert( iCsr>=iStart );
  118835. if( (mCover|mCovered)&mPhrase ){
  118836. iScore++;
  118837. }else{
  118838. iScore += 1000;
  118839. }
  118840. mCover |= mPhrase;
  118841. for(j=0; j<pPhrase->nToken; j++){
  118842. mHighlight |= (mPos>>j);
  118843. }
  118844. if( 0==(*pCsr & 0x0FE) ) break;
  118845. fts3GetDeltaPosition(&pCsr, &iCsr);
  118846. }
  118847. }
  118848. }
  118849. /* Set the output variables before returning. */
  118850. *piToken = iStart;
  118851. *piScore = iScore;
  118852. *pmCover = mCover;
  118853. *pmHighlight = mHighlight;
  118854. }
  118855. /*
  118856. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  118857. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  118858. */
  118859. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  118860. SnippetIter *p = (SnippetIter *)ctx;
  118861. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  118862. char *pCsr;
  118863. int rc;
  118864. pPhrase->nToken = pExpr->pPhrase->nToken;
  118865. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  118866. assert( rc==SQLITE_OK || pCsr==0 );
  118867. if( pCsr ){
  118868. int iFirst = 0;
  118869. pPhrase->pList = pCsr;
  118870. fts3GetDeltaPosition(&pCsr, &iFirst);
  118871. assert( iFirst>=0 );
  118872. pPhrase->pHead = pCsr;
  118873. pPhrase->pTail = pCsr;
  118874. pPhrase->iHead = iFirst;
  118875. pPhrase->iTail = iFirst;
  118876. }else{
  118877. assert( rc!=SQLITE_OK || (
  118878. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  118879. ));
  118880. }
  118881. return rc;
  118882. }
  118883. /*
  118884. ** Select the fragment of text consisting of nFragment contiguous tokens
  118885. ** from column iCol that represent the "best" snippet. The best snippet
  118886. ** is the snippet with the highest score, where scores are calculated
  118887. ** by adding:
  118888. **
  118889. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  118890. **
  118891. ** (b) +1000 points for the first occurrence of each matchable phrase in
  118892. ** the snippet for which the corresponding mCovered bit is not set.
  118893. **
  118894. ** The selected snippet parameters are stored in structure *pFragment before
  118895. ** returning. The score of the selected snippet is stored in *piScore
  118896. ** before returning.
  118897. */
  118898. static int fts3BestSnippet(
  118899. int nSnippet, /* Desired snippet length */
  118900. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  118901. int iCol, /* Index of column to create snippet from */
  118902. u64 mCovered, /* Mask of phrases already covered */
  118903. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  118904. SnippetFragment *pFragment, /* OUT: Best snippet found */
  118905. int *piScore /* OUT: Score of snippet pFragment */
  118906. ){
  118907. int rc; /* Return Code */
  118908. int nList; /* Number of phrases in expression */
  118909. SnippetIter sIter; /* Iterates through snippet candidates */
  118910. int nByte; /* Number of bytes of space to allocate */
  118911. int iBestScore = -1; /* Best snippet score found so far */
  118912. int i; /* Loop counter */
  118913. memset(&sIter, 0, sizeof(sIter));
  118914. /* Iterate through the phrases in the expression to count them. The same
  118915. ** callback makes sure the doclists are loaded for each phrase.
  118916. */
  118917. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  118918. if( rc!=SQLITE_OK ){
  118919. return rc;
  118920. }
  118921. /* Now that it is known how many phrases there are, allocate and zero
  118922. ** the required space using malloc().
  118923. */
  118924. nByte = sizeof(SnippetPhrase) * nList;
  118925. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  118926. if( !sIter.aPhrase ){
  118927. return SQLITE_NOMEM;
  118928. }
  118929. memset(sIter.aPhrase, 0, nByte);
  118930. /* Initialize the contents of the SnippetIter object. Then iterate through
  118931. ** the set of phrases in the expression to populate the aPhrase[] array.
  118932. */
  118933. sIter.pCsr = pCsr;
  118934. sIter.iCol = iCol;
  118935. sIter.nSnippet = nSnippet;
  118936. sIter.nPhrase = nList;
  118937. sIter.iCurrent = -1;
  118938. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  118939. /* Set the *pmSeen output variable. */
  118940. for(i=0; i<nList; i++){
  118941. if( sIter.aPhrase[i].pHead ){
  118942. *pmSeen |= (u64)1 << i;
  118943. }
  118944. }
  118945. /* Loop through all candidate snippets. Store the best snippet in
  118946. ** *pFragment. Store its associated 'score' in iBestScore.
  118947. */
  118948. pFragment->iCol = iCol;
  118949. while( !fts3SnippetNextCandidate(&sIter) ){
  118950. int iPos;
  118951. int iScore;
  118952. u64 mCover;
  118953. u64 mHighlight;
  118954. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  118955. assert( iScore>=0 );
  118956. if( iScore>iBestScore ){
  118957. pFragment->iPos = iPos;
  118958. pFragment->hlmask = mHighlight;
  118959. pFragment->covered = mCover;
  118960. iBestScore = iScore;
  118961. }
  118962. }
  118963. sqlite3_free(sIter.aPhrase);
  118964. *piScore = iBestScore;
  118965. return SQLITE_OK;
  118966. }
  118967. /*
  118968. ** Append a string to the string-buffer passed as the first argument.
  118969. **
  118970. ** If nAppend is negative, then the length of the string zAppend is
  118971. ** determined using strlen().
  118972. */
  118973. static int fts3StringAppend(
  118974. StrBuffer *pStr, /* Buffer to append to */
  118975. const char *zAppend, /* Pointer to data to append to buffer */
  118976. int nAppend /* Size of zAppend in bytes (or -1) */
  118977. ){
  118978. if( nAppend<0 ){
  118979. nAppend = (int)strlen(zAppend);
  118980. }
  118981. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  118982. ** to grow the buffer until so that it is big enough to accomadate the
  118983. ** appended data.
  118984. */
  118985. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  118986. int nAlloc = pStr->nAlloc+nAppend+100;
  118987. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  118988. if( !zNew ){
  118989. return SQLITE_NOMEM;
  118990. }
  118991. pStr->z = zNew;
  118992. pStr->nAlloc = nAlloc;
  118993. }
  118994. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  118995. /* Append the data to the string buffer. */
  118996. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  118997. pStr->n += nAppend;
  118998. pStr->z[pStr->n] = '\0';
  118999. return SQLITE_OK;
  119000. }
  119001. /*
  119002. ** The fts3BestSnippet() function often selects snippets that end with a
  119003. ** query term. That is, the final term of the snippet is always a term
  119004. ** that requires highlighting. For example, if 'X' is a highlighted term
  119005. ** and '.' is a non-highlighted term, BestSnippet() may select:
  119006. **
  119007. ** ........X.....X
  119008. **
  119009. ** This function "shifts" the beginning of the snippet forward in the
  119010. ** document so that there are approximately the same number of
  119011. ** non-highlighted terms to the right of the final highlighted term as there
  119012. ** are to the left of the first highlighted term. For example, to this:
  119013. **
  119014. ** ....X.....X....
  119015. **
  119016. ** This is done as part of extracting the snippet text, not when selecting
  119017. ** the snippet. Snippet selection is done based on doclists only, so there
  119018. ** is no way for fts3BestSnippet() to know whether or not the document
  119019. ** actually contains terms that follow the final highlighted term.
  119020. */
  119021. static int fts3SnippetShift(
  119022. Fts3Table *pTab, /* FTS3 table snippet comes from */
  119023. int iLangid, /* Language id to use in tokenizing */
  119024. int nSnippet, /* Number of tokens desired for snippet */
  119025. const char *zDoc, /* Document text to extract snippet from */
  119026. int nDoc, /* Size of buffer zDoc in bytes */
  119027. int *piPos, /* IN/OUT: First token of snippet */
  119028. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  119029. ){
  119030. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  119031. if( hlmask ){
  119032. int nLeft; /* Tokens to the left of first highlight */
  119033. int nRight; /* Tokens to the right of last highlight */
  119034. int nDesired; /* Ideal number of tokens to shift forward */
  119035. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  119036. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  119037. nDesired = (nLeft-nRight)/2;
  119038. /* Ideally, the start of the snippet should be pushed forward in the
  119039. ** document nDesired tokens. This block checks if there are actually
  119040. ** nDesired tokens to the right of the snippet. If so, *piPos and
  119041. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  119042. ** right. Otherwise, the snippet is shifted by the number of tokens
  119043. ** available.
  119044. */
  119045. if( nDesired>0 ){
  119046. int nShift; /* Number of tokens to shift snippet by */
  119047. int iCurrent = 0; /* Token counter */
  119048. int rc; /* Return Code */
  119049. sqlite3_tokenizer_module *pMod;
  119050. sqlite3_tokenizer_cursor *pC;
  119051. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  119052. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  119053. ** or more tokens in zDoc/nDoc.
  119054. */
  119055. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  119056. if( rc!=SQLITE_OK ){
  119057. return rc;
  119058. }
  119059. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  119060. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  119061. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  119062. }
  119063. pMod->xClose(pC);
  119064. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  119065. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  119066. assert( nShift<=nDesired );
  119067. if( nShift>0 ){
  119068. *piPos += nShift;
  119069. *pHlmask = hlmask >> nShift;
  119070. }
  119071. }
  119072. }
  119073. return SQLITE_OK;
  119074. }
  119075. /*
  119076. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  119077. ** append it to string buffer pOut.
  119078. */
  119079. static int fts3SnippetText(
  119080. Fts3Cursor *pCsr, /* FTS3 Cursor */
  119081. SnippetFragment *pFragment, /* Snippet to extract */
  119082. int iFragment, /* Fragment number */
  119083. int isLast, /* True for final fragment in snippet */
  119084. int nSnippet, /* Number of tokens in extracted snippet */
  119085. const char *zOpen, /* String inserted before highlighted term */
  119086. const char *zClose, /* String inserted after highlighted term */
  119087. const char *zEllipsis, /* String inserted between snippets */
  119088. StrBuffer *pOut /* Write output here */
  119089. ){
  119090. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119091. int rc; /* Return code */
  119092. const char *zDoc; /* Document text to extract snippet from */
  119093. int nDoc; /* Size of zDoc in bytes */
  119094. int iCurrent = 0; /* Current token number of document */
  119095. int iEnd = 0; /* Byte offset of end of current token */
  119096. int isShiftDone = 0; /* True after snippet is shifted */
  119097. int iPos = pFragment->iPos; /* First token of snippet */
  119098. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  119099. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  119100. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  119101. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  119102. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  119103. if( zDoc==0 ){
  119104. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  119105. return SQLITE_NOMEM;
  119106. }
  119107. return SQLITE_OK;
  119108. }
  119109. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  119110. /* Open a token cursor on the document. */
  119111. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  119112. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  119113. if( rc!=SQLITE_OK ){
  119114. return rc;
  119115. }
  119116. while( rc==SQLITE_OK ){
  119117. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  119118. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  119119. int iBegin = 0; /* Offset in zDoc of start of token */
  119120. int iFin = 0; /* Offset in zDoc of end of token */
  119121. int isHighlight = 0; /* True for highlighted terms */
  119122. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  119123. ** in the FTS code the variable that the third argument to xNext points to
  119124. ** is initialized to zero before the first (*but not necessarily
  119125. ** subsequent*) call to xNext(). This is done for a particular application
  119126. ** that needs to know whether or not the tokenizer is being used for
  119127. ** snippet generation or for some other purpose.
  119128. **
  119129. ** Extreme care is required when writing code to depend on this
  119130. ** initialization. It is not a documented part of the tokenizer interface.
  119131. ** If a tokenizer is used directly by any code outside of FTS, this
  119132. ** convention might not be respected. */
  119133. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  119134. if( rc!=SQLITE_OK ){
  119135. if( rc==SQLITE_DONE ){
  119136. /* Special case - the last token of the snippet is also the last token
  119137. ** of the column. Append any punctuation that occurred between the end
  119138. ** of the previous token and the end of the document to the output.
  119139. ** Then break out of the loop. */
  119140. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  119141. }
  119142. break;
  119143. }
  119144. if( iCurrent<iPos ){ continue; }
  119145. if( !isShiftDone ){
  119146. int n = nDoc - iBegin;
  119147. rc = fts3SnippetShift(
  119148. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  119149. );
  119150. isShiftDone = 1;
  119151. /* Now that the shift has been done, check if the initial "..." are
  119152. ** required. They are required if (a) this is not the first fragment,
  119153. ** or (b) this fragment does not begin at position 0 of its column.
  119154. */
  119155. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  119156. rc = fts3StringAppend(pOut, zEllipsis, -1);
  119157. }
  119158. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  119159. }
  119160. if( iCurrent>=(iPos+nSnippet) ){
  119161. if( isLast ){
  119162. rc = fts3StringAppend(pOut, zEllipsis, -1);
  119163. }
  119164. break;
  119165. }
  119166. /* Set isHighlight to true if this term should be highlighted. */
  119167. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  119168. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  119169. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  119170. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  119171. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  119172. iEnd = iFin;
  119173. }
  119174. pMod->xClose(pC);
  119175. return rc;
  119176. }
  119177. /*
  119178. ** This function is used to count the entries in a column-list (a
  119179. ** delta-encoded list of term offsets within a single column of a single
  119180. ** row). When this function is called, *ppCollist should point to the
  119181. ** beginning of the first varint in the column-list (the varint that
  119182. ** contains the position of the first matching term in the column data).
  119183. ** Before returning, *ppCollist is set to point to the first byte after
  119184. ** the last varint in the column-list (either the 0x00 signifying the end
  119185. ** of the position-list, or the 0x01 that precedes the column number of
  119186. ** the next column in the position-list).
  119187. **
  119188. ** The number of elements in the column-list is returned.
  119189. */
  119190. static int fts3ColumnlistCount(char **ppCollist){
  119191. char *pEnd = *ppCollist;
  119192. char c = 0;
  119193. int nEntry = 0;
  119194. /* A column-list is terminated by either a 0x01 or 0x00. */
  119195. while( 0xFE & (*pEnd | c) ){
  119196. c = *pEnd++ & 0x80;
  119197. if( !c ) nEntry++;
  119198. }
  119199. *ppCollist = pEnd;
  119200. return nEntry;
  119201. }
  119202. /*
  119203. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  119204. ** for a single query.
  119205. **
  119206. ** fts3ExprIterate() callback to load the 'global' elements of a
  119207. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  119208. ** of the matchinfo array that are constant for all rows returned by the
  119209. ** current query.
  119210. **
  119211. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  119212. ** function populates Matchinfo.aMatchinfo[] as follows:
  119213. **
  119214. ** for(iCol=0; iCol<nCol; iCol++){
  119215. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  119216. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  119217. ** }
  119218. **
  119219. ** where X is the number of matches for phrase iPhrase is column iCol of all
  119220. ** rows of the table. Y is the number of rows for which column iCol contains
  119221. ** at least one instance of phrase iPhrase.
  119222. **
  119223. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  119224. ** Y values are set to nDoc, where nDoc is the number of documents in the
  119225. ** file system. This is done because the full-text index doclist is required
  119226. ** to calculate these values properly, and the full-text index doclist is
  119227. ** not available for deferred tokens.
  119228. */
  119229. static int fts3ExprGlobalHitsCb(
  119230. Fts3Expr *pExpr, /* Phrase expression node */
  119231. int iPhrase, /* Phrase number (numbered from zero) */
  119232. void *pCtx /* Pointer to MatchInfo structure */
  119233. ){
  119234. MatchInfo *p = (MatchInfo *)pCtx;
  119235. return sqlite3Fts3EvalPhraseStats(
  119236. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  119237. );
  119238. }
  119239. /*
  119240. ** fts3ExprIterate() callback used to collect the "local" part of the
  119241. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  119242. ** array that are different for each row returned by the query.
  119243. */
  119244. static int fts3ExprLocalHitsCb(
  119245. Fts3Expr *pExpr, /* Phrase expression node */
  119246. int iPhrase, /* Phrase number */
  119247. void *pCtx /* Pointer to MatchInfo structure */
  119248. ){
  119249. int rc = SQLITE_OK;
  119250. MatchInfo *p = (MatchInfo *)pCtx;
  119251. int iStart = iPhrase * p->nCol * 3;
  119252. int i;
  119253. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  119254. char *pCsr;
  119255. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  119256. if( pCsr ){
  119257. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  119258. }else{
  119259. p->aMatchinfo[iStart+i*3] = 0;
  119260. }
  119261. }
  119262. return rc;
  119263. }
  119264. static int fts3MatchinfoCheck(
  119265. Fts3Table *pTab,
  119266. char cArg,
  119267. char **pzErr
  119268. ){
  119269. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  119270. || (cArg==FTS3_MATCHINFO_NCOL)
  119271. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  119272. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  119273. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  119274. || (cArg==FTS3_MATCHINFO_LCS)
  119275. || (cArg==FTS3_MATCHINFO_HITS)
  119276. ){
  119277. return SQLITE_OK;
  119278. }
  119279. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  119280. return SQLITE_ERROR;
  119281. }
  119282. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  119283. int nVal; /* Number of integers output by cArg */
  119284. switch( cArg ){
  119285. case FTS3_MATCHINFO_NDOC:
  119286. case FTS3_MATCHINFO_NPHRASE:
  119287. case FTS3_MATCHINFO_NCOL:
  119288. nVal = 1;
  119289. break;
  119290. case FTS3_MATCHINFO_AVGLENGTH:
  119291. case FTS3_MATCHINFO_LENGTH:
  119292. case FTS3_MATCHINFO_LCS:
  119293. nVal = pInfo->nCol;
  119294. break;
  119295. default:
  119296. assert( cArg==FTS3_MATCHINFO_HITS );
  119297. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  119298. break;
  119299. }
  119300. return nVal;
  119301. }
  119302. static int fts3MatchinfoSelectDoctotal(
  119303. Fts3Table *pTab,
  119304. sqlite3_stmt **ppStmt,
  119305. sqlite3_int64 *pnDoc,
  119306. const char **paLen
  119307. ){
  119308. sqlite3_stmt *pStmt;
  119309. const char *a;
  119310. sqlite3_int64 nDoc;
  119311. if( !*ppStmt ){
  119312. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  119313. if( rc!=SQLITE_OK ) return rc;
  119314. }
  119315. pStmt = *ppStmt;
  119316. assert( sqlite3_data_count(pStmt)==1 );
  119317. a = sqlite3_column_blob(pStmt, 0);
  119318. a += sqlite3Fts3GetVarint(a, &nDoc);
  119319. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  119320. *pnDoc = (u32)nDoc;
  119321. if( paLen ) *paLen = a;
  119322. return SQLITE_OK;
  119323. }
  119324. /*
  119325. ** An instance of the following structure is used to store state while
  119326. ** iterating through a multi-column position-list corresponding to the
  119327. ** hits for a single phrase on a single row in order to calculate the
  119328. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  119329. */
  119330. typedef struct LcsIterator LcsIterator;
  119331. struct LcsIterator {
  119332. Fts3Expr *pExpr; /* Pointer to phrase expression */
  119333. int iPosOffset; /* Tokens count up to end of this phrase */
  119334. char *pRead; /* Cursor used to iterate through aDoclist */
  119335. int iPos; /* Current position */
  119336. };
  119337. /*
  119338. ** If LcsIterator.iCol is set to the following value, the iterator has
  119339. ** finished iterating through all offsets for all columns.
  119340. */
  119341. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  119342. static int fts3MatchinfoLcsCb(
  119343. Fts3Expr *pExpr, /* Phrase expression node */
  119344. int iPhrase, /* Phrase number (numbered from zero) */
  119345. void *pCtx /* Pointer to MatchInfo structure */
  119346. ){
  119347. LcsIterator *aIter = (LcsIterator *)pCtx;
  119348. aIter[iPhrase].pExpr = pExpr;
  119349. return SQLITE_OK;
  119350. }
  119351. /*
  119352. ** Advance the iterator passed as an argument to the next position. Return
  119353. ** 1 if the iterator is at EOF or if it now points to the start of the
  119354. ** position list for the next column.
  119355. */
  119356. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  119357. char *pRead = pIter->pRead;
  119358. sqlite3_int64 iRead;
  119359. int rc = 0;
  119360. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  119361. if( iRead==0 || iRead==1 ){
  119362. pRead = 0;
  119363. rc = 1;
  119364. }else{
  119365. pIter->iPos += (int)(iRead-2);
  119366. }
  119367. pIter->pRead = pRead;
  119368. return rc;
  119369. }
  119370. /*
  119371. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  119372. **
  119373. ** If the call is successful, the longest-common-substring lengths for each
  119374. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  119375. ** array before returning. SQLITE_OK is returned in this case.
  119376. **
  119377. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  119378. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  119379. ** undefined.
  119380. */
  119381. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  119382. LcsIterator *aIter;
  119383. int i;
  119384. int iCol;
  119385. int nToken = 0;
  119386. /* Allocate and populate the array of LcsIterator objects. The array
  119387. ** contains one element for each matchable phrase in the query.
  119388. **/
  119389. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  119390. if( !aIter ) return SQLITE_NOMEM;
  119391. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  119392. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  119393. for(i=0; i<pInfo->nPhrase; i++){
  119394. LcsIterator *pIter = &aIter[i];
  119395. nToken -= pIter->pExpr->pPhrase->nToken;
  119396. pIter->iPosOffset = nToken;
  119397. }
  119398. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119399. int nLcs = 0; /* LCS value for this column */
  119400. int nLive = 0; /* Number of iterators in aIter not at EOF */
  119401. for(i=0; i<pInfo->nPhrase; i++){
  119402. int rc;
  119403. LcsIterator *pIt = &aIter[i];
  119404. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  119405. if( rc!=SQLITE_OK ) return rc;
  119406. if( pIt->pRead ){
  119407. pIt->iPos = pIt->iPosOffset;
  119408. fts3LcsIteratorAdvance(&aIter[i]);
  119409. nLive++;
  119410. }
  119411. }
  119412. while( nLive>0 ){
  119413. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  119414. int nThisLcs = 0; /* LCS for the current iterator positions */
  119415. for(i=0; i<pInfo->nPhrase; i++){
  119416. LcsIterator *pIter = &aIter[i];
  119417. if( pIter->pRead==0 ){
  119418. /* This iterator is already at EOF for this column. */
  119419. nThisLcs = 0;
  119420. }else{
  119421. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  119422. pAdv = pIter;
  119423. }
  119424. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  119425. nThisLcs++;
  119426. }else{
  119427. nThisLcs = 1;
  119428. }
  119429. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  119430. }
  119431. }
  119432. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  119433. }
  119434. pInfo->aMatchinfo[iCol] = nLcs;
  119435. }
  119436. sqlite3_free(aIter);
  119437. return SQLITE_OK;
  119438. }
  119439. /*
  119440. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  119441. ** be returned by the matchinfo() function. Argument zArg contains the
  119442. ** format string passed as the second argument to matchinfo (or the
  119443. ** default value "pcx" if no second argument was specified). The format
  119444. ** string has already been validated and the pInfo->aMatchinfo[] array
  119445. ** is guaranteed to be large enough for the output.
  119446. **
  119447. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  119448. ** If it is false, then assume that those fields that do not change between
  119449. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  119450. ** have already been populated.
  119451. **
  119452. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  119453. ** occurs. If a value other than SQLITE_OK is returned, the state the
  119454. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  119455. */
  119456. static int fts3MatchinfoValues(
  119457. Fts3Cursor *pCsr, /* FTS3 cursor object */
  119458. int bGlobal, /* True to grab the global stats */
  119459. MatchInfo *pInfo, /* Matchinfo context object */
  119460. const char *zArg /* Matchinfo format string */
  119461. ){
  119462. int rc = SQLITE_OK;
  119463. int i;
  119464. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119465. sqlite3_stmt *pSelect = 0;
  119466. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  119467. switch( zArg[i] ){
  119468. case FTS3_MATCHINFO_NPHRASE:
  119469. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  119470. break;
  119471. case FTS3_MATCHINFO_NCOL:
  119472. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  119473. break;
  119474. case FTS3_MATCHINFO_NDOC:
  119475. if( bGlobal ){
  119476. sqlite3_int64 nDoc = 0;
  119477. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  119478. pInfo->aMatchinfo[0] = (u32)nDoc;
  119479. }
  119480. break;
  119481. case FTS3_MATCHINFO_AVGLENGTH:
  119482. if( bGlobal ){
  119483. sqlite3_int64 nDoc; /* Number of rows in table */
  119484. const char *a; /* Aggregate column length array */
  119485. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  119486. if( rc==SQLITE_OK ){
  119487. int iCol;
  119488. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119489. u32 iVal;
  119490. sqlite3_int64 nToken;
  119491. a += sqlite3Fts3GetVarint(a, &nToken);
  119492. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  119493. pInfo->aMatchinfo[iCol] = iVal;
  119494. }
  119495. }
  119496. }
  119497. break;
  119498. case FTS3_MATCHINFO_LENGTH: {
  119499. sqlite3_stmt *pSelectDocsize = 0;
  119500. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  119501. if( rc==SQLITE_OK ){
  119502. int iCol;
  119503. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  119504. for(iCol=0; iCol<pInfo->nCol; iCol++){
  119505. sqlite3_int64 nToken;
  119506. a += sqlite3Fts3GetVarint(a, &nToken);
  119507. pInfo->aMatchinfo[iCol] = (u32)nToken;
  119508. }
  119509. }
  119510. sqlite3_reset(pSelectDocsize);
  119511. break;
  119512. }
  119513. case FTS3_MATCHINFO_LCS:
  119514. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  119515. if( rc==SQLITE_OK ){
  119516. rc = fts3MatchinfoLcs(pCsr, pInfo);
  119517. }
  119518. break;
  119519. default: {
  119520. Fts3Expr *pExpr;
  119521. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  119522. pExpr = pCsr->pExpr;
  119523. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  119524. if( rc!=SQLITE_OK ) break;
  119525. if( bGlobal ){
  119526. if( pCsr->pDeferred ){
  119527. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  119528. if( rc!=SQLITE_OK ) break;
  119529. }
  119530. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  119531. if( rc!=SQLITE_OK ) break;
  119532. }
  119533. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  119534. break;
  119535. }
  119536. }
  119537. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  119538. }
  119539. sqlite3_reset(pSelect);
  119540. return rc;
  119541. }
  119542. /*
  119543. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  119544. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  119545. */
  119546. static int fts3GetMatchinfo(
  119547. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  119548. const char *zArg /* Second argument to matchinfo() function */
  119549. ){
  119550. MatchInfo sInfo;
  119551. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119552. int rc = SQLITE_OK;
  119553. int bGlobal = 0; /* Collect 'global' stats as well as local */
  119554. memset(&sInfo, 0, sizeof(MatchInfo));
  119555. sInfo.pCursor = pCsr;
  119556. sInfo.nCol = pTab->nColumn;
  119557. /* If there is cached matchinfo() data, but the format string for the
  119558. ** cache does not match the format string for this request, discard
  119559. ** the cached data. */
  119560. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  119561. assert( pCsr->aMatchinfo );
  119562. sqlite3_free(pCsr->aMatchinfo);
  119563. pCsr->zMatchinfo = 0;
  119564. pCsr->aMatchinfo = 0;
  119565. }
  119566. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  119567. ** matchinfo function has been called for this query. In this case
  119568. ** allocate the array used to accumulate the matchinfo data and
  119569. ** initialize those elements that are constant for every row.
  119570. */
  119571. if( pCsr->aMatchinfo==0 ){
  119572. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  119573. int nArg; /* Bytes in zArg */
  119574. int i; /* Used to iterate through zArg */
  119575. /* Determine the number of phrases in the query */
  119576. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  119577. sInfo.nPhrase = pCsr->nPhrase;
  119578. /* Determine the number of integers in the buffer returned by this call. */
  119579. for(i=0; zArg[i]; i++){
  119580. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  119581. }
  119582. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  119583. nArg = (int)strlen(zArg);
  119584. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  119585. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  119586. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  119587. pCsr->nMatchinfo = nMatchinfo;
  119588. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  119589. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  119590. pCsr->isMatchinfoNeeded = 1;
  119591. bGlobal = 1;
  119592. }
  119593. sInfo.aMatchinfo = pCsr->aMatchinfo;
  119594. sInfo.nPhrase = pCsr->nPhrase;
  119595. if( pCsr->isMatchinfoNeeded ){
  119596. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  119597. pCsr->isMatchinfoNeeded = 0;
  119598. }
  119599. return rc;
  119600. }
  119601. /*
  119602. ** Implementation of snippet() function.
  119603. */
  119604. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  119605. sqlite3_context *pCtx, /* SQLite function call context */
  119606. Fts3Cursor *pCsr, /* Cursor object */
  119607. const char *zStart, /* Snippet start text - "<b>" */
  119608. const char *zEnd, /* Snippet end text - "</b>" */
  119609. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  119610. int iCol, /* Extract snippet from this column */
  119611. int nToken /* Approximate number of tokens in snippet */
  119612. ){
  119613. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119614. int rc = SQLITE_OK;
  119615. int i;
  119616. StrBuffer res = {0, 0, 0};
  119617. /* The returned text includes up to four fragments of text extracted from
  119618. ** the data in the current row. The first iteration of the for(...) loop
  119619. ** below attempts to locate a single fragment of text nToken tokens in
  119620. ** size that contains at least one instance of all phrases in the query
  119621. ** expression that appear in the current row. If such a fragment of text
  119622. ** cannot be found, the second iteration of the loop attempts to locate
  119623. ** a pair of fragments, and so on.
  119624. */
  119625. int nSnippet = 0; /* Number of fragments in this snippet */
  119626. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  119627. int nFToken = -1; /* Number of tokens in each fragment */
  119628. if( !pCsr->pExpr ){
  119629. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  119630. return;
  119631. }
  119632. for(nSnippet=1; 1; nSnippet++){
  119633. int iSnip; /* Loop counter 0..nSnippet-1 */
  119634. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  119635. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  119636. if( nToken>=0 ){
  119637. nFToken = (nToken+nSnippet-1) / nSnippet;
  119638. }else{
  119639. nFToken = -1 * nToken;
  119640. }
  119641. for(iSnip=0; iSnip<nSnippet; iSnip++){
  119642. int iBestScore = -1; /* Best score of columns checked so far */
  119643. int iRead; /* Used to iterate through columns */
  119644. SnippetFragment *pFragment = &aSnippet[iSnip];
  119645. memset(pFragment, 0, sizeof(*pFragment));
  119646. /* Loop through all columns of the table being considered for snippets.
  119647. ** If the iCol argument to this function was negative, this means all
  119648. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  119649. */
  119650. for(iRead=0; iRead<pTab->nColumn; iRead++){
  119651. SnippetFragment sF = {0, 0, 0, 0};
  119652. int iS;
  119653. if( iCol>=0 && iRead!=iCol ) continue;
  119654. /* Find the best snippet of nFToken tokens in column iRead. */
  119655. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  119656. if( rc!=SQLITE_OK ){
  119657. goto snippet_out;
  119658. }
  119659. if( iS>iBestScore ){
  119660. *pFragment = sF;
  119661. iBestScore = iS;
  119662. }
  119663. }
  119664. mCovered |= pFragment->covered;
  119665. }
  119666. /* If all query phrases seen by fts3BestSnippet() are present in at least
  119667. ** one of the nSnippet snippet fragments, break out of the loop.
  119668. */
  119669. assert( (mCovered&mSeen)==mCovered );
  119670. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  119671. }
  119672. assert( nFToken>0 );
  119673. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  119674. rc = fts3SnippetText(pCsr, &aSnippet[i],
  119675. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  119676. );
  119677. }
  119678. snippet_out:
  119679. sqlite3Fts3SegmentsClose(pTab);
  119680. if( rc!=SQLITE_OK ){
  119681. sqlite3_result_error_code(pCtx, rc);
  119682. sqlite3_free(res.z);
  119683. }else{
  119684. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  119685. }
  119686. }
  119687. typedef struct TermOffset TermOffset;
  119688. typedef struct TermOffsetCtx TermOffsetCtx;
  119689. struct TermOffset {
  119690. char *pList; /* Position-list */
  119691. int iPos; /* Position just read from pList */
  119692. int iOff; /* Offset of this term from read positions */
  119693. };
  119694. struct TermOffsetCtx {
  119695. Fts3Cursor *pCsr;
  119696. int iCol; /* Column of table to populate aTerm for */
  119697. int iTerm;
  119698. sqlite3_int64 iDocid;
  119699. TermOffset *aTerm;
  119700. };
  119701. /*
  119702. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  119703. */
  119704. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  119705. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  119706. int nTerm; /* Number of tokens in phrase */
  119707. int iTerm; /* For looping through nTerm phrase terms */
  119708. char *pList; /* Pointer to position list for phrase */
  119709. int iPos = 0; /* First position in position-list */
  119710. int rc;
  119711. UNUSED_PARAMETER(iPhrase);
  119712. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  119713. nTerm = pExpr->pPhrase->nToken;
  119714. if( pList ){
  119715. fts3GetDeltaPosition(&pList, &iPos);
  119716. assert( iPos>=0 );
  119717. }
  119718. for(iTerm=0; iTerm<nTerm; iTerm++){
  119719. TermOffset *pT = &p->aTerm[p->iTerm++];
  119720. pT->iOff = nTerm-iTerm-1;
  119721. pT->pList = pList;
  119722. pT->iPos = iPos;
  119723. }
  119724. return rc;
  119725. }
  119726. /*
  119727. ** Implementation of offsets() function.
  119728. */
  119729. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  119730. sqlite3_context *pCtx, /* SQLite function call context */
  119731. Fts3Cursor *pCsr /* Cursor object */
  119732. ){
  119733. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119734. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  119735. int rc; /* Return Code */
  119736. int nToken; /* Number of tokens in query */
  119737. int iCol; /* Column currently being processed */
  119738. StrBuffer res = {0, 0, 0}; /* Result string */
  119739. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  119740. if( !pCsr->pExpr ){
  119741. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  119742. return;
  119743. }
  119744. memset(&sCtx, 0, sizeof(sCtx));
  119745. assert( pCsr->isRequireSeek==0 );
  119746. /* Count the number of terms in the query */
  119747. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  119748. if( rc!=SQLITE_OK ) goto offsets_out;
  119749. /* Allocate the array of TermOffset iterators. */
  119750. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  119751. if( 0==sCtx.aTerm ){
  119752. rc = SQLITE_NOMEM;
  119753. goto offsets_out;
  119754. }
  119755. sCtx.iDocid = pCsr->iPrevId;
  119756. sCtx.pCsr = pCsr;
  119757. /* Loop through the table columns, appending offset information to
  119758. ** string-buffer res for each column.
  119759. */
  119760. for(iCol=0; iCol<pTab->nColumn; iCol++){
  119761. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  119762. const char *ZDUMMY; /* Dummy argument used with xNext() */
  119763. int NDUMMY = 0; /* Dummy argument used with xNext() */
  119764. int iStart = 0;
  119765. int iEnd = 0;
  119766. int iCurrent = 0;
  119767. const char *zDoc;
  119768. int nDoc;
  119769. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  119770. ** no way that this operation can fail, so the return code from
  119771. ** fts3ExprIterate() can be discarded.
  119772. */
  119773. sCtx.iCol = iCol;
  119774. sCtx.iTerm = 0;
  119775. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  119776. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  119777. ** in column iCol, jump immediately to the next iteration of the loop.
  119778. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  119779. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  119780. ** to the caller.
  119781. */
  119782. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  119783. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  119784. if( zDoc==0 ){
  119785. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  119786. continue;
  119787. }
  119788. rc = SQLITE_NOMEM;
  119789. goto offsets_out;
  119790. }
  119791. /* Initialize a tokenizer iterator to iterate through column iCol. */
  119792. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  119793. zDoc, nDoc, &pC
  119794. );
  119795. if( rc!=SQLITE_OK ) goto offsets_out;
  119796. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  119797. while( rc==SQLITE_OK ){
  119798. int i; /* Used to loop through terms */
  119799. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  119800. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  119801. for(i=0; i<nToken; i++){
  119802. TermOffset *pT = &sCtx.aTerm[i];
  119803. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  119804. iMinPos = pT->iPos-pT->iOff;
  119805. pTerm = pT;
  119806. }
  119807. }
  119808. if( !pTerm ){
  119809. /* All offsets for this column have been gathered. */
  119810. rc = SQLITE_DONE;
  119811. }else{
  119812. assert( iCurrent<=iMinPos );
  119813. if( 0==(0xFE&*pTerm->pList) ){
  119814. pTerm->pList = 0;
  119815. }else{
  119816. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  119817. }
  119818. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  119819. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  119820. }
  119821. if( rc==SQLITE_OK ){
  119822. char aBuffer[64];
  119823. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  119824. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  119825. );
  119826. rc = fts3StringAppend(&res, aBuffer, -1);
  119827. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  119828. rc = FTS_CORRUPT_VTAB;
  119829. }
  119830. }
  119831. }
  119832. if( rc==SQLITE_DONE ){
  119833. rc = SQLITE_OK;
  119834. }
  119835. pMod->xClose(pC);
  119836. if( rc!=SQLITE_OK ) goto offsets_out;
  119837. }
  119838. offsets_out:
  119839. sqlite3_free(sCtx.aTerm);
  119840. assert( rc!=SQLITE_DONE );
  119841. sqlite3Fts3SegmentsClose(pTab);
  119842. if( rc!=SQLITE_OK ){
  119843. sqlite3_result_error_code(pCtx, rc);
  119844. sqlite3_free(res.z);
  119845. }else{
  119846. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  119847. }
  119848. return;
  119849. }
  119850. /*
  119851. ** Implementation of matchinfo() function.
  119852. */
  119853. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  119854. sqlite3_context *pContext, /* Function call context */
  119855. Fts3Cursor *pCsr, /* FTS3 table cursor */
  119856. const char *zArg /* Second arg to matchinfo() function */
  119857. ){
  119858. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  119859. int rc;
  119860. int i;
  119861. const char *zFormat;
  119862. if( zArg ){
  119863. for(i=0; zArg[i]; i++){
  119864. char *zErr = 0;
  119865. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  119866. sqlite3_result_error(pContext, zErr, -1);
  119867. sqlite3_free(zErr);
  119868. return;
  119869. }
  119870. }
  119871. zFormat = zArg;
  119872. }else{
  119873. zFormat = FTS3_MATCHINFO_DEFAULT;
  119874. }
  119875. if( !pCsr->pExpr ){
  119876. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  119877. return;
  119878. }
  119879. /* Retrieve matchinfo() data. */
  119880. rc = fts3GetMatchinfo(pCsr, zFormat);
  119881. sqlite3Fts3SegmentsClose(pTab);
  119882. if( rc!=SQLITE_OK ){
  119883. sqlite3_result_error_code(pContext, rc);
  119884. }else{
  119885. int n = pCsr->nMatchinfo * sizeof(u32);
  119886. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  119887. }
  119888. }
  119889. #endif
  119890. /************** End of fts3_snippet.c ****************************************/
  119891. /************** Begin file fts3_unicode.c ************************************/
  119892. /*
  119893. ** 2012 May 24
  119894. **
  119895. ** The author disclaims copyright to this source code. In place of
  119896. ** a legal notice, here is a blessing:
  119897. **
  119898. ** May you do good and not evil.
  119899. ** May you find forgiveness for yourself and forgive others.
  119900. ** May you share freely, never taking more than you give.
  119901. **
  119902. ******************************************************************************
  119903. **
  119904. ** Implementation of the "unicode" full-text-search tokenizer.
  119905. */
  119906. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  119907. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  119908. /* #include <assert.h> */
  119909. /* #include <stdlib.h> */
  119910. /* #include <stdio.h> */
  119911. /* #include <string.h> */
  119912. /*
  119913. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  119914. ** from the sqlite3 source file utf.c. If this file is compiled as part
  119915. ** of the amalgamation, they are not required.
  119916. */
  119917. #ifndef SQLITE_AMALGAMATION
  119918. static const unsigned char sqlite3Utf8Trans1[] = {
  119919. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119920. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  119921. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  119922. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  119923. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119924. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  119925. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  119926. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  119927. };
  119928. #define READ_UTF8(zIn, zTerm, c) \
  119929. c = *(zIn++); \
  119930. if( c>=0xc0 ){ \
  119931. c = sqlite3Utf8Trans1[c-0xc0]; \
  119932. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  119933. c = (c<<6) + (0x3f & *(zIn++)); \
  119934. } \
  119935. if( c<0x80 \
  119936. || (c&0xFFFFF800)==0xD800 \
  119937. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  119938. }
  119939. #define WRITE_UTF8(zOut, c) { \
  119940. if( c<0x00080 ){ \
  119941. *zOut++ = (u8)(c&0xFF); \
  119942. } \
  119943. else if( c<0x00800 ){ \
  119944. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  119945. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119946. } \
  119947. else if( c<0x10000 ){ \
  119948. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  119949. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  119950. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119951. }else{ \
  119952. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  119953. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  119954. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  119955. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  119956. } \
  119957. }
  119958. #endif /* ifndef SQLITE_AMALGAMATION */
  119959. typedef struct unicode_tokenizer unicode_tokenizer;
  119960. typedef struct unicode_cursor unicode_cursor;
  119961. struct unicode_tokenizer {
  119962. sqlite3_tokenizer base;
  119963. int bRemoveDiacritic;
  119964. int nException;
  119965. int *aiException;
  119966. };
  119967. struct unicode_cursor {
  119968. sqlite3_tokenizer_cursor base;
  119969. const unsigned char *aInput; /* Input text being tokenized */
  119970. int nInput; /* Size of aInput[] in bytes */
  119971. int iOff; /* Current offset within aInput[] */
  119972. int iToken; /* Index of next token to be returned */
  119973. char *zToken; /* storage for current token */
  119974. int nAlloc; /* space allocated at zToken */
  119975. };
  119976. /*
  119977. ** Destroy a tokenizer allocated by unicodeCreate().
  119978. */
  119979. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  119980. if( pTokenizer ){
  119981. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  119982. sqlite3_free(p->aiException);
  119983. sqlite3_free(p);
  119984. }
  119985. return SQLITE_OK;
  119986. }
  119987. /*
  119988. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  119989. ** statement has specified that the tokenizer for this table shall consider
  119990. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  119991. ** token characters (if bAlnum==1).
  119992. **
  119993. ** For each codepoint in the zIn/nIn string, this function checks if the
  119994. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  119995. ** If so, no action is taken. Otherwise, the codepoint is added to the
  119996. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  119997. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  119998. ** codepoints in the aiException[] array.
  119999. **
  120000. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  120001. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  120002. ** It is not possible to change the behavior of the tokenizer with respect
  120003. ** to these codepoints.
  120004. */
  120005. static int unicodeAddExceptions(
  120006. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  120007. int bAlnum, /* Replace Isalnum() return value with this */
  120008. const char *zIn, /* Array of characters to make exceptions */
  120009. int nIn /* Length of z in bytes */
  120010. ){
  120011. const unsigned char *z = (const unsigned char *)zIn;
  120012. const unsigned char *zTerm = &z[nIn];
  120013. int iCode;
  120014. int nEntry = 0;
  120015. assert( bAlnum==0 || bAlnum==1 );
  120016. while( z<zTerm ){
  120017. READ_UTF8(z, zTerm, iCode);
  120018. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  120019. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  120020. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  120021. ){
  120022. nEntry++;
  120023. }
  120024. }
  120025. if( nEntry ){
  120026. int *aNew; /* New aiException[] array */
  120027. int nNew; /* Number of valid entries in array aNew[] */
  120028. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  120029. if( aNew==0 ) return SQLITE_NOMEM;
  120030. nNew = p->nException;
  120031. z = (const unsigned char *)zIn;
  120032. while( z<zTerm ){
  120033. READ_UTF8(z, zTerm, iCode);
  120034. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  120035. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  120036. ){
  120037. int i, j;
  120038. for(i=0; i<nNew && aNew[i]<iCode; i++);
  120039. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  120040. aNew[i] = iCode;
  120041. nNew++;
  120042. }
  120043. }
  120044. p->aiException = aNew;
  120045. p->nException = nNew;
  120046. }
  120047. return SQLITE_OK;
  120048. }
  120049. /*
  120050. ** Return true if the p->aiException[] array contains the value iCode.
  120051. */
  120052. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  120053. if( p->nException>0 ){
  120054. int *a = p->aiException;
  120055. int iLo = 0;
  120056. int iHi = p->nException-1;
  120057. while( iHi>=iLo ){
  120058. int iTest = (iHi + iLo) / 2;
  120059. if( iCode==a[iTest] ){
  120060. return 1;
  120061. }else if( iCode>a[iTest] ){
  120062. iLo = iTest+1;
  120063. }else{
  120064. iHi = iTest-1;
  120065. }
  120066. }
  120067. }
  120068. return 0;
  120069. }
  120070. /*
  120071. ** Return true if, for the purposes of tokenization, codepoint iCode is
  120072. ** considered a token character (not a separator).
  120073. */
  120074. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  120075. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  120076. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  120077. }
  120078. /*
  120079. ** Create a new tokenizer instance.
  120080. */
  120081. static int unicodeCreate(
  120082. int nArg, /* Size of array argv[] */
  120083. const char * const *azArg, /* Tokenizer creation arguments */
  120084. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  120085. ){
  120086. unicode_tokenizer *pNew; /* New tokenizer object */
  120087. int i;
  120088. int rc = SQLITE_OK;
  120089. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  120090. if( pNew==NULL ) return SQLITE_NOMEM;
  120091. memset(pNew, 0, sizeof(unicode_tokenizer));
  120092. pNew->bRemoveDiacritic = 1;
  120093. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  120094. const char *z = azArg[i];
  120095. int n = strlen(z);
  120096. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  120097. pNew->bRemoveDiacritic = 1;
  120098. }
  120099. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  120100. pNew->bRemoveDiacritic = 0;
  120101. }
  120102. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  120103. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  120104. }
  120105. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  120106. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  120107. }
  120108. else{
  120109. /* Unrecognized argument */
  120110. rc = SQLITE_ERROR;
  120111. }
  120112. }
  120113. if( rc!=SQLITE_OK ){
  120114. unicodeDestroy((sqlite3_tokenizer *)pNew);
  120115. pNew = 0;
  120116. }
  120117. *pp = (sqlite3_tokenizer *)pNew;
  120118. return rc;
  120119. }
  120120. /*
  120121. ** Prepare to begin tokenizing a particular string. The input
  120122. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  120123. ** used to incrementally tokenize this string is returned in
  120124. ** *ppCursor.
  120125. */
  120126. static int unicodeOpen(
  120127. sqlite3_tokenizer *p, /* The tokenizer */
  120128. const char *aInput, /* Input string */
  120129. int nInput, /* Size of string aInput in bytes */
  120130. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  120131. ){
  120132. unicode_cursor *pCsr;
  120133. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  120134. if( pCsr==0 ){
  120135. return SQLITE_NOMEM;
  120136. }
  120137. memset(pCsr, 0, sizeof(unicode_cursor));
  120138. pCsr->aInput = (const unsigned char *)aInput;
  120139. if( aInput==0 ){
  120140. pCsr->nInput = 0;
  120141. }else if( nInput<0 ){
  120142. pCsr->nInput = (int)strlen(aInput);
  120143. }else{
  120144. pCsr->nInput = nInput;
  120145. }
  120146. *pp = &pCsr->base;
  120147. UNUSED_PARAMETER(p);
  120148. return SQLITE_OK;
  120149. }
  120150. /*
  120151. ** Close a tokenization cursor previously opened by a call to
  120152. ** simpleOpen() above.
  120153. */
  120154. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  120155. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  120156. sqlite3_free(pCsr->zToken);
  120157. sqlite3_free(pCsr);
  120158. return SQLITE_OK;
  120159. }
  120160. /*
  120161. ** Extract the next token from a tokenization cursor. The cursor must
  120162. ** have been opened by a prior call to simpleOpen().
  120163. */
  120164. static int unicodeNext(
  120165. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  120166. const char **paToken, /* OUT: Token text */
  120167. int *pnToken, /* OUT: Number of bytes at *paToken */
  120168. int *piStart, /* OUT: Starting offset of token */
  120169. int *piEnd, /* OUT: Ending offset of token */
  120170. int *piPos /* OUT: Position integer of token */
  120171. ){
  120172. unicode_cursor *pCsr = (unicode_cursor *)pC;
  120173. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  120174. int iCode;
  120175. char *zOut;
  120176. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  120177. const unsigned char *zStart = z;
  120178. const unsigned char *zEnd;
  120179. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  120180. /* Scan past any delimiter characters before the start of the next token.
  120181. ** Return SQLITE_DONE early if this takes us all the way to the end of
  120182. ** the input. */
  120183. while( z<zTerm ){
  120184. READ_UTF8(z, zTerm, iCode);
  120185. if( unicodeIsAlnum(p, iCode) ) break;
  120186. zStart = z;
  120187. }
  120188. if( zStart>=zTerm ) return SQLITE_DONE;
  120189. zOut = pCsr->zToken;
  120190. do {
  120191. int iOut;
  120192. /* Grow the output buffer if required. */
  120193. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  120194. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  120195. if( !zNew ) return SQLITE_NOMEM;
  120196. zOut = &zNew[zOut - pCsr->zToken];
  120197. pCsr->zToken = zNew;
  120198. pCsr->nAlloc += 64;
  120199. }
  120200. /* Write the folded case of the last character read to the output */
  120201. zEnd = z;
  120202. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  120203. if( iOut ){
  120204. WRITE_UTF8(zOut, iOut);
  120205. }
  120206. /* If the cursor is not at EOF, read the next character */
  120207. if( z>=zTerm ) break;
  120208. READ_UTF8(z, zTerm, iCode);
  120209. }while( unicodeIsAlnum(p, iCode)
  120210. || sqlite3FtsUnicodeIsdiacritic(iCode)
  120211. );
  120212. /* Set the output variables and return. */
  120213. pCsr->iOff = (z - pCsr->aInput);
  120214. *paToken = pCsr->zToken;
  120215. *pnToken = zOut - pCsr->zToken;
  120216. *piStart = (zStart - pCsr->aInput);
  120217. *piEnd = (zEnd - pCsr->aInput);
  120218. *piPos = pCsr->iToken++;
  120219. return SQLITE_OK;
  120220. }
  120221. /*
  120222. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  120223. ** structure for the unicode tokenizer.
  120224. */
  120225. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  120226. static const sqlite3_tokenizer_module module = {
  120227. 0,
  120228. unicodeCreate,
  120229. unicodeDestroy,
  120230. unicodeOpen,
  120231. unicodeClose,
  120232. unicodeNext,
  120233. 0,
  120234. };
  120235. *ppModule = &module;
  120236. }
  120237. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  120238. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  120239. /************** End of fts3_unicode.c ****************************************/
  120240. /************** Begin file fts3_unicode2.c ***********************************/
  120241. /*
  120242. ** 2012 May 25
  120243. **
  120244. ** The author disclaims copyright to this source code. In place of
  120245. ** a legal notice, here is a blessing:
  120246. **
  120247. ** May you do good and not evil.
  120248. ** May you find forgiveness for yourself and forgive others.
  120249. ** May you share freely, never taking more than you give.
  120250. **
  120251. ******************************************************************************
  120252. */
  120253. /*
  120254. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  120255. */
  120256. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  120257. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  120258. /* #include <assert.h> */
  120259. /*
  120260. ** Return true if the argument corresponds to a unicode codepoint
  120261. ** classified as either a letter or a number. Otherwise false.
  120262. **
  120263. ** The results are undefined if the value passed to this function
  120264. ** is less than zero.
  120265. */
  120266. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  120267. /* Each unsigned integer in the following array corresponds to a contiguous
  120268. ** range of unicode codepoints that are not either letters or numbers (i.e.
  120269. ** codepoints for which this function should return 0).
  120270. **
  120271. ** The most significant 22 bits in each 32-bit value contain the first
  120272. ** codepoint in the range. The least significant 10 bits are used to store
  120273. ** the size of the range (always at least 1). In other words, the value
  120274. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  120275. ** C. It is not possible to represent a range larger than 1023 codepoints
  120276. ** using this format.
  120277. */
  120278. const static unsigned int aEntry[] = {
  120279. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  120280. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  120281. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  120282. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  120283. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  120284. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  120285. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  120286. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  120287. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  120288. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  120289. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  120290. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  120291. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  120292. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  120293. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  120294. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  120295. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  120296. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  120297. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  120298. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  120299. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  120300. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  120301. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  120302. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  120303. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  120304. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  120305. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  120306. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  120307. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  120308. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  120309. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  120310. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  120311. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  120312. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  120313. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  120314. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  120315. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  120316. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  120317. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  120318. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  120319. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  120320. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  120321. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  120322. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  120323. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  120324. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  120325. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  120326. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  120327. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  120328. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  120329. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  120330. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  120331. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  120332. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  120333. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  120334. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  120335. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  120336. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  120337. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  120338. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  120339. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  120340. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  120341. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  120342. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  120343. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  120344. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  120345. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  120346. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  120347. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  120348. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  120349. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  120350. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  120351. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  120352. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  120353. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  120354. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  120355. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  120356. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  120357. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  120358. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  120359. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  120360. 0x380400F0,
  120361. };
  120362. static const unsigned int aAscii[4] = {
  120363. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  120364. };
  120365. if( c<128 ){
  120366. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  120367. }else if( c<(1<<22) ){
  120368. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  120369. int iRes;
  120370. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  120371. int iLo = 0;
  120372. while( iHi>=iLo ){
  120373. int iTest = (iHi + iLo) / 2;
  120374. if( key >= aEntry[iTest] ){
  120375. iRes = iTest;
  120376. iLo = iTest+1;
  120377. }else{
  120378. iHi = iTest-1;
  120379. }
  120380. }
  120381. assert( aEntry[0]<key );
  120382. assert( key>=aEntry[iRes] );
  120383. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  120384. }
  120385. return 1;
  120386. }
  120387. /*
  120388. ** If the argument is a codepoint corresponding to a lowercase letter
  120389. ** in the ASCII range with a diacritic added, return the codepoint
  120390. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  120391. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  120392. ** E"). The resuls of passing a codepoint that corresponds to an
  120393. ** uppercase letter are undefined.
  120394. */
  120395. static int remove_diacritic(int c){
  120396. unsigned short aDia[] = {
  120397. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  120398. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  120399. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  120400. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  120401. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  120402. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  120403. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  120404. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  120405. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  120406. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  120407. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  120408. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  120409. 62924, 63050, 63082, 63274, 63390,
  120410. };
  120411. char aChar[] = {
  120412. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  120413. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  120414. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  120415. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  120416. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  120417. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  120418. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  120419. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  120420. 'e', 'i', 'o', 'u', 'y',
  120421. };
  120422. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  120423. int iRes = 0;
  120424. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  120425. int iLo = 0;
  120426. while( iHi>=iLo ){
  120427. int iTest = (iHi + iLo) / 2;
  120428. if( key >= aDia[iTest] ){
  120429. iRes = iTest;
  120430. iLo = iTest+1;
  120431. }else{
  120432. iHi = iTest-1;
  120433. }
  120434. }
  120435. assert( key>=aDia[iRes] );
  120436. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  120437. };
  120438. /*
  120439. ** Return true if the argument interpreted as a unicode codepoint
  120440. ** is a diacritical modifier character.
  120441. */
  120442. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  120443. unsigned int mask0 = 0x08029FDF;
  120444. unsigned int mask1 = 0x000361F8;
  120445. if( c<768 || c>817 ) return 0;
  120446. return (c < 768+32) ?
  120447. (mask0 & (1 << (c-768))) :
  120448. (mask1 & (1 << (c-768-32)));
  120449. }
  120450. /*
  120451. ** Interpret the argument as a unicode codepoint. If the codepoint
  120452. ** is an upper case character that has a lower case equivalent,
  120453. ** return the codepoint corresponding to the lower case version.
  120454. ** Otherwise, return a copy of the argument.
  120455. **
  120456. ** The results are undefined if the value passed to this function
  120457. ** is less than zero.
  120458. */
  120459. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  120460. /* Each entry in the following array defines a rule for folding a range
  120461. ** of codepoints to lower case. The rule applies to a range of nRange
  120462. ** codepoints starting at codepoint iCode.
  120463. **
  120464. ** If the least significant bit in flags is clear, then the rule applies
  120465. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  120466. ** need to be folded). Or, if it is set, then the rule only applies to
  120467. ** every second codepoint in the range, starting with codepoint C.
  120468. **
  120469. ** The 7 most significant bits in flags are an index into the aiOff[]
  120470. ** array. If a specific codepoint C does require folding, then its lower
  120471. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  120472. **
  120473. ** The contents of this array are generated by parsing the CaseFolding.txt
  120474. ** file distributed as part of the "Unicode Character Database". See
  120475. ** http://www.unicode.org for details.
  120476. */
  120477. static const struct TableEntry {
  120478. unsigned short iCode;
  120479. unsigned char flags;
  120480. unsigned char nRange;
  120481. } aEntry[] = {
  120482. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  120483. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  120484. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  120485. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  120486. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  120487. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  120488. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  120489. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  120490. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  120491. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  120492. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  120493. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  120494. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  120495. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  120496. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  120497. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  120498. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  120499. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  120500. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  120501. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  120502. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  120503. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  120504. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  120505. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  120506. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  120507. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  120508. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  120509. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  120510. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  120511. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  120512. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  120513. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  120514. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  120515. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  120516. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  120517. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  120518. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  120519. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  120520. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  120521. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  120522. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  120523. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  120524. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  120525. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  120526. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  120527. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  120528. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  120529. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  120530. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  120531. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  120532. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  120533. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  120534. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  120535. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  120536. {65313, 14, 26},
  120537. };
  120538. static const unsigned short aiOff[] = {
  120539. 1, 2, 8, 15, 16, 26, 28, 32,
  120540. 37, 38, 40, 48, 63, 64, 69, 71,
  120541. 79, 80, 116, 202, 203, 205, 206, 207,
  120542. 209, 210, 211, 213, 214, 217, 218, 219,
  120543. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  120544. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  120545. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  120546. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  120547. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  120548. 65514, 65521, 65527, 65528, 65529,
  120549. };
  120550. int ret = c;
  120551. assert( c>=0 );
  120552. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  120553. if( c<128 ){
  120554. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  120555. }else if( c<65536 ){
  120556. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  120557. int iLo = 0;
  120558. int iRes = -1;
  120559. while( iHi>=iLo ){
  120560. int iTest = (iHi + iLo) / 2;
  120561. int cmp = (c - aEntry[iTest].iCode);
  120562. if( cmp>=0 ){
  120563. iRes = iTest;
  120564. iLo = iTest+1;
  120565. }else{
  120566. iHi = iTest-1;
  120567. }
  120568. }
  120569. assert( iRes<0 || c>=aEntry[iRes].iCode );
  120570. if( iRes>=0 ){
  120571. const struct TableEntry *p = &aEntry[iRes];
  120572. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  120573. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  120574. assert( ret>0 );
  120575. }
  120576. }
  120577. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  120578. }
  120579. else if( c>=66560 && c<66600 ){
  120580. ret = c + 40;
  120581. }
  120582. return ret;
  120583. }
  120584. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  120585. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  120586. /************** End of fts3_unicode2.c ***************************************/
  120587. /************** Begin file rtree.c *******************************************/
  120588. /*
  120589. ** 2001 September 15
  120590. **
  120591. ** The author disclaims copyright to this source code. In place of
  120592. ** a legal notice, here is a blessing:
  120593. **
  120594. ** May you do good and not evil.
  120595. ** May you find forgiveness for yourself and forgive others.
  120596. ** May you share freely, never taking more than you give.
  120597. **
  120598. *************************************************************************
  120599. ** This file contains code for implementations of the r-tree and r*-tree
  120600. ** algorithms packaged as an SQLite virtual table module.
  120601. */
  120602. /*
  120603. ** Database Format of R-Tree Tables
  120604. ** --------------------------------
  120605. **
  120606. ** The data structure for a single virtual r-tree table is stored in three
  120607. ** native SQLite tables declared as follows. In each case, the '%' character
  120608. ** in the table name is replaced with the user-supplied name of the r-tree
  120609. ** table.
  120610. **
  120611. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  120612. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  120613. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  120614. **
  120615. ** The data for each node of the r-tree structure is stored in the %_node
  120616. ** table. For each node that is not the root node of the r-tree, there is
  120617. ** an entry in the %_parent table associating the node with its parent.
  120618. ** And for each row of data in the table, there is an entry in the %_rowid
  120619. ** table that maps from the entries rowid to the id of the node that it
  120620. ** is stored on.
  120621. **
  120622. ** The root node of an r-tree always exists, even if the r-tree table is
  120623. ** empty. The nodeno of the root node is always 1. All other nodes in the
  120624. ** table must be the same size as the root node. The content of each node
  120625. ** is formatted as follows:
  120626. **
  120627. ** 1. If the node is the root node (node 1), then the first 2 bytes
  120628. ** of the node contain the tree depth as a big-endian integer.
  120629. ** For non-root nodes, the first 2 bytes are left unused.
  120630. **
  120631. ** 2. The next 2 bytes contain the number of entries currently
  120632. ** stored in the node.
  120633. **
  120634. ** 3. The remainder of the node contains the node entries. Each entry
  120635. ** consists of a single 8-byte integer followed by an even number
  120636. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  120637. ** of a record. For internal nodes it is the node number of a
  120638. ** child page.
  120639. */
  120640. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  120641. /*
  120642. ** This file contains an implementation of a couple of different variants
  120643. ** of the r-tree algorithm. See the README file for further details. The
  120644. ** same data-structure is used for all, but the algorithms for insert and
  120645. ** delete operations vary. The variants used are selected at compile time
  120646. ** by defining the following symbols:
  120647. */
  120648. /* Either, both or none of the following may be set to activate
  120649. ** r*tree variant algorithms.
  120650. */
  120651. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  120652. #define VARIANT_RSTARTREE_REINSERT 1
  120653. /*
  120654. ** Exactly one of the following must be set to 1.
  120655. */
  120656. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  120657. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  120658. #define VARIANT_RSTARTREE_SPLIT 1
  120659. #define VARIANT_GUTTMAN_SPLIT \
  120660. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  120661. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  120662. #define PickNext QuadraticPickNext
  120663. #define PickSeeds QuadraticPickSeeds
  120664. #define AssignCells splitNodeGuttman
  120665. #endif
  120666. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  120667. #define PickNext LinearPickNext
  120668. #define PickSeeds LinearPickSeeds
  120669. #define AssignCells splitNodeGuttman
  120670. #endif
  120671. #if VARIANT_RSTARTREE_SPLIT
  120672. #define AssignCells splitNodeStartree
  120673. #endif
  120674. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  120675. # define NDEBUG 1
  120676. #endif
  120677. #ifndef SQLITE_CORE
  120678. SQLITE_EXTENSION_INIT1
  120679. #else
  120680. #endif
  120681. /* #include <string.h> */
  120682. /* #include <assert.h> */
  120683. #ifndef SQLITE_AMALGAMATION
  120684. #include "sqlite3rtree.h"
  120685. typedef sqlite3_int64 i64;
  120686. typedef unsigned char u8;
  120687. typedef unsigned int u32;
  120688. #endif
  120689. /* The following macro is used to suppress compiler warnings.
  120690. */
  120691. #ifndef UNUSED_PARAMETER
  120692. # define UNUSED_PARAMETER(x) (void)(x)
  120693. #endif
  120694. typedef struct Rtree Rtree;
  120695. typedef struct RtreeCursor RtreeCursor;
  120696. typedef struct RtreeNode RtreeNode;
  120697. typedef struct RtreeCell RtreeCell;
  120698. typedef struct RtreeConstraint RtreeConstraint;
  120699. typedef struct RtreeMatchArg RtreeMatchArg;
  120700. typedef struct RtreeGeomCallback RtreeGeomCallback;
  120701. typedef union RtreeCoord RtreeCoord;
  120702. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  120703. #define RTREE_MAX_DIMENSIONS 5
  120704. /* Size of hash table Rtree.aHash. This hash table is not expected to
  120705. ** ever contain very many entries, so a fixed number of buckets is
  120706. ** used.
  120707. */
  120708. #define HASHSIZE 128
  120709. /*
  120710. ** An rtree virtual-table object.
  120711. */
  120712. struct Rtree {
  120713. sqlite3_vtab base;
  120714. sqlite3 *db; /* Host database connection */
  120715. int iNodeSize; /* Size in bytes of each node in the node table */
  120716. int nDim; /* Number of dimensions */
  120717. int nBytesPerCell; /* Bytes consumed per cell */
  120718. int iDepth; /* Current depth of the r-tree structure */
  120719. char *zDb; /* Name of database containing r-tree table */
  120720. char *zName; /* Name of r-tree table */
  120721. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  120722. int nBusy; /* Current number of users of this structure */
  120723. /* List of nodes removed during a CondenseTree operation. List is
  120724. ** linked together via the pointer normally used for hash chains -
  120725. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  120726. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  120727. */
  120728. RtreeNode *pDeleted;
  120729. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  120730. /* Statements to read/write/delete a record from xxx_node */
  120731. sqlite3_stmt *pReadNode;
  120732. sqlite3_stmt *pWriteNode;
  120733. sqlite3_stmt *pDeleteNode;
  120734. /* Statements to read/write/delete a record from xxx_rowid */
  120735. sqlite3_stmt *pReadRowid;
  120736. sqlite3_stmt *pWriteRowid;
  120737. sqlite3_stmt *pDeleteRowid;
  120738. /* Statements to read/write/delete a record from xxx_parent */
  120739. sqlite3_stmt *pReadParent;
  120740. sqlite3_stmt *pWriteParent;
  120741. sqlite3_stmt *pDeleteParent;
  120742. int eCoordType;
  120743. };
  120744. /* Possible values for eCoordType: */
  120745. #define RTREE_COORD_REAL32 0
  120746. #define RTREE_COORD_INT32 1
  120747. /*
  120748. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  120749. ** only deal with integer coordinates. No floating point operations
  120750. ** will be done.
  120751. */
  120752. #ifdef SQLITE_RTREE_INT_ONLY
  120753. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  120754. typedef int RtreeValue; /* Low accuracy coordinate */
  120755. #else
  120756. typedef double RtreeDValue; /* High accuracy coordinate */
  120757. typedef float RtreeValue; /* Low accuracy coordinate */
  120758. #endif
  120759. /*
  120760. ** The minimum number of cells allowed for a node is a third of the
  120761. ** maximum. In Gutman's notation:
  120762. **
  120763. ** m = M/3
  120764. **
  120765. ** If an R*-tree "Reinsert" operation is required, the same number of
  120766. ** cells are removed from the overfull node and reinserted into the tree.
  120767. */
  120768. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  120769. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  120770. #define RTREE_MAXCELLS 51
  120771. /*
  120772. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  120773. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  120774. ** Therefore all non-root nodes must contain at least 3 entries. Since
  120775. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  120776. ** 40 or less.
  120777. */
  120778. #define RTREE_MAX_DEPTH 40
  120779. /*
  120780. ** An rtree cursor object.
  120781. */
  120782. struct RtreeCursor {
  120783. sqlite3_vtab_cursor base;
  120784. RtreeNode *pNode; /* Node cursor is currently pointing at */
  120785. int iCell; /* Index of current cell in pNode */
  120786. int iStrategy; /* Copy of idxNum search parameter */
  120787. int nConstraint; /* Number of entries in aConstraint */
  120788. RtreeConstraint *aConstraint; /* Search constraints. */
  120789. };
  120790. union RtreeCoord {
  120791. RtreeValue f;
  120792. int i;
  120793. };
  120794. /*
  120795. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  120796. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  120797. ** variable pRtree points to the Rtree structure associated with the
  120798. ** RtreeCoord.
  120799. */
  120800. #ifdef SQLITE_RTREE_INT_ONLY
  120801. # define DCOORD(coord) ((RtreeDValue)coord.i)
  120802. #else
  120803. # define DCOORD(coord) ( \
  120804. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  120805. ((double)coord.f) : \
  120806. ((double)coord.i) \
  120807. )
  120808. #endif
  120809. /*
  120810. ** A search constraint.
  120811. */
  120812. struct RtreeConstraint {
  120813. int iCoord; /* Index of constrained coordinate */
  120814. int op; /* Constraining operation */
  120815. RtreeDValue rValue; /* Constraint value. */
  120816. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  120817. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  120818. };
  120819. /* Possible values for RtreeConstraint.op */
  120820. #define RTREE_EQ 0x41
  120821. #define RTREE_LE 0x42
  120822. #define RTREE_LT 0x43
  120823. #define RTREE_GE 0x44
  120824. #define RTREE_GT 0x45
  120825. #define RTREE_MATCH 0x46
  120826. /*
  120827. ** An rtree structure node.
  120828. */
  120829. struct RtreeNode {
  120830. RtreeNode *pParent; /* Parent node */
  120831. i64 iNode;
  120832. int nRef;
  120833. int isDirty;
  120834. u8 *zData;
  120835. RtreeNode *pNext; /* Next node in this hash chain */
  120836. };
  120837. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  120838. /*
  120839. ** Structure to store a deserialized rtree record.
  120840. */
  120841. struct RtreeCell {
  120842. i64 iRowid;
  120843. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  120844. };
  120845. /*
  120846. ** Value for the first field of every RtreeMatchArg object. The MATCH
  120847. ** operator tests that the first field of a blob operand matches this
  120848. ** value to avoid operating on invalid blobs (which could cause a segfault).
  120849. */
  120850. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  120851. /*
  120852. ** An instance of this structure must be supplied as a blob argument to
  120853. ** the right-hand-side of an SQL MATCH operator used to constrain an
  120854. ** r-tree query.
  120855. */
  120856. struct RtreeMatchArg {
  120857. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  120858. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  120859. void *pContext;
  120860. int nParam;
  120861. RtreeDValue aParam[1];
  120862. };
  120863. /*
  120864. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  120865. ** a single instance of the following structure is allocated. It is used
  120866. ** as the context for the user-function created by by s_r_g_c(). The object
  120867. ** is eventually deleted by the destructor mechanism provided by
  120868. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  120869. ** the geometry callback function).
  120870. */
  120871. struct RtreeGeomCallback {
  120872. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  120873. void *pContext;
  120874. };
  120875. #ifndef MAX
  120876. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  120877. #endif
  120878. #ifndef MIN
  120879. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  120880. #endif
  120881. /*
  120882. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  120883. ** 64 bit integer. The deserialized value is returned.
  120884. */
  120885. static int readInt16(u8 *p){
  120886. return (p[0]<<8) + p[1];
  120887. }
  120888. static void readCoord(u8 *p, RtreeCoord *pCoord){
  120889. u32 i = (
  120890. (((u32)p[0]) << 24) +
  120891. (((u32)p[1]) << 16) +
  120892. (((u32)p[2]) << 8) +
  120893. (((u32)p[3]) << 0)
  120894. );
  120895. *(u32 *)pCoord = i;
  120896. }
  120897. static i64 readInt64(u8 *p){
  120898. return (
  120899. (((i64)p[0]) << 56) +
  120900. (((i64)p[1]) << 48) +
  120901. (((i64)p[2]) << 40) +
  120902. (((i64)p[3]) << 32) +
  120903. (((i64)p[4]) << 24) +
  120904. (((i64)p[5]) << 16) +
  120905. (((i64)p[6]) << 8) +
  120906. (((i64)p[7]) << 0)
  120907. );
  120908. }
  120909. /*
  120910. ** Functions to serialize a 16 bit integer, 32 bit real number and
  120911. ** 64 bit integer. The value returned is the number of bytes written
  120912. ** to the argument buffer (always 2, 4 and 8 respectively).
  120913. */
  120914. static int writeInt16(u8 *p, int i){
  120915. p[0] = (i>> 8)&0xFF;
  120916. p[1] = (i>> 0)&0xFF;
  120917. return 2;
  120918. }
  120919. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  120920. u32 i;
  120921. assert( sizeof(RtreeCoord)==4 );
  120922. assert( sizeof(u32)==4 );
  120923. i = *(u32 *)pCoord;
  120924. p[0] = (i>>24)&0xFF;
  120925. p[1] = (i>>16)&0xFF;
  120926. p[2] = (i>> 8)&0xFF;
  120927. p[3] = (i>> 0)&0xFF;
  120928. return 4;
  120929. }
  120930. static int writeInt64(u8 *p, i64 i){
  120931. p[0] = (i>>56)&0xFF;
  120932. p[1] = (i>>48)&0xFF;
  120933. p[2] = (i>>40)&0xFF;
  120934. p[3] = (i>>32)&0xFF;
  120935. p[4] = (i>>24)&0xFF;
  120936. p[5] = (i>>16)&0xFF;
  120937. p[6] = (i>> 8)&0xFF;
  120938. p[7] = (i>> 0)&0xFF;
  120939. return 8;
  120940. }
  120941. /*
  120942. ** Increment the reference count of node p.
  120943. */
  120944. static void nodeReference(RtreeNode *p){
  120945. if( p ){
  120946. p->nRef++;
  120947. }
  120948. }
  120949. /*
  120950. ** Clear the content of node p (set all bytes to 0x00).
  120951. */
  120952. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  120953. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  120954. p->isDirty = 1;
  120955. }
  120956. /*
  120957. ** Given a node number iNode, return the corresponding key to use
  120958. ** in the Rtree.aHash table.
  120959. */
  120960. static int nodeHash(i64 iNode){
  120961. return (
  120962. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  120963. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  120964. ) % HASHSIZE;
  120965. }
  120966. /*
  120967. ** Search the node hash table for node iNode. If found, return a pointer
  120968. ** to it. Otherwise, return 0.
  120969. */
  120970. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  120971. RtreeNode *p;
  120972. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  120973. return p;
  120974. }
  120975. /*
  120976. ** Add node pNode to the node hash table.
  120977. */
  120978. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  120979. int iHash;
  120980. assert( pNode->pNext==0 );
  120981. iHash = nodeHash(pNode->iNode);
  120982. pNode->pNext = pRtree->aHash[iHash];
  120983. pRtree->aHash[iHash] = pNode;
  120984. }
  120985. /*
  120986. ** Remove node pNode from the node hash table.
  120987. */
  120988. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  120989. RtreeNode **pp;
  120990. if( pNode->iNode!=0 ){
  120991. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  120992. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  120993. *pp = pNode->pNext;
  120994. pNode->pNext = 0;
  120995. }
  120996. }
  120997. /*
  120998. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  120999. ** indicating that node has not yet been assigned a node number. It is
  121000. ** assigned a node number when nodeWrite() is called to write the
  121001. ** node contents out to the database.
  121002. */
  121003. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  121004. RtreeNode *pNode;
  121005. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  121006. if( pNode ){
  121007. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  121008. pNode->zData = (u8 *)&pNode[1];
  121009. pNode->nRef = 1;
  121010. pNode->pParent = pParent;
  121011. pNode->isDirty = 1;
  121012. nodeReference(pParent);
  121013. }
  121014. return pNode;
  121015. }
  121016. /*
  121017. ** Obtain a reference to an r-tree node.
  121018. */
  121019. static int
  121020. nodeAcquire(
  121021. Rtree *pRtree, /* R-tree structure */
  121022. i64 iNode, /* Node number to load */
  121023. RtreeNode *pParent, /* Either the parent node or NULL */
  121024. RtreeNode **ppNode /* OUT: Acquired node */
  121025. ){
  121026. int rc;
  121027. int rc2 = SQLITE_OK;
  121028. RtreeNode *pNode;
  121029. /* Check if the requested node is already in the hash table. If so,
  121030. ** increase its reference count and return it.
  121031. */
  121032. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  121033. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  121034. if( pParent && !pNode->pParent ){
  121035. nodeReference(pParent);
  121036. pNode->pParent = pParent;
  121037. }
  121038. pNode->nRef++;
  121039. *ppNode = pNode;
  121040. return SQLITE_OK;
  121041. }
  121042. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  121043. rc = sqlite3_step(pRtree->pReadNode);
  121044. if( rc==SQLITE_ROW ){
  121045. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  121046. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  121047. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  121048. if( !pNode ){
  121049. rc2 = SQLITE_NOMEM;
  121050. }else{
  121051. pNode->pParent = pParent;
  121052. pNode->zData = (u8 *)&pNode[1];
  121053. pNode->nRef = 1;
  121054. pNode->iNode = iNode;
  121055. pNode->isDirty = 0;
  121056. pNode->pNext = 0;
  121057. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  121058. nodeReference(pParent);
  121059. }
  121060. }
  121061. }
  121062. rc = sqlite3_reset(pRtree->pReadNode);
  121063. if( rc==SQLITE_OK ) rc = rc2;
  121064. /* If the root node was just loaded, set pRtree->iDepth to the height
  121065. ** of the r-tree structure. A height of zero means all data is stored on
  121066. ** the root node. A height of one means the children of the root node
  121067. ** are the leaves, and so on. If the depth as specified on the root node
  121068. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  121069. */
  121070. if( pNode && iNode==1 ){
  121071. pRtree->iDepth = readInt16(pNode->zData);
  121072. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  121073. rc = SQLITE_CORRUPT_VTAB;
  121074. }
  121075. }
  121076. /* If no error has occurred so far, check if the "number of entries"
  121077. ** field on the node is too large. If so, set the return code to
  121078. ** SQLITE_CORRUPT_VTAB.
  121079. */
  121080. if( pNode && rc==SQLITE_OK ){
  121081. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  121082. rc = SQLITE_CORRUPT_VTAB;
  121083. }
  121084. }
  121085. if( rc==SQLITE_OK ){
  121086. if( pNode!=0 ){
  121087. nodeHashInsert(pRtree, pNode);
  121088. }else{
  121089. rc = SQLITE_CORRUPT_VTAB;
  121090. }
  121091. *ppNode = pNode;
  121092. }else{
  121093. sqlite3_free(pNode);
  121094. *ppNode = 0;
  121095. }
  121096. return rc;
  121097. }
  121098. /*
  121099. ** Overwrite cell iCell of node pNode with the contents of pCell.
  121100. */
  121101. static void nodeOverwriteCell(
  121102. Rtree *pRtree,
  121103. RtreeNode *pNode,
  121104. RtreeCell *pCell,
  121105. int iCell
  121106. ){
  121107. int ii;
  121108. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  121109. p += writeInt64(p, pCell->iRowid);
  121110. for(ii=0; ii<(pRtree->nDim*2); ii++){
  121111. p += writeCoord(p, &pCell->aCoord[ii]);
  121112. }
  121113. pNode->isDirty = 1;
  121114. }
  121115. /*
  121116. ** Remove cell the cell with index iCell from node pNode.
  121117. */
  121118. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  121119. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  121120. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  121121. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  121122. memmove(pDst, pSrc, nByte);
  121123. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  121124. pNode->isDirty = 1;
  121125. }
  121126. /*
  121127. ** Insert the contents of cell pCell into node pNode. If the insert
  121128. ** is successful, return SQLITE_OK.
  121129. **
  121130. ** If there is not enough free space in pNode, return SQLITE_FULL.
  121131. */
  121132. static int
  121133. nodeInsertCell(
  121134. Rtree *pRtree,
  121135. RtreeNode *pNode,
  121136. RtreeCell *pCell
  121137. ){
  121138. int nCell; /* Current number of cells in pNode */
  121139. int nMaxCell; /* Maximum number of cells for pNode */
  121140. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  121141. nCell = NCELL(pNode);
  121142. assert( nCell<=nMaxCell );
  121143. if( nCell<nMaxCell ){
  121144. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  121145. writeInt16(&pNode->zData[2], nCell+1);
  121146. pNode->isDirty = 1;
  121147. }
  121148. return (nCell==nMaxCell);
  121149. }
  121150. /*
  121151. ** If the node is dirty, write it out to the database.
  121152. */
  121153. static int
  121154. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  121155. int rc = SQLITE_OK;
  121156. if( pNode->isDirty ){
  121157. sqlite3_stmt *p = pRtree->pWriteNode;
  121158. if( pNode->iNode ){
  121159. sqlite3_bind_int64(p, 1, pNode->iNode);
  121160. }else{
  121161. sqlite3_bind_null(p, 1);
  121162. }
  121163. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  121164. sqlite3_step(p);
  121165. pNode->isDirty = 0;
  121166. rc = sqlite3_reset(p);
  121167. if( pNode->iNode==0 && rc==SQLITE_OK ){
  121168. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  121169. nodeHashInsert(pRtree, pNode);
  121170. }
  121171. }
  121172. return rc;
  121173. }
  121174. /*
  121175. ** Release a reference to a node. If the node is dirty and the reference
  121176. ** count drops to zero, the node data is written to the database.
  121177. */
  121178. static int
  121179. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  121180. int rc = SQLITE_OK;
  121181. if( pNode ){
  121182. assert( pNode->nRef>0 );
  121183. pNode->nRef--;
  121184. if( pNode->nRef==0 ){
  121185. if( pNode->iNode==1 ){
  121186. pRtree->iDepth = -1;
  121187. }
  121188. if( pNode->pParent ){
  121189. rc = nodeRelease(pRtree, pNode->pParent);
  121190. }
  121191. if( rc==SQLITE_OK ){
  121192. rc = nodeWrite(pRtree, pNode);
  121193. }
  121194. nodeHashDelete(pRtree, pNode);
  121195. sqlite3_free(pNode);
  121196. }
  121197. }
  121198. return rc;
  121199. }
  121200. /*
  121201. ** Return the 64-bit integer value associated with cell iCell of
  121202. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  121203. ** an internal node, then the 64-bit integer is a child page number.
  121204. */
  121205. static i64 nodeGetRowid(
  121206. Rtree *pRtree,
  121207. RtreeNode *pNode,
  121208. int iCell
  121209. ){
  121210. assert( iCell<NCELL(pNode) );
  121211. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  121212. }
  121213. /*
  121214. ** Return coordinate iCoord from cell iCell in node pNode.
  121215. */
  121216. static void nodeGetCoord(
  121217. Rtree *pRtree,
  121218. RtreeNode *pNode,
  121219. int iCell,
  121220. int iCoord,
  121221. RtreeCoord *pCoord /* Space to write result to */
  121222. ){
  121223. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  121224. }
  121225. /*
  121226. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  121227. ** to by pCell with the results.
  121228. */
  121229. static void nodeGetCell(
  121230. Rtree *pRtree,
  121231. RtreeNode *pNode,
  121232. int iCell,
  121233. RtreeCell *pCell
  121234. ){
  121235. int ii;
  121236. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  121237. for(ii=0; ii<pRtree->nDim*2; ii++){
  121238. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  121239. }
  121240. }
  121241. /* Forward declaration for the function that does the work of
  121242. ** the virtual table module xCreate() and xConnect() methods.
  121243. */
  121244. static int rtreeInit(
  121245. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  121246. );
  121247. /*
  121248. ** Rtree virtual table module xCreate method.
  121249. */
  121250. static int rtreeCreate(
  121251. sqlite3 *db,
  121252. void *pAux,
  121253. int argc, const char *const*argv,
  121254. sqlite3_vtab **ppVtab,
  121255. char **pzErr
  121256. ){
  121257. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  121258. }
  121259. /*
  121260. ** Rtree virtual table module xConnect method.
  121261. */
  121262. static int rtreeConnect(
  121263. sqlite3 *db,
  121264. void *pAux,
  121265. int argc, const char *const*argv,
  121266. sqlite3_vtab **ppVtab,
  121267. char **pzErr
  121268. ){
  121269. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  121270. }
  121271. /*
  121272. ** Increment the r-tree reference count.
  121273. */
  121274. static void rtreeReference(Rtree *pRtree){
  121275. pRtree->nBusy++;
  121276. }
  121277. /*
  121278. ** Decrement the r-tree reference count. When the reference count reaches
  121279. ** zero the structure is deleted.
  121280. */
  121281. static void rtreeRelease(Rtree *pRtree){
  121282. pRtree->nBusy--;
  121283. if( pRtree->nBusy==0 ){
  121284. sqlite3_finalize(pRtree->pReadNode);
  121285. sqlite3_finalize(pRtree->pWriteNode);
  121286. sqlite3_finalize(pRtree->pDeleteNode);
  121287. sqlite3_finalize(pRtree->pReadRowid);
  121288. sqlite3_finalize(pRtree->pWriteRowid);
  121289. sqlite3_finalize(pRtree->pDeleteRowid);
  121290. sqlite3_finalize(pRtree->pReadParent);
  121291. sqlite3_finalize(pRtree->pWriteParent);
  121292. sqlite3_finalize(pRtree->pDeleteParent);
  121293. sqlite3_free(pRtree);
  121294. }
  121295. }
  121296. /*
  121297. ** Rtree virtual table module xDisconnect method.
  121298. */
  121299. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  121300. rtreeRelease((Rtree *)pVtab);
  121301. return SQLITE_OK;
  121302. }
  121303. /*
  121304. ** Rtree virtual table module xDestroy method.
  121305. */
  121306. static int rtreeDestroy(sqlite3_vtab *pVtab){
  121307. Rtree *pRtree = (Rtree *)pVtab;
  121308. int rc;
  121309. char *zCreate = sqlite3_mprintf(
  121310. "DROP TABLE '%q'.'%q_node';"
  121311. "DROP TABLE '%q'.'%q_rowid';"
  121312. "DROP TABLE '%q'.'%q_parent';",
  121313. pRtree->zDb, pRtree->zName,
  121314. pRtree->zDb, pRtree->zName,
  121315. pRtree->zDb, pRtree->zName
  121316. );
  121317. if( !zCreate ){
  121318. rc = SQLITE_NOMEM;
  121319. }else{
  121320. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  121321. sqlite3_free(zCreate);
  121322. }
  121323. if( rc==SQLITE_OK ){
  121324. rtreeRelease(pRtree);
  121325. }
  121326. return rc;
  121327. }
  121328. /*
  121329. ** Rtree virtual table module xOpen method.
  121330. */
  121331. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  121332. int rc = SQLITE_NOMEM;
  121333. RtreeCursor *pCsr;
  121334. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  121335. if( pCsr ){
  121336. memset(pCsr, 0, sizeof(RtreeCursor));
  121337. pCsr->base.pVtab = pVTab;
  121338. rc = SQLITE_OK;
  121339. }
  121340. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  121341. return rc;
  121342. }
  121343. /*
  121344. ** Free the RtreeCursor.aConstraint[] array and its contents.
  121345. */
  121346. static void freeCursorConstraints(RtreeCursor *pCsr){
  121347. if( pCsr->aConstraint ){
  121348. int i; /* Used to iterate through constraint array */
  121349. for(i=0; i<pCsr->nConstraint; i++){
  121350. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  121351. if( pGeom ){
  121352. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  121353. sqlite3_free(pGeom);
  121354. }
  121355. }
  121356. sqlite3_free(pCsr->aConstraint);
  121357. pCsr->aConstraint = 0;
  121358. }
  121359. }
  121360. /*
  121361. ** Rtree virtual table module xClose method.
  121362. */
  121363. static int rtreeClose(sqlite3_vtab_cursor *cur){
  121364. Rtree *pRtree = (Rtree *)(cur->pVtab);
  121365. int rc;
  121366. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121367. freeCursorConstraints(pCsr);
  121368. rc = nodeRelease(pRtree, pCsr->pNode);
  121369. sqlite3_free(pCsr);
  121370. return rc;
  121371. }
  121372. /*
  121373. ** Rtree virtual table module xEof method.
  121374. **
  121375. ** Return non-zero if the cursor does not currently point to a valid
  121376. ** record (i.e if the scan has finished), or zero otherwise.
  121377. */
  121378. static int rtreeEof(sqlite3_vtab_cursor *cur){
  121379. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121380. return (pCsr->pNode==0);
  121381. }
  121382. /*
  121383. ** The r-tree constraint passed as the second argument to this function is
  121384. ** guaranteed to be a MATCH constraint.
  121385. */
  121386. static int testRtreeGeom(
  121387. Rtree *pRtree, /* R-Tree object */
  121388. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  121389. RtreeCell *pCell, /* Cell to test */
  121390. int *pbRes /* OUT: Test result */
  121391. ){
  121392. int i;
  121393. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  121394. int nCoord = pRtree->nDim*2;
  121395. assert( pConstraint->op==RTREE_MATCH );
  121396. assert( pConstraint->pGeom );
  121397. for(i=0; i<nCoord; i++){
  121398. aCoord[i] = DCOORD(pCell->aCoord[i]);
  121399. }
  121400. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  121401. }
  121402. /*
  121403. ** Cursor pCursor currently points to a cell in a non-leaf page.
  121404. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  121405. ** (excluded) by the constraints in the pCursor->aConstraint[]
  121406. ** array, or false otherwise.
  121407. **
  121408. ** Return SQLITE_OK if successful or an SQLite error code if an error
  121409. ** occurs within a geometry callback.
  121410. */
  121411. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  121412. RtreeCell cell;
  121413. int ii;
  121414. int bRes = 0;
  121415. int rc = SQLITE_OK;
  121416. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  121417. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  121418. RtreeConstraint *p = &pCursor->aConstraint[ii];
  121419. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  121420. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  121421. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  121422. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  121423. );
  121424. switch( p->op ){
  121425. case RTREE_LE: case RTREE_LT:
  121426. bRes = p->rValue<cell_min;
  121427. break;
  121428. case RTREE_GE: case RTREE_GT:
  121429. bRes = p->rValue>cell_max;
  121430. break;
  121431. case RTREE_EQ:
  121432. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  121433. break;
  121434. default: {
  121435. assert( p->op==RTREE_MATCH );
  121436. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  121437. bRes = !bRes;
  121438. break;
  121439. }
  121440. }
  121441. }
  121442. *pbEof = bRes;
  121443. return rc;
  121444. }
  121445. /*
  121446. ** Test if the cell that cursor pCursor currently points to
  121447. ** would be filtered (excluded) by the constraints in the
  121448. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  121449. ** returning. If the cell is not filtered (excluded) by the constraints,
  121450. ** set pbEof to zero.
  121451. **
  121452. ** Return SQLITE_OK if successful or an SQLite error code if an error
  121453. ** occurs within a geometry callback.
  121454. **
  121455. ** This function assumes that the cell is part of a leaf node.
  121456. */
  121457. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  121458. RtreeCell cell;
  121459. int ii;
  121460. *pbEof = 0;
  121461. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  121462. for(ii=0; ii<pCursor->nConstraint; ii++){
  121463. RtreeConstraint *p = &pCursor->aConstraint[ii];
  121464. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  121465. int res;
  121466. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  121467. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  121468. );
  121469. switch( p->op ){
  121470. case RTREE_LE: res = (coord<=p->rValue); break;
  121471. case RTREE_LT: res = (coord<p->rValue); break;
  121472. case RTREE_GE: res = (coord>=p->rValue); break;
  121473. case RTREE_GT: res = (coord>p->rValue); break;
  121474. case RTREE_EQ: res = (coord==p->rValue); break;
  121475. default: {
  121476. int rc;
  121477. assert( p->op==RTREE_MATCH );
  121478. rc = testRtreeGeom(pRtree, p, &cell, &res);
  121479. if( rc!=SQLITE_OK ){
  121480. return rc;
  121481. }
  121482. break;
  121483. }
  121484. }
  121485. if( !res ){
  121486. *pbEof = 1;
  121487. return SQLITE_OK;
  121488. }
  121489. }
  121490. return SQLITE_OK;
  121491. }
  121492. /*
  121493. ** Cursor pCursor currently points at a node that heads a sub-tree of
  121494. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  121495. ** to point to the left-most cell of the sub-tree that matches the
  121496. ** configured constraints.
  121497. */
  121498. static int descendToCell(
  121499. Rtree *pRtree,
  121500. RtreeCursor *pCursor,
  121501. int iHeight,
  121502. int *pEof /* OUT: Set to true if cannot descend */
  121503. ){
  121504. int isEof;
  121505. int rc;
  121506. int ii;
  121507. RtreeNode *pChild;
  121508. sqlite3_int64 iRowid;
  121509. RtreeNode *pSavedNode = pCursor->pNode;
  121510. int iSavedCell = pCursor->iCell;
  121511. assert( iHeight>=0 );
  121512. if( iHeight==0 ){
  121513. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  121514. }else{
  121515. rc = testRtreeCell(pRtree, pCursor, &isEof);
  121516. }
  121517. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  121518. goto descend_to_cell_out;
  121519. }
  121520. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  121521. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  121522. if( rc!=SQLITE_OK ){
  121523. goto descend_to_cell_out;
  121524. }
  121525. nodeRelease(pRtree, pCursor->pNode);
  121526. pCursor->pNode = pChild;
  121527. isEof = 1;
  121528. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  121529. pCursor->iCell = ii;
  121530. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  121531. if( rc!=SQLITE_OK ){
  121532. goto descend_to_cell_out;
  121533. }
  121534. }
  121535. if( isEof ){
  121536. assert( pCursor->pNode==pChild );
  121537. nodeReference(pSavedNode);
  121538. nodeRelease(pRtree, pChild);
  121539. pCursor->pNode = pSavedNode;
  121540. pCursor->iCell = iSavedCell;
  121541. }
  121542. descend_to_cell_out:
  121543. *pEof = isEof;
  121544. return rc;
  121545. }
  121546. /*
  121547. ** One of the cells in node pNode is guaranteed to have a 64-bit
  121548. ** integer value equal to iRowid. Return the index of this cell.
  121549. */
  121550. static int nodeRowidIndex(
  121551. Rtree *pRtree,
  121552. RtreeNode *pNode,
  121553. i64 iRowid,
  121554. int *piIndex
  121555. ){
  121556. int ii;
  121557. int nCell = NCELL(pNode);
  121558. for(ii=0; ii<nCell; ii++){
  121559. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  121560. *piIndex = ii;
  121561. return SQLITE_OK;
  121562. }
  121563. }
  121564. return SQLITE_CORRUPT_VTAB;
  121565. }
  121566. /*
  121567. ** Return the index of the cell containing a pointer to node pNode
  121568. ** in its parent. If pNode is the root node, return -1.
  121569. */
  121570. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  121571. RtreeNode *pParent = pNode->pParent;
  121572. if( pParent ){
  121573. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  121574. }
  121575. *piIndex = -1;
  121576. return SQLITE_OK;
  121577. }
  121578. /*
  121579. ** Rtree virtual table module xNext method.
  121580. */
  121581. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  121582. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  121583. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121584. int rc = SQLITE_OK;
  121585. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  121586. ** already at EOF. It is against the rules to call the xNext() method of
  121587. ** a cursor that has already reached EOF.
  121588. */
  121589. assert( pCsr->pNode );
  121590. if( pCsr->iStrategy==1 ){
  121591. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  121592. nodeRelease(pRtree, pCsr->pNode);
  121593. pCsr->pNode = 0;
  121594. }else{
  121595. /* Move to the next entry that matches the configured constraints. */
  121596. int iHeight = 0;
  121597. while( pCsr->pNode ){
  121598. RtreeNode *pNode = pCsr->pNode;
  121599. int nCell = NCELL(pNode);
  121600. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  121601. int isEof;
  121602. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  121603. if( rc!=SQLITE_OK || !isEof ){
  121604. return rc;
  121605. }
  121606. }
  121607. pCsr->pNode = pNode->pParent;
  121608. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  121609. if( rc!=SQLITE_OK ){
  121610. return rc;
  121611. }
  121612. nodeReference(pCsr->pNode);
  121613. nodeRelease(pRtree, pNode);
  121614. iHeight++;
  121615. }
  121616. }
  121617. return rc;
  121618. }
  121619. /*
  121620. ** Rtree virtual table module xRowid method.
  121621. */
  121622. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  121623. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  121624. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121625. assert(pCsr->pNode);
  121626. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  121627. return SQLITE_OK;
  121628. }
  121629. /*
  121630. ** Rtree virtual table module xColumn method.
  121631. */
  121632. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  121633. Rtree *pRtree = (Rtree *)cur->pVtab;
  121634. RtreeCursor *pCsr = (RtreeCursor *)cur;
  121635. if( i==0 ){
  121636. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  121637. sqlite3_result_int64(ctx, iRowid);
  121638. }else{
  121639. RtreeCoord c;
  121640. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  121641. #ifndef SQLITE_RTREE_INT_ONLY
  121642. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  121643. sqlite3_result_double(ctx, c.f);
  121644. }else
  121645. #endif
  121646. {
  121647. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  121648. sqlite3_result_int(ctx, c.i);
  121649. }
  121650. }
  121651. return SQLITE_OK;
  121652. }
  121653. /*
  121654. ** Use nodeAcquire() to obtain the leaf node containing the record with
  121655. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  121656. ** return SQLITE_OK. If there is no such record in the table, set
  121657. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  121658. ** to zero and return an SQLite error code.
  121659. */
  121660. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  121661. int rc;
  121662. *ppLeaf = 0;
  121663. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  121664. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  121665. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  121666. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  121667. sqlite3_reset(pRtree->pReadRowid);
  121668. }else{
  121669. rc = sqlite3_reset(pRtree->pReadRowid);
  121670. }
  121671. return rc;
  121672. }
  121673. /*
  121674. ** This function is called to configure the RtreeConstraint object passed
  121675. ** as the second argument for a MATCH constraint. The value passed as the
  121676. ** first argument to this function is the right-hand operand to the MATCH
  121677. ** operator.
  121678. */
  121679. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  121680. RtreeMatchArg *p;
  121681. sqlite3_rtree_geometry *pGeom;
  121682. int nBlob;
  121683. /* Check that value is actually a blob. */
  121684. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  121685. /* Check that the blob is roughly the right size. */
  121686. nBlob = sqlite3_value_bytes(pValue);
  121687. if( nBlob<(int)sizeof(RtreeMatchArg)
  121688. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  121689. ){
  121690. return SQLITE_ERROR;
  121691. }
  121692. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  121693. sizeof(sqlite3_rtree_geometry) + nBlob
  121694. );
  121695. if( !pGeom ) return SQLITE_NOMEM;
  121696. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  121697. p = (RtreeMatchArg *)&pGeom[1];
  121698. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  121699. if( p->magic!=RTREE_GEOMETRY_MAGIC
  121700. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  121701. ){
  121702. sqlite3_free(pGeom);
  121703. return SQLITE_ERROR;
  121704. }
  121705. pGeom->pContext = p->pContext;
  121706. pGeom->nParam = p->nParam;
  121707. pGeom->aParam = p->aParam;
  121708. pCons->xGeom = p->xGeom;
  121709. pCons->pGeom = pGeom;
  121710. return SQLITE_OK;
  121711. }
  121712. /*
  121713. ** Rtree virtual table module xFilter method.
  121714. */
  121715. static int rtreeFilter(
  121716. sqlite3_vtab_cursor *pVtabCursor,
  121717. int idxNum, const char *idxStr,
  121718. int argc, sqlite3_value **argv
  121719. ){
  121720. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  121721. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  121722. RtreeNode *pRoot = 0;
  121723. int ii;
  121724. int rc = SQLITE_OK;
  121725. rtreeReference(pRtree);
  121726. freeCursorConstraints(pCsr);
  121727. pCsr->iStrategy = idxNum;
  121728. if( idxNum==1 ){
  121729. /* Special case - lookup by rowid. */
  121730. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  121731. i64 iRowid = sqlite3_value_int64(argv[0]);
  121732. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  121733. pCsr->pNode = pLeaf;
  121734. if( pLeaf ){
  121735. assert( rc==SQLITE_OK );
  121736. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  121737. }
  121738. }else{
  121739. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  121740. ** with the configured constraints.
  121741. */
  121742. if( argc>0 ){
  121743. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  121744. pCsr->nConstraint = argc;
  121745. if( !pCsr->aConstraint ){
  121746. rc = SQLITE_NOMEM;
  121747. }else{
  121748. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  121749. assert( (idxStr==0 && argc==0)
  121750. || (idxStr && (int)strlen(idxStr)==argc*2) );
  121751. for(ii=0; ii<argc; ii++){
  121752. RtreeConstraint *p = &pCsr->aConstraint[ii];
  121753. p->op = idxStr[ii*2];
  121754. p->iCoord = idxStr[ii*2+1]-'a';
  121755. if( p->op==RTREE_MATCH ){
  121756. /* A MATCH operator. The right-hand-side must be a blob that
  121757. ** can be cast into an RtreeMatchArg object. One created using
  121758. ** an sqlite3_rtree_geometry_callback() SQL user function.
  121759. */
  121760. rc = deserializeGeometry(argv[ii], p);
  121761. if( rc!=SQLITE_OK ){
  121762. break;
  121763. }
  121764. }else{
  121765. #ifdef SQLITE_RTREE_INT_ONLY
  121766. p->rValue = sqlite3_value_int64(argv[ii]);
  121767. #else
  121768. p->rValue = sqlite3_value_double(argv[ii]);
  121769. #endif
  121770. }
  121771. }
  121772. }
  121773. }
  121774. if( rc==SQLITE_OK ){
  121775. pCsr->pNode = 0;
  121776. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  121777. }
  121778. if( rc==SQLITE_OK ){
  121779. int isEof = 1;
  121780. int nCell = NCELL(pRoot);
  121781. pCsr->pNode = pRoot;
  121782. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  121783. assert( pCsr->pNode==pRoot );
  121784. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  121785. if( !isEof ){
  121786. break;
  121787. }
  121788. }
  121789. if( rc==SQLITE_OK && isEof ){
  121790. assert( pCsr->pNode==pRoot );
  121791. nodeRelease(pRtree, pRoot);
  121792. pCsr->pNode = 0;
  121793. }
  121794. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  121795. }
  121796. }
  121797. rtreeRelease(pRtree);
  121798. return rc;
  121799. }
  121800. /*
  121801. ** Rtree virtual table module xBestIndex method. There are three
  121802. ** table scan strategies to choose from (in order from most to
  121803. ** least desirable):
  121804. **
  121805. ** idxNum idxStr Strategy
  121806. ** ------------------------------------------------
  121807. ** 1 Unused Direct lookup by rowid.
  121808. ** 2 See below R-tree query or full-table scan.
  121809. ** ------------------------------------------------
  121810. **
  121811. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  121812. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  121813. ** constraint used. The first two bytes of idxStr correspond to
  121814. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  121815. ** (argvIndex==1) etc.
  121816. **
  121817. ** The first of each pair of bytes in idxStr identifies the constraint
  121818. ** operator as follows:
  121819. **
  121820. ** Operator Byte Value
  121821. ** ----------------------
  121822. ** = 0x41 ('A')
  121823. ** <= 0x42 ('B')
  121824. ** < 0x43 ('C')
  121825. ** >= 0x44 ('D')
  121826. ** > 0x45 ('E')
  121827. ** MATCH 0x46 ('F')
  121828. ** ----------------------
  121829. **
  121830. ** The second of each pair of bytes identifies the coordinate column
  121831. ** to which the constraint applies. The leftmost coordinate column
  121832. ** is 'a', the second from the left 'b' etc.
  121833. */
  121834. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  121835. int rc = SQLITE_OK;
  121836. int ii;
  121837. int iIdx = 0;
  121838. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  121839. memset(zIdxStr, 0, sizeof(zIdxStr));
  121840. UNUSED_PARAMETER(tab);
  121841. assert( pIdxInfo->idxStr==0 );
  121842. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  121843. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  121844. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  121845. /* We have an equality constraint on the rowid. Use strategy 1. */
  121846. int jj;
  121847. for(jj=0; jj<ii; jj++){
  121848. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  121849. pIdxInfo->aConstraintUsage[jj].omit = 0;
  121850. }
  121851. pIdxInfo->idxNum = 1;
  121852. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  121853. pIdxInfo->aConstraintUsage[jj].omit = 1;
  121854. /* This strategy involves a two rowid lookups on an B-Tree structures
  121855. ** and then a linear search of an R-Tree node. This should be
  121856. ** considered almost as quick as a direct rowid lookup (for which
  121857. ** sqlite uses an internal cost of 0.0).
  121858. */
  121859. pIdxInfo->estimatedCost = 10.0;
  121860. return SQLITE_OK;
  121861. }
  121862. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  121863. u8 op;
  121864. switch( p->op ){
  121865. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  121866. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  121867. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  121868. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  121869. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  121870. default:
  121871. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  121872. op = RTREE_MATCH;
  121873. break;
  121874. }
  121875. zIdxStr[iIdx++] = op;
  121876. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  121877. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  121878. pIdxInfo->aConstraintUsage[ii].omit = 1;
  121879. }
  121880. }
  121881. pIdxInfo->idxNum = 2;
  121882. pIdxInfo->needToFreeIdxStr = 1;
  121883. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  121884. return SQLITE_NOMEM;
  121885. }
  121886. assert( iIdx>=0 );
  121887. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  121888. return rc;
  121889. }
  121890. /*
  121891. ** Return the N-dimensional volumn of the cell stored in *p.
  121892. */
  121893. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  121894. RtreeDValue area = (RtreeDValue)1;
  121895. int ii;
  121896. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121897. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  121898. }
  121899. return area;
  121900. }
  121901. /*
  121902. ** Return the margin length of cell p. The margin length is the sum
  121903. ** of the objects size in each dimension.
  121904. */
  121905. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  121906. RtreeDValue margin = (RtreeDValue)0;
  121907. int ii;
  121908. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121909. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  121910. }
  121911. return margin;
  121912. }
  121913. /*
  121914. ** Store the union of cells p1 and p2 in p1.
  121915. */
  121916. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  121917. int ii;
  121918. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  121919. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121920. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  121921. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  121922. }
  121923. }else{
  121924. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121925. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  121926. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  121927. }
  121928. }
  121929. }
  121930. /*
  121931. ** Return true if the area covered by p2 is a subset of the area covered
  121932. ** by p1. False otherwise.
  121933. */
  121934. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  121935. int ii;
  121936. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  121937. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  121938. RtreeCoord *a1 = &p1->aCoord[ii];
  121939. RtreeCoord *a2 = &p2->aCoord[ii];
  121940. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  121941. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  121942. ){
  121943. return 0;
  121944. }
  121945. }
  121946. return 1;
  121947. }
  121948. /*
  121949. ** Return the amount cell p would grow by if it were unioned with pCell.
  121950. */
  121951. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  121952. RtreeDValue area;
  121953. RtreeCell cell;
  121954. memcpy(&cell, p, sizeof(RtreeCell));
  121955. area = cellArea(pRtree, &cell);
  121956. cellUnion(pRtree, &cell, pCell);
  121957. return (cellArea(pRtree, &cell)-area);
  121958. }
  121959. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  121960. static RtreeDValue cellOverlap(
  121961. Rtree *pRtree,
  121962. RtreeCell *p,
  121963. RtreeCell *aCell,
  121964. int nCell,
  121965. int iExclude
  121966. ){
  121967. int ii;
  121968. RtreeDValue overlap = 0.0;
  121969. for(ii=0; ii<nCell; ii++){
  121970. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  121971. if( ii!=iExclude )
  121972. #else
  121973. assert( iExclude==-1 );
  121974. UNUSED_PARAMETER(iExclude);
  121975. #endif
  121976. {
  121977. int jj;
  121978. RtreeDValue o = (RtreeDValue)1;
  121979. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  121980. RtreeDValue x1, x2;
  121981. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  121982. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  121983. if( x2<x1 ){
  121984. o = 0.0;
  121985. break;
  121986. }else{
  121987. o = o * (x2-x1);
  121988. }
  121989. }
  121990. overlap += o;
  121991. }
  121992. }
  121993. return overlap;
  121994. }
  121995. #endif
  121996. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  121997. static RtreeDValue cellOverlapEnlargement(
  121998. Rtree *pRtree,
  121999. RtreeCell *p,
  122000. RtreeCell *pInsert,
  122001. RtreeCell *aCell,
  122002. int nCell,
  122003. int iExclude
  122004. ){
  122005. RtreeDValue before, after;
  122006. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  122007. cellUnion(pRtree, p, pInsert);
  122008. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  122009. return (after-before);
  122010. }
  122011. #endif
  122012. /*
  122013. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  122014. ** ChooseSubTree in r*tree terminology.
  122015. */
  122016. static int ChooseLeaf(
  122017. Rtree *pRtree, /* Rtree table */
  122018. RtreeCell *pCell, /* Cell to insert into rtree */
  122019. int iHeight, /* Height of sub-tree rooted at pCell */
  122020. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  122021. ){
  122022. int rc;
  122023. int ii;
  122024. RtreeNode *pNode;
  122025. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  122026. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  122027. int iCell;
  122028. sqlite3_int64 iBest = 0;
  122029. RtreeDValue fMinGrowth = 0.0;
  122030. RtreeDValue fMinArea = 0.0;
  122031. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122032. RtreeDValue fMinOverlap = 0.0;
  122033. RtreeDValue overlap;
  122034. #endif
  122035. int nCell = NCELL(pNode);
  122036. RtreeCell cell;
  122037. RtreeNode *pChild;
  122038. RtreeCell *aCell = 0;
  122039. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122040. if( ii==(pRtree->iDepth-1) ){
  122041. int jj;
  122042. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  122043. if( !aCell ){
  122044. rc = SQLITE_NOMEM;
  122045. nodeRelease(pRtree, pNode);
  122046. pNode = 0;
  122047. continue;
  122048. }
  122049. for(jj=0; jj<nCell; jj++){
  122050. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  122051. }
  122052. }
  122053. #endif
  122054. /* Select the child node which will be enlarged the least if pCell
  122055. ** is inserted into it. Resolve ties by choosing the entry with
  122056. ** the smallest area.
  122057. */
  122058. for(iCell=0; iCell<nCell; iCell++){
  122059. int bBest = 0;
  122060. RtreeDValue growth;
  122061. RtreeDValue area;
  122062. nodeGetCell(pRtree, pNode, iCell, &cell);
  122063. growth = cellGrowth(pRtree, &cell, pCell);
  122064. area = cellArea(pRtree, &cell);
  122065. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  122066. if( ii==(pRtree->iDepth-1) ){
  122067. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  122068. }else{
  122069. overlap = 0.0;
  122070. }
  122071. if( (iCell==0)
  122072. || (overlap<fMinOverlap)
  122073. || (overlap==fMinOverlap && growth<fMinGrowth)
  122074. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  122075. ){
  122076. bBest = 1;
  122077. fMinOverlap = overlap;
  122078. }
  122079. #else
  122080. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  122081. bBest = 1;
  122082. }
  122083. #endif
  122084. if( bBest ){
  122085. fMinGrowth = growth;
  122086. fMinArea = area;
  122087. iBest = cell.iRowid;
  122088. }
  122089. }
  122090. sqlite3_free(aCell);
  122091. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  122092. nodeRelease(pRtree, pNode);
  122093. pNode = pChild;
  122094. }
  122095. *ppLeaf = pNode;
  122096. return rc;
  122097. }
  122098. /*
  122099. ** A cell with the same content as pCell has just been inserted into
  122100. ** the node pNode. This function updates the bounding box cells in
  122101. ** all ancestor elements.
  122102. */
  122103. static int AdjustTree(
  122104. Rtree *pRtree, /* Rtree table */
  122105. RtreeNode *pNode, /* Adjust ancestry of this node. */
  122106. RtreeCell *pCell /* This cell was just inserted */
  122107. ){
  122108. RtreeNode *p = pNode;
  122109. while( p->pParent ){
  122110. RtreeNode *pParent = p->pParent;
  122111. RtreeCell cell;
  122112. int iCell;
  122113. if( nodeParentIndex(pRtree, p, &iCell) ){
  122114. return SQLITE_CORRUPT_VTAB;
  122115. }
  122116. nodeGetCell(pRtree, pParent, iCell, &cell);
  122117. if( !cellContains(pRtree, &cell, pCell) ){
  122118. cellUnion(pRtree, &cell, pCell);
  122119. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  122120. }
  122121. p = pParent;
  122122. }
  122123. return SQLITE_OK;
  122124. }
  122125. /*
  122126. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  122127. */
  122128. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  122129. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  122130. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  122131. sqlite3_step(pRtree->pWriteRowid);
  122132. return sqlite3_reset(pRtree->pWriteRowid);
  122133. }
  122134. /*
  122135. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  122136. */
  122137. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  122138. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  122139. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  122140. sqlite3_step(pRtree->pWriteParent);
  122141. return sqlite3_reset(pRtree->pWriteParent);
  122142. }
  122143. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  122144. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  122145. /*
  122146. ** Implementation of the linear variant of the PickNext() function from
  122147. ** Guttman[84].
  122148. */
  122149. static RtreeCell *LinearPickNext(
  122150. Rtree *pRtree,
  122151. RtreeCell *aCell,
  122152. int nCell,
  122153. RtreeCell *pLeftBox,
  122154. RtreeCell *pRightBox,
  122155. int *aiUsed
  122156. ){
  122157. int ii;
  122158. for(ii=0; aiUsed[ii]; ii++);
  122159. aiUsed[ii] = 1;
  122160. return &aCell[ii];
  122161. }
  122162. /*
  122163. ** Implementation of the linear variant of the PickSeeds() function from
  122164. ** Guttman[84].
  122165. */
  122166. static void LinearPickSeeds(
  122167. Rtree *pRtree,
  122168. RtreeCell *aCell,
  122169. int nCell,
  122170. int *piLeftSeed,
  122171. int *piRightSeed
  122172. ){
  122173. int i;
  122174. int iLeftSeed = 0;
  122175. int iRightSeed = 1;
  122176. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  122177. /* Pick two "seed" cells from the array of cells. The algorithm used
  122178. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  122179. ** indices of the two seed cells in the array are stored in local
  122180. ** variables iLeftSeek and iRightSeed.
  122181. */
  122182. for(i=0; i<pRtree->nDim; i++){
  122183. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  122184. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  122185. RtreeDValue x3 = x1;
  122186. RtreeDValue x4 = x2;
  122187. int jj;
  122188. int iCellLeft = 0;
  122189. int iCellRight = 0;
  122190. for(jj=1; jj<nCell; jj++){
  122191. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  122192. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  122193. if( left<x1 ) x1 = left;
  122194. if( right>x4 ) x4 = right;
  122195. if( left>x3 ){
  122196. x3 = left;
  122197. iCellRight = jj;
  122198. }
  122199. if( right<x2 ){
  122200. x2 = right;
  122201. iCellLeft = jj;
  122202. }
  122203. }
  122204. if( x4!=x1 ){
  122205. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  122206. if( normalwidth>maxNormalInnerWidth ){
  122207. iLeftSeed = iCellLeft;
  122208. iRightSeed = iCellRight;
  122209. }
  122210. }
  122211. }
  122212. *piLeftSeed = iLeftSeed;
  122213. *piRightSeed = iRightSeed;
  122214. }
  122215. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  122216. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  122217. /*
  122218. ** Implementation of the quadratic variant of the PickNext() function from
  122219. ** Guttman[84].
  122220. */
  122221. static RtreeCell *QuadraticPickNext(
  122222. Rtree *pRtree,
  122223. RtreeCell *aCell,
  122224. int nCell,
  122225. RtreeCell *pLeftBox,
  122226. RtreeCell *pRightBox,
  122227. int *aiUsed
  122228. ){
  122229. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  122230. int iSelect = -1;
  122231. RtreeDValue fDiff;
  122232. int ii;
  122233. for(ii=0; ii<nCell; ii++){
  122234. if( aiUsed[ii]==0 ){
  122235. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  122236. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  122237. RtreeDValue diff = FABS(right-left);
  122238. if( iSelect<0 || diff>fDiff ){
  122239. fDiff = diff;
  122240. iSelect = ii;
  122241. }
  122242. }
  122243. }
  122244. aiUsed[iSelect] = 1;
  122245. return &aCell[iSelect];
  122246. }
  122247. /*
  122248. ** Implementation of the quadratic variant of the PickSeeds() function from
  122249. ** Guttman[84].
  122250. */
  122251. static void QuadraticPickSeeds(
  122252. Rtree *pRtree,
  122253. RtreeCell *aCell,
  122254. int nCell,
  122255. int *piLeftSeed,
  122256. int *piRightSeed
  122257. ){
  122258. int ii;
  122259. int jj;
  122260. int iLeftSeed = 0;
  122261. int iRightSeed = 1;
  122262. RtreeDValue fWaste = 0.0;
  122263. for(ii=0; ii<nCell; ii++){
  122264. for(jj=ii+1; jj<nCell; jj++){
  122265. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  122266. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  122267. RtreeDValue waste = growth - right;
  122268. if( waste>fWaste ){
  122269. iLeftSeed = ii;
  122270. iRightSeed = jj;
  122271. fWaste = waste;
  122272. }
  122273. }
  122274. }
  122275. *piLeftSeed = iLeftSeed;
  122276. *piRightSeed = iRightSeed;
  122277. }
  122278. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  122279. /*
  122280. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  122281. ** nIdx. The aIdx array contains the set of integers from 0 to
  122282. ** (nIdx-1) in no particular order. This function sorts the values
  122283. ** in aIdx according to the indexed values in aDistance. For
  122284. ** example, assuming the inputs:
  122285. **
  122286. ** aIdx = { 0, 1, 2, 3 }
  122287. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  122288. **
  122289. ** this function sets the aIdx array to contain:
  122290. **
  122291. ** aIdx = { 0, 1, 2, 3 }
  122292. **
  122293. ** The aSpare array is used as temporary working space by the
  122294. ** sorting algorithm.
  122295. */
  122296. static void SortByDistance(
  122297. int *aIdx,
  122298. int nIdx,
  122299. RtreeDValue *aDistance,
  122300. int *aSpare
  122301. ){
  122302. if( nIdx>1 ){
  122303. int iLeft = 0;
  122304. int iRight = 0;
  122305. int nLeft = nIdx/2;
  122306. int nRight = nIdx-nLeft;
  122307. int *aLeft = aIdx;
  122308. int *aRight = &aIdx[nLeft];
  122309. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  122310. SortByDistance(aRight, nRight, aDistance, aSpare);
  122311. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  122312. aLeft = aSpare;
  122313. while( iLeft<nLeft || iRight<nRight ){
  122314. if( iLeft==nLeft ){
  122315. aIdx[iLeft+iRight] = aRight[iRight];
  122316. iRight++;
  122317. }else if( iRight==nRight ){
  122318. aIdx[iLeft+iRight] = aLeft[iLeft];
  122319. iLeft++;
  122320. }else{
  122321. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  122322. RtreeDValue fRight = aDistance[aRight[iRight]];
  122323. if( fLeft<fRight ){
  122324. aIdx[iLeft+iRight] = aLeft[iLeft];
  122325. iLeft++;
  122326. }else{
  122327. aIdx[iLeft+iRight] = aRight[iRight];
  122328. iRight++;
  122329. }
  122330. }
  122331. }
  122332. #if 0
  122333. /* Check that the sort worked */
  122334. {
  122335. int jj;
  122336. for(jj=1; jj<nIdx; jj++){
  122337. RtreeDValue left = aDistance[aIdx[jj-1]];
  122338. RtreeDValue right = aDistance[aIdx[jj]];
  122339. assert( left<=right );
  122340. }
  122341. }
  122342. #endif
  122343. }
  122344. }
  122345. /*
  122346. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  122347. ** nIdx. The aIdx array contains the set of integers from 0 to
  122348. ** (nIdx-1) in no particular order. This function sorts the values
  122349. ** in aIdx according to dimension iDim of the cells in aCell. The
  122350. ** minimum value of dimension iDim is considered first, the
  122351. ** maximum used to break ties.
  122352. **
  122353. ** The aSpare array is used as temporary working space by the
  122354. ** sorting algorithm.
  122355. */
  122356. static void SortByDimension(
  122357. Rtree *pRtree,
  122358. int *aIdx,
  122359. int nIdx,
  122360. int iDim,
  122361. RtreeCell *aCell,
  122362. int *aSpare
  122363. ){
  122364. if( nIdx>1 ){
  122365. int iLeft = 0;
  122366. int iRight = 0;
  122367. int nLeft = nIdx/2;
  122368. int nRight = nIdx-nLeft;
  122369. int *aLeft = aIdx;
  122370. int *aRight = &aIdx[nLeft];
  122371. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  122372. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  122373. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  122374. aLeft = aSpare;
  122375. while( iLeft<nLeft || iRight<nRight ){
  122376. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  122377. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  122378. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  122379. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  122380. if( (iLeft!=nLeft) && ((iRight==nRight)
  122381. || (xleft1<xright1)
  122382. || (xleft1==xright1 && xleft2<xright2)
  122383. )){
  122384. aIdx[iLeft+iRight] = aLeft[iLeft];
  122385. iLeft++;
  122386. }else{
  122387. aIdx[iLeft+iRight] = aRight[iRight];
  122388. iRight++;
  122389. }
  122390. }
  122391. #if 0
  122392. /* Check that the sort worked */
  122393. {
  122394. int jj;
  122395. for(jj=1; jj<nIdx; jj++){
  122396. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  122397. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  122398. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  122399. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  122400. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  122401. }
  122402. }
  122403. #endif
  122404. }
  122405. }
  122406. #if VARIANT_RSTARTREE_SPLIT
  122407. /*
  122408. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  122409. */
  122410. static int splitNodeStartree(
  122411. Rtree *pRtree,
  122412. RtreeCell *aCell,
  122413. int nCell,
  122414. RtreeNode *pLeft,
  122415. RtreeNode *pRight,
  122416. RtreeCell *pBboxLeft,
  122417. RtreeCell *pBboxRight
  122418. ){
  122419. int **aaSorted;
  122420. int *aSpare;
  122421. int ii;
  122422. int iBestDim = 0;
  122423. int iBestSplit = 0;
  122424. RtreeDValue fBestMargin = 0.0;
  122425. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  122426. aaSorted = (int **)sqlite3_malloc(nByte);
  122427. if( !aaSorted ){
  122428. return SQLITE_NOMEM;
  122429. }
  122430. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  122431. memset(aaSorted, 0, nByte);
  122432. for(ii=0; ii<pRtree->nDim; ii++){
  122433. int jj;
  122434. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  122435. for(jj=0; jj<nCell; jj++){
  122436. aaSorted[ii][jj] = jj;
  122437. }
  122438. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  122439. }
  122440. for(ii=0; ii<pRtree->nDim; ii++){
  122441. RtreeDValue margin = 0.0;
  122442. RtreeDValue fBestOverlap = 0.0;
  122443. RtreeDValue fBestArea = 0.0;
  122444. int iBestLeft = 0;
  122445. int nLeft;
  122446. for(
  122447. nLeft=RTREE_MINCELLS(pRtree);
  122448. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  122449. nLeft++
  122450. ){
  122451. RtreeCell left;
  122452. RtreeCell right;
  122453. int kk;
  122454. RtreeDValue overlap;
  122455. RtreeDValue area;
  122456. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  122457. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  122458. for(kk=1; kk<(nCell-1); kk++){
  122459. if( kk<nLeft ){
  122460. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  122461. }else{
  122462. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  122463. }
  122464. }
  122465. margin += cellMargin(pRtree, &left);
  122466. margin += cellMargin(pRtree, &right);
  122467. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  122468. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  122469. if( (nLeft==RTREE_MINCELLS(pRtree))
  122470. || (overlap<fBestOverlap)
  122471. || (overlap==fBestOverlap && area<fBestArea)
  122472. ){
  122473. iBestLeft = nLeft;
  122474. fBestOverlap = overlap;
  122475. fBestArea = area;
  122476. }
  122477. }
  122478. if( ii==0 || margin<fBestMargin ){
  122479. iBestDim = ii;
  122480. fBestMargin = margin;
  122481. iBestSplit = iBestLeft;
  122482. }
  122483. }
  122484. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  122485. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  122486. for(ii=0; ii<nCell; ii++){
  122487. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  122488. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  122489. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  122490. nodeInsertCell(pRtree, pTarget, pCell);
  122491. cellUnion(pRtree, pBbox, pCell);
  122492. }
  122493. sqlite3_free(aaSorted);
  122494. return SQLITE_OK;
  122495. }
  122496. #endif
  122497. #if VARIANT_GUTTMAN_SPLIT
  122498. /*
  122499. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  122500. */
  122501. static int splitNodeGuttman(
  122502. Rtree *pRtree,
  122503. RtreeCell *aCell,
  122504. int nCell,
  122505. RtreeNode *pLeft,
  122506. RtreeNode *pRight,
  122507. RtreeCell *pBboxLeft,
  122508. RtreeCell *pBboxRight
  122509. ){
  122510. int iLeftSeed = 0;
  122511. int iRightSeed = 1;
  122512. int *aiUsed;
  122513. int i;
  122514. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  122515. if( !aiUsed ){
  122516. return SQLITE_NOMEM;
  122517. }
  122518. memset(aiUsed, 0, sizeof(int)*nCell);
  122519. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  122520. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  122521. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  122522. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  122523. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  122524. aiUsed[iLeftSeed] = 1;
  122525. aiUsed[iRightSeed] = 1;
  122526. for(i=nCell-2; i>0; i--){
  122527. RtreeCell *pNext;
  122528. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  122529. RtreeDValue diff =
  122530. cellGrowth(pRtree, pBboxLeft, pNext) -
  122531. cellGrowth(pRtree, pBboxRight, pNext)
  122532. ;
  122533. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  122534. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  122535. ){
  122536. nodeInsertCell(pRtree, pRight, pNext);
  122537. cellUnion(pRtree, pBboxRight, pNext);
  122538. }else{
  122539. nodeInsertCell(pRtree, pLeft, pNext);
  122540. cellUnion(pRtree, pBboxLeft, pNext);
  122541. }
  122542. }
  122543. sqlite3_free(aiUsed);
  122544. return SQLITE_OK;
  122545. }
  122546. #endif
  122547. static int updateMapping(
  122548. Rtree *pRtree,
  122549. i64 iRowid,
  122550. RtreeNode *pNode,
  122551. int iHeight
  122552. ){
  122553. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  122554. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  122555. if( iHeight>0 ){
  122556. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  122557. if( pChild ){
  122558. nodeRelease(pRtree, pChild->pParent);
  122559. nodeReference(pNode);
  122560. pChild->pParent = pNode;
  122561. }
  122562. }
  122563. return xSetMapping(pRtree, iRowid, pNode->iNode);
  122564. }
  122565. static int SplitNode(
  122566. Rtree *pRtree,
  122567. RtreeNode *pNode,
  122568. RtreeCell *pCell,
  122569. int iHeight
  122570. ){
  122571. int i;
  122572. int newCellIsRight = 0;
  122573. int rc = SQLITE_OK;
  122574. int nCell = NCELL(pNode);
  122575. RtreeCell *aCell;
  122576. int *aiUsed;
  122577. RtreeNode *pLeft = 0;
  122578. RtreeNode *pRight = 0;
  122579. RtreeCell leftbbox;
  122580. RtreeCell rightbbox;
  122581. /* Allocate an array and populate it with a copy of pCell and
  122582. ** all cells from node pLeft. Then zero the original node.
  122583. */
  122584. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  122585. if( !aCell ){
  122586. rc = SQLITE_NOMEM;
  122587. goto splitnode_out;
  122588. }
  122589. aiUsed = (int *)&aCell[nCell+1];
  122590. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  122591. for(i=0; i<nCell; i++){
  122592. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  122593. }
  122594. nodeZero(pRtree, pNode);
  122595. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  122596. nCell++;
  122597. if( pNode->iNode==1 ){
  122598. pRight = nodeNew(pRtree, pNode);
  122599. pLeft = nodeNew(pRtree, pNode);
  122600. pRtree->iDepth++;
  122601. pNode->isDirty = 1;
  122602. writeInt16(pNode->zData, pRtree->iDepth);
  122603. }else{
  122604. pLeft = pNode;
  122605. pRight = nodeNew(pRtree, pLeft->pParent);
  122606. nodeReference(pLeft);
  122607. }
  122608. if( !pLeft || !pRight ){
  122609. rc = SQLITE_NOMEM;
  122610. goto splitnode_out;
  122611. }
  122612. memset(pLeft->zData, 0, pRtree->iNodeSize);
  122613. memset(pRight->zData, 0, pRtree->iNodeSize);
  122614. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  122615. if( rc!=SQLITE_OK ){
  122616. goto splitnode_out;
  122617. }
  122618. /* Ensure both child nodes have node numbers assigned to them by calling
  122619. ** nodeWrite(). Node pRight always needs a node number, as it was created
  122620. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  122621. ** In this case avoid the all to nodeWrite().
  122622. */
  122623. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  122624. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  122625. ){
  122626. goto splitnode_out;
  122627. }
  122628. rightbbox.iRowid = pRight->iNode;
  122629. leftbbox.iRowid = pLeft->iNode;
  122630. if( pNode->iNode==1 ){
  122631. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  122632. if( rc!=SQLITE_OK ){
  122633. goto splitnode_out;
  122634. }
  122635. }else{
  122636. RtreeNode *pParent = pLeft->pParent;
  122637. int iCell;
  122638. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  122639. if( rc==SQLITE_OK ){
  122640. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  122641. rc = AdjustTree(pRtree, pParent, &leftbbox);
  122642. }
  122643. if( rc!=SQLITE_OK ){
  122644. goto splitnode_out;
  122645. }
  122646. }
  122647. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  122648. goto splitnode_out;
  122649. }
  122650. for(i=0; i<NCELL(pRight); i++){
  122651. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  122652. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  122653. if( iRowid==pCell->iRowid ){
  122654. newCellIsRight = 1;
  122655. }
  122656. if( rc!=SQLITE_OK ){
  122657. goto splitnode_out;
  122658. }
  122659. }
  122660. if( pNode->iNode==1 ){
  122661. for(i=0; i<NCELL(pLeft); i++){
  122662. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  122663. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  122664. if( rc!=SQLITE_OK ){
  122665. goto splitnode_out;
  122666. }
  122667. }
  122668. }else if( newCellIsRight==0 ){
  122669. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  122670. }
  122671. if( rc==SQLITE_OK ){
  122672. rc = nodeRelease(pRtree, pRight);
  122673. pRight = 0;
  122674. }
  122675. if( rc==SQLITE_OK ){
  122676. rc = nodeRelease(pRtree, pLeft);
  122677. pLeft = 0;
  122678. }
  122679. splitnode_out:
  122680. nodeRelease(pRtree, pRight);
  122681. nodeRelease(pRtree, pLeft);
  122682. sqlite3_free(aCell);
  122683. return rc;
  122684. }
  122685. /*
  122686. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  122687. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  122688. ** the pLeaf->pParent chain all the way up to the root node.
  122689. **
  122690. ** This operation is required when a row is deleted (or updated - an update
  122691. ** is implemented as a delete followed by an insert). SQLite provides the
  122692. ** rowid of the row to delete, which can be used to find the leaf on which
  122693. ** the entry resides (argument pLeaf). Once the leaf is located, this
  122694. ** function is called to determine its ancestry.
  122695. */
  122696. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  122697. int rc = SQLITE_OK;
  122698. RtreeNode *pChild = pLeaf;
  122699. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  122700. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  122701. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  122702. rc = sqlite3_step(pRtree->pReadParent);
  122703. if( rc==SQLITE_ROW ){
  122704. RtreeNode *pTest; /* Used to test for reference loops */
  122705. i64 iNode; /* Node number of parent node */
  122706. /* Before setting pChild->pParent, test that we are not creating a
  122707. ** loop of references (as we would if, say, pChild==pParent). We don't
  122708. ** want to do this as it leads to a memory leak when trying to delete
  122709. ** the referenced counted node structures.
  122710. */
  122711. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  122712. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  122713. if( !pTest ){
  122714. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  122715. }
  122716. }
  122717. rc = sqlite3_reset(pRtree->pReadParent);
  122718. if( rc==SQLITE_OK ) rc = rc2;
  122719. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  122720. pChild = pChild->pParent;
  122721. }
  122722. return rc;
  122723. }
  122724. static int deleteCell(Rtree *, RtreeNode *, int, int);
  122725. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  122726. int rc;
  122727. int rc2;
  122728. RtreeNode *pParent = 0;
  122729. int iCell;
  122730. assert( pNode->nRef==1 );
  122731. /* Remove the entry in the parent cell. */
  122732. rc = nodeParentIndex(pRtree, pNode, &iCell);
  122733. if( rc==SQLITE_OK ){
  122734. pParent = pNode->pParent;
  122735. pNode->pParent = 0;
  122736. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  122737. }
  122738. rc2 = nodeRelease(pRtree, pParent);
  122739. if( rc==SQLITE_OK ){
  122740. rc = rc2;
  122741. }
  122742. if( rc!=SQLITE_OK ){
  122743. return rc;
  122744. }
  122745. /* Remove the xxx_node entry. */
  122746. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  122747. sqlite3_step(pRtree->pDeleteNode);
  122748. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  122749. return rc;
  122750. }
  122751. /* Remove the xxx_parent entry. */
  122752. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  122753. sqlite3_step(pRtree->pDeleteParent);
  122754. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  122755. return rc;
  122756. }
  122757. /* Remove the node from the in-memory hash table and link it into
  122758. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  122759. */
  122760. nodeHashDelete(pRtree, pNode);
  122761. pNode->iNode = iHeight;
  122762. pNode->pNext = pRtree->pDeleted;
  122763. pNode->nRef++;
  122764. pRtree->pDeleted = pNode;
  122765. return SQLITE_OK;
  122766. }
  122767. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  122768. RtreeNode *pParent = pNode->pParent;
  122769. int rc = SQLITE_OK;
  122770. if( pParent ){
  122771. int ii;
  122772. int nCell = NCELL(pNode);
  122773. RtreeCell box; /* Bounding box for pNode */
  122774. nodeGetCell(pRtree, pNode, 0, &box);
  122775. for(ii=1; ii<nCell; ii++){
  122776. RtreeCell cell;
  122777. nodeGetCell(pRtree, pNode, ii, &cell);
  122778. cellUnion(pRtree, &box, &cell);
  122779. }
  122780. box.iRowid = pNode->iNode;
  122781. rc = nodeParentIndex(pRtree, pNode, &ii);
  122782. if( rc==SQLITE_OK ){
  122783. nodeOverwriteCell(pRtree, pParent, &box, ii);
  122784. rc = fixBoundingBox(pRtree, pParent);
  122785. }
  122786. }
  122787. return rc;
  122788. }
  122789. /*
  122790. ** Delete the cell at index iCell of node pNode. After removing the
  122791. ** cell, adjust the r-tree data structure if required.
  122792. */
  122793. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  122794. RtreeNode *pParent;
  122795. int rc;
  122796. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  122797. return rc;
  122798. }
  122799. /* Remove the cell from the node. This call just moves bytes around
  122800. ** the in-memory node image, so it cannot fail.
  122801. */
  122802. nodeDeleteCell(pRtree, pNode, iCell);
  122803. /* If the node is not the tree root and now has less than the minimum
  122804. ** number of cells, remove it from the tree. Otherwise, update the
  122805. ** cell in the parent node so that it tightly contains the updated
  122806. ** node.
  122807. */
  122808. pParent = pNode->pParent;
  122809. assert( pParent || pNode->iNode==1 );
  122810. if( pParent ){
  122811. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  122812. rc = removeNode(pRtree, pNode, iHeight);
  122813. }else{
  122814. rc = fixBoundingBox(pRtree, pNode);
  122815. }
  122816. }
  122817. return rc;
  122818. }
  122819. static int Reinsert(
  122820. Rtree *pRtree,
  122821. RtreeNode *pNode,
  122822. RtreeCell *pCell,
  122823. int iHeight
  122824. ){
  122825. int *aOrder;
  122826. int *aSpare;
  122827. RtreeCell *aCell;
  122828. RtreeDValue *aDistance;
  122829. int nCell;
  122830. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  122831. int iDim;
  122832. int ii;
  122833. int rc = SQLITE_OK;
  122834. int n;
  122835. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  122836. nCell = NCELL(pNode)+1;
  122837. n = (nCell+1)&(~1);
  122838. /* Allocate the buffers used by this operation. The allocation is
  122839. ** relinquished before this function returns.
  122840. */
  122841. aCell = (RtreeCell *)sqlite3_malloc(n * (
  122842. sizeof(RtreeCell) + /* aCell array */
  122843. sizeof(int) + /* aOrder array */
  122844. sizeof(int) + /* aSpare array */
  122845. sizeof(RtreeDValue) /* aDistance array */
  122846. ));
  122847. if( !aCell ){
  122848. return SQLITE_NOMEM;
  122849. }
  122850. aOrder = (int *)&aCell[n];
  122851. aSpare = (int *)&aOrder[n];
  122852. aDistance = (RtreeDValue *)&aSpare[n];
  122853. for(ii=0; ii<nCell; ii++){
  122854. if( ii==(nCell-1) ){
  122855. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  122856. }else{
  122857. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  122858. }
  122859. aOrder[ii] = ii;
  122860. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122861. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  122862. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  122863. }
  122864. }
  122865. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122866. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  122867. }
  122868. for(ii=0; ii<nCell; ii++){
  122869. aDistance[ii] = 0.0;
  122870. for(iDim=0; iDim<pRtree->nDim; iDim++){
  122871. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  122872. DCOORD(aCell[ii].aCoord[iDim*2]));
  122873. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  122874. }
  122875. }
  122876. SortByDistance(aOrder, nCell, aDistance, aSpare);
  122877. nodeZero(pRtree, pNode);
  122878. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  122879. RtreeCell *p = &aCell[aOrder[ii]];
  122880. nodeInsertCell(pRtree, pNode, p);
  122881. if( p->iRowid==pCell->iRowid ){
  122882. if( iHeight==0 ){
  122883. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  122884. }else{
  122885. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  122886. }
  122887. }
  122888. }
  122889. if( rc==SQLITE_OK ){
  122890. rc = fixBoundingBox(pRtree, pNode);
  122891. }
  122892. for(; rc==SQLITE_OK && ii<nCell; ii++){
  122893. /* Find a node to store this cell in. pNode->iNode currently contains
  122894. ** the height of the sub-tree headed by the cell.
  122895. */
  122896. RtreeNode *pInsert;
  122897. RtreeCell *p = &aCell[aOrder[ii]];
  122898. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  122899. if( rc==SQLITE_OK ){
  122900. int rc2;
  122901. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  122902. rc2 = nodeRelease(pRtree, pInsert);
  122903. if( rc==SQLITE_OK ){
  122904. rc = rc2;
  122905. }
  122906. }
  122907. }
  122908. sqlite3_free(aCell);
  122909. return rc;
  122910. }
  122911. /*
  122912. ** Insert cell pCell into node pNode. Node pNode is the head of a
  122913. ** subtree iHeight high (leaf nodes have iHeight==0).
  122914. */
  122915. static int rtreeInsertCell(
  122916. Rtree *pRtree,
  122917. RtreeNode *pNode,
  122918. RtreeCell *pCell,
  122919. int iHeight
  122920. ){
  122921. int rc = SQLITE_OK;
  122922. if( iHeight>0 ){
  122923. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  122924. if( pChild ){
  122925. nodeRelease(pRtree, pChild->pParent);
  122926. nodeReference(pNode);
  122927. pChild->pParent = pNode;
  122928. }
  122929. }
  122930. if( nodeInsertCell(pRtree, pNode, pCell) ){
  122931. #if VARIANT_RSTARTREE_REINSERT
  122932. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  122933. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  122934. }else{
  122935. pRtree->iReinsertHeight = iHeight;
  122936. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  122937. }
  122938. #else
  122939. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  122940. #endif
  122941. }else{
  122942. rc = AdjustTree(pRtree, pNode, pCell);
  122943. if( rc==SQLITE_OK ){
  122944. if( iHeight==0 ){
  122945. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  122946. }else{
  122947. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  122948. }
  122949. }
  122950. }
  122951. return rc;
  122952. }
  122953. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  122954. int ii;
  122955. int rc = SQLITE_OK;
  122956. int nCell = NCELL(pNode);
  122957. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  122958. RtreeNode *pInsert;
  122959. RtreeCell cell;
  122960. nodeGetCell(pRtree, pNode, ii, &cell);
  122961. /* Find a node to store this cell in. pNode->iNode currently contains
  122962. ** the height of the sub-tree headed by the cell.
  122963. */
  122964. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  122965. if( rc==SQLITE_OK ){
  122966. int rc2;
  122967. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  122968. rc2 = nodeRelease(pRtree, pInsert);
  122969. if( rc==SQLITE_OK ){
  122970. rc = rc2;
  122971. }
  122972. }
  122973. }
  122974. return rc;
  122975. }
  122976. /*
  122977. ** Select a currently unused rowid for a new r-tree record.
  122978. */
  122979. static int newRowid(Rtree *pRtree, i64 *piRowid){
  122980. int rc;
  122981. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  122982. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  122983. sqlite3_step(pRtree->pWriteRowid);
  122984. rc = sqlite3_reset(pRtree->pWriteRowid);
  122985. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  122986. return rc;
  122987. }
  122988. /*
  122989. ** Remove the entry with rowid=iDelete from the r-tree structure.
  122990. */
  122991. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  122992. int rc; /* Return code */
  122993. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  122994. int iCell; /* Index of iDelete cell in pLeaf */
  122995. RtreeNode *pRoot; /* Root node of rtree structure */
  122996. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  122997. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  122998. /* Obtain a reference to the leaf node that contains the entry
  122999. ** about to be deleted.
  123000. */
  123001. if( rc==SQLITE_OK ){
  123002. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  123003. }
  123004. /* Delete the cell in question from the leaf node. */
  123005. if( rc==SQLITE_OK ){
  123006. int rc2;
  123007. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  123008. if( rc==SQLITE_OK ){
  123009. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  123010. }
  123011. rc2 = nodeRelease(pRtree, pLeaf);
  123012. if( rc==SQLITE_OK ){
  123013. rc = rc2;
  123014. }
  123015. }
  123016. /* Delete the corresponding entry in the <rtree>_rowid table. */
  123017. if( rc==SQLITE_OK ){
  123018. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  123019. sqlite3_step(pRtree->pDeleteRowid);
  123020. rc = sqlite3_reset(pRtree->pDeleteRowid);
  123021. }
  123022. /* Check if the root node now has exactly one child. If so, remove
  123023. ** it, schedule the contents of the child for reinsertion and
  123024. ** reduce the tree height by one.
  123025. **
  123026. ** This is equivalent to copying the contents of the child into
  123027. ** the root node (the operation that Gutman's paper says to perform
  123028. ** in this scenario).
  123029. */
  123030. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  123031. int rc2;
  123032. RtreeNode *pChild;
  123033. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  123034. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  123035. if( rc==SQLITE_OK ){
  123036. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  123037. }
  123038. rc2 = nodeRelease(pRtree, pChild);
  123039. if( rc==SQLITE_OK ) rc = rc2;
  123040. if( rc==SQLITE_OK ){
  123041. pRtree->iDepth--;
  123042. writeInt16(pRoot->zData, pRtree->iDepth);
  123043. pRoot->isDirty = 1;
  123044. }
  123045. }
  123046. /* Re-insert the contents of any underfull nodes removed from the tree. */
  123047. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  123048. if( rc==SQLITE_OK ){
  123049. rc = reinsertNodeContent(pRtree, pLeaf);
  123050. }
  123051. pRtree->pDeleted = pLeaf->pNext;
  123052. sqlite3_free(pLeaf);
  123053. }
  123054. /* Release the reference to the root node. */
  123055. if( rc==SQLITE_OK ){
  123056. rc = nodeRelease(pRtree, pRoot);
  123057. }else{
  123058. nodeRelease(pRtree, pRoot);
  123059. }
  123060. return rc;
  123061. }
  123062. /*
  123063. ** Rounding constants for float->double conversion.
  123064. */
  123065. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  123066. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  123067. #if !defined(SQLITE_RTREE_INT_ONLY)
  123068. /*
  123069. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  123070. ** while taking care to round toward negative or positive, respectively.
  123071. */
  123072. static RtreeValue rtreeValueDown(sqlite3_value *v){
  123073. double d = sqlite3_value_double(v);
  123074. float f = (float)d;
  123075. if( f>d ){
  123076. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  123077. }
  123078. return f;
  123079. }
  123080. static RtreeValue rtreeValueUp(sqlite3_value *v){
  123081. double d = sqlite3_value_double(v);
  123082. float f = (float)d;
  123083. if( f<d ){
  123084. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  123085. }
  123086. return f;
  123087. }
  123088. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  123089. /*
  123090. ** The xUpdate method for rtree module virtual tables.
  123091. */
  123092. static int rtreeUpdate(
  123093. sqlite3_vtab *pVtab,
  123094. int nData,
  123095. sqlite3_value **azData,
  123096. sqlite_int64 *pRowid
  123097. ){
  123098. Rtree *pRtree = (Rtree *)pVtab;
  123099. int rc = SQLITE_OK;
  123100. RtreeCell cell; /* New cell to insert if nData>1 */
  123101. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  123102. rtreeReference(pRtree);
  123103. assert(nData>=1);
  123104. /* Constraint handling. A write operation on an r-tree table may return
  123105. ** SQLITE_CONSTRAINT for two reasons:
  123106. **
  123107. ** 1. A duplicate rowid value, or
  123108. ** 2. The supplied data violates the "x2>=x1" constraint.
  123109. **
  123110. ** In the first case, if the conflict-handling mode is REPLACE, then
  123111. ** the conflicting row can be removed before proceeding. In the second
  123112. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  123113. ** conflict-handling mode specified by the user.
  123114. */
  123115. if( nData>1 ){
  123116. int ii;
  123117. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  123118. assert( nData==(pRtree->nDim*2 + 3) );
  123119. #ifndef SQLITE_RTREE_INT_ONLY
  123120. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  123121. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  123122. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  123123. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  123124. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  123125. rc = SQLITE_CONSTRAINT;
  123126. goto constraint;
  123127. }
  123128. }
  123129. }else
  123130. #endif
  123131. {
  123132. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  123133. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  123134. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  123135. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  123136. rc = SQLITE_CONSTRAINT;
  123137. goto constraint;
  123138. }
  123139. }
  123140. }
  123141. /* If a rowid value was supplied, check if it is already present in
  123142. ** the table. If so, the constraint has failed. */
  123143. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  123144. cell.iRowid = sqlite3_value_int64(azData[2]);
  123145. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  123146. || sqlite3_value_int64(azData[0])!=cell.iRowid
  123147. ){
  123148. int steprc;
  123149. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  123150. steprc = sqlite3_step(pRtree->pReadRowid);
  123151. rc = sqlite3_reset(pRtree->pReadRowid);
  123152. if( SQLITE_ROW==steprc ){
  123153. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  123154. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  123155. }else{
  123156. rc = SQLITE_CONSTRAINT;
  123157. goto constraint;
  123158. }
  123159. }
  123160. }
  123161. bHaveRowid = 1;
  123162. }
  123163. }
  123164. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  123165. ** record to delete from the r-tree table. The following block does
  123166. ** just that.
  123167. */
  123168. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  123169. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  123170. }
  123171. /* If the azData[] array contains more than one element, elements
  123172. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  123173. ** the r-tree structure.
  123174. */
  123175. if( rc==SQLITE_OK && nData>1 ){
  123176. /* Insert the new record into the r-tree */
  123177. RtreeNode *pLeaf = 0;
  123178. /* Figure out the rowid of the new row. */
  123179. if( bHaveRowid==0 ){
  123180. rc = newRowid(pRtree, &cell.iRowid);
  123181. }
  123182. *pRowid = cell.iRowid;
  123183. if( rc==SQLITE_OK ){
  123184. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  123185. }
  123186. if( rc==SQLITE_OK ){
  123187. int rc2;
  123188. pRtree->iReinsertHeight = -1;
  123189. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  123190. rc2 = nodeRelease(pRtree, pLeaf);
  123191. if( rc==SQLITE_OK ){
  123192. rc = rc2;
  123193. }
  123194. }
  123195. }
  123196. constraint:
  123197. rtreeRelease(pRtree);
  123198. return rc;
  123199. }
  123200. /*
  123201. ** The xRename method for rtree module virtual tables.
  123202. */
  123203. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  123204. Rtree *pRtree = (Rtree *)pVtab;
  123205. int rc = SQLITE_NOMEM;
  123206. char *zSql = sqlite3_mprintf(
  123207. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  123208. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  123209. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  123210. , pRtree->zDb, pRtree->zName, zNewName
  123211. , pRtree->zDb, pRtree->zName, zNewName
  123212. , pRtree->zDb, pRtree->zName, zNewName
  123213. );
  123214. if( zSql ){
  123215. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  123216. sqlite3_free(zSql);
  123217. }
  123218. return rc;
  123219. }
  123220. static sqlite3_module rtreeModule = {
  123221. 0, /* iVersion */
  123222. rtreeCreate, /* xCreate - create a table */
  123223. rtreeConnect, /* xConnect - connect to an existing table */
  123224. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  123225. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  123226. rtreeDestroy, /* xDestroy - Drop a table */
  123227. rtreeOpen, /* xOpen - open a cursor */
  123228. rtreeClose, /* xClose - close a cursor */
  123229. rtreeFilter, /* xFilter - configure scan constraints */
  123230. rtreeNext, /* xNext - advance a cursor */
  123231. rtreeEof, /* xEof */
  123232. rtreeColumn, /* xColumn - read data */
  123233. rtreeRowid, /* xRowid - read data */
  123234. rtreeUpdate, /* xUpdate - write data */
  123235. 0, /* xBegin - begin transaction */
  123236. 0, /* xSync - sync transaction */
  123237. 0, /* xCommit - commit transaction */
  123238. 0, /* xRollback - rollback transaction */
  123239. 0, /* xFindFunction - function overloading */
  123240. rtreeRename, /* xRename - rename the table */
  123241. 0, /* xSavepoint */
  123242. 0, /* xRelease */
  123243. 0 /* xRollbackTo */
  123244. };
  123245. static int rtreeSqlInit(
  123246. Rtree *pRtree,
  123247. sqlite3 *db,
  123248. const char *zDb,
  123249. const char *zPrefix,
  123250. int isCreate
  123251. ){
  123252. int rc = SQLITE_OK;
  123253. #define N_STATEMENT 9
  123254. static const char *azSql[N_STATEMENT] = {
  123255. /* Read and write the xxx_node table */
  123256. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  123257. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  123258. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  123259. /* Read and write the xxx_rowid table */
  123260. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  123261. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  123262. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  123263. /* Read and write the xxx_parent table */
  123264. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  123265. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  123266. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  123267. };
  123268. sqlite3_stmt **appStmt[N_STATEMENT];
  123269. int i;
  123270. pRtree->db = db;
  123271. if( isCreate ){
  123272. char *zCreate = sqlite3_mprintf(
  123273. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  123274. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  123275. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  123276. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  123277. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  123278. );
  123279. if( !zCreate ){
  123280. return SQLITE_NOMEM;
  123281. }
  123282. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  123283. sqlite3_free(zCreate);
  123284. if( rc!=SQLITE_OK ){
  123285. return rc;
  123286. }
  123287. }
  123288. appStmt[0] = &pRtree->pReadNode;
  123289. appStmt[1] = &pRtree->pWriteNode;
  123290. appStmt[2] = &pRtree->pDeleteNode;
  123291. appStmt[3] = &pRtree->pReadRowid;
  123292. appStmt[4] = &pRtree->pWriteRowid;
  123293. appStmt[5] = &pRtree->pDeleteRowid;
  123294. appStmt[6] = &pRtree->pReadParent;
  123295. appStmt[7] = &pRtree->pWriteParent;
  123296. appStmt[8] = &pRtree->pDeleteParent;
  123297. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  123298. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  123299. if( zSql ){
  123300. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  123301. }else{
  123302. rc = SQLITE_NOMEM;
  123303. }
  123304. sqlite3_free(zSql);
  123305. }
  123306. return rc;
  123307. }
  123308. /*
  123309. ** The second argument to this function contains the text of an SQL statement
  123310. ** that returns a single integer value. The statement is compiled and executed
  123311. ** using database connection db. If successful, the integer value returned
  123312. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  123313. ** code is returned and the value of *piVal after returning is not defined.
  123314. */
  123315. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  123316. int rc = SQLITE_NOMEM;
  123317. if( zSql ){
  123318. sqlite3_stmt *pStmt = 0;
  123319. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  123320. if( rc==SQLITE_OK ){
  123321. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  123322. *piVal = sqlite3_column_int(pStmt, 0);
  123323. }
  123324. rc = sqlite3_finalize(pStmt);
  123325. }
  123326. }
  123327. return rc;
  123328. }
  123329. /*
  123330. ** This function is called from within the xConnect() or xCreate() method to
  123331. ** determine the node-size used by the rtree table being created or connected
  123332. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  123333. ** Otherwise, an SQLite error code is returned.
  123334. **
  123335. ** If this function is being called as part of an xConnect(), then the rtree
  123336. ** table already exists. In this case the node-size is determined by inspecting
  123337. ** the root node of the tree.
  123338. **
  123339. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  123340. ** This ensures that each node is stored on a single database page. If the
  123341. ** database page-size is so large that more than RTREE_MAXCELLS entries
  123342. ** would fit in a single node, use a smaller node-size.
  123343. */
  123344. static int getNodeSize(
  123345. sqlite3 *db, /* Database handle */
  123346. Rtree *pRtree, /* Rtree handle */
  123347. int isCreate, /* True for xCreate, false for xConnect */
  123348. char **pzErr /* OUT: Error message, if any */
  123349. ){
  123350. int rc;
  123351. char *zSql;
  123352. if( isCreate ){
  123353. int iPageSize = 0;
  123354. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  123355. rc = getIntFromStmt(db, zSql, &iPageSize);
  123356. if( rc==SQLITE_OK ){
  123357. pRtree->iNodeSize = iPageSize-64;
  123358. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  123359. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  123360. }
  123361. }else{
  123362. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123363. }
  123364. }else{
  123365. zSql = sqlite3_mprintf(
  123366. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  123367. pRtree->zDb, pRtree->zName
  123368. );
  123369. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  123370. if( rc!=SQLITE_OK ){
  123371. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123372. }
  123373. }
  123374. sqlite3_free(zSql);
  123375. return rc;
  123376. }
  123377. /*
  123378. ** This function is the implementation of both the xConnect and xCreate
  123379. ** methods of the r-tree virtual table.
  123380. **
  123381. ** argv[0] -> module name
  123382. ** argv[1] -> database name
  123383. ** argv[2] -> table name
  123384. ** argv[...] -> column names...
  123385. */
  123386. static int rtreeInit(
  123387. sqlite3 *db, /* Database connection */
  123388. void *pAux, /* One of the RTREE_COORD_* constants */
  123389. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  123390. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  123391. char **pzErr, /* OUT: Error message, if any */
  123392. int isCreate /* True for xCreate, false for xConnect */
  123393. ){
  123394. int rc = SQLITE_OK;
  123395. Rtree *pRtree;
  123396. int nDb; /* Length of string argv[1] */
  123397. int nName; /* Length of string argv[2] */
  123398. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  123399. const char *aErrMsg[] = {
  123400. 0, /* 0 */
  123401. "Wrong number of columns for an rtree table", /* 1 */
  123402. "Too few columns for an rtree table", /* 2 */
  123403. "Too many columns for an rtree table" /* 3 */
  123404. };
  123405. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  123406. if( aErrMsg[iErr] ){
  123407. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  123408. return SQLITE_ERROR;
  123409. }
  123410. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  123411. /* Allocate the sqlite3_vtab structure */
  123412. nDb = (int)strlen(argv[1]);
  123413. nName = (int)strlen(argv[2]);
  123414. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  123415. if( !pRtree ){
  123416. return SQLITE_NOMEM;
  123417. }
  123418. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  123419. pRtree->nBusy = 1;
  123420. pRtree->base.pModule = &rtreeModule;
  123421. pRtree->zDb = (char *)&pRtree[1];
  123422. pRtree->zName = &pRtree->zDb[nDb+1];
  123423. pRtree->nDim = (argc-4)/2;
  123424. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  123425. pRtree->eCoordType = eCoordType;
  123426. memcpy(pRtree->zDb, argv[1], nDb);
  123427. memcpy(pRtree->zName, argv[2], nName);
  123428. /* Figure out the node size to use. */
  123429. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  123430. /* Create/Connect to the underlying relational database schema. If
  123431. ** that is successful, call sqlite3_declare_vtab() to configure
  123432. ** the r-tree table schema.
  123433. */
  123434. if( rc==SQLITE_OK ){
  123435. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  123436. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123437. }else{
  123438. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  123439. char *zTmp;
  123440. int ii;
  123441. for(ii=4; zSql && ii<argc; ii++){
  123442. zTmp = zSql;
  123443. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  123444. sqlite3_free(zTmp);
  123445. }
  123446. if( zSql ){
  123447. zTmp = zSql;
  123448. zSql = sqlite3_mprintf("%s);", zTmp);
  123449. sqlite3_free(zTmp);
  123450. }
  123451. if( !zSql ){
  123452. rc = SQLITE_NOMEM;
  123453. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  123454. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  123455. }
  123456. sqlite3_free(zSql);
  123457. }
  123458. }
  123459. if( rc==SQLITE_OK ){
  123460. *ppVtab = (sqlite3_vtab *)pRtree;
  123461. }else{
  123462. rtreeRelease(pRtree);
  123463. }
  123464. return rc;
  123465. }
  123466. /*
  123467. ** Implementation of a scalar function that decodes r-tree nodes to
  123468. ** human readable strings. This can be used for debugging and analysis.
  123469. **
  123470. ** The scalar function takes two arguments, a blob of data containing
  123471. ** an r-tree node, and the number of dimensions the r-tree indexes.
  123472. ** For a two-dimensional r-tree structure called "rt", to deserialize
  123473. ** all nodes, a statement like:
  123474. **
  123475. ** SELECT rtreenode(2, data) FROM rt_node;
  123476. **
  123477. ** The human readable string takes the form of a Tcl list with one
  123478. ** entry for each cell in the r-tree node. Each entry is itself a
  123479. ** list, containing the 8-byte rowid/pageno followed by the
  123480. ** <num-dimension>*2 coordinates.
  123481. */
  123482. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  123483. char *zText = 0;
  123484. RtreeNode node;
  123485. Rtree tree;
  123486. int ii;
  123487. UNUSED_PARAMETER(nArg);
  123488. memset(&node, 0, sizeof(RtreeNode));
  123489. memset(&tree, 0, sizeof(Rtree));
  123490. tree.nDim = sqlite3_value_int(apArg[0]);
  123491. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  123492. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  123493. for(ii=0; ii<NCELL(&node); ii++){
  123494. char zCell[512];
  123495. int nCell = 0;
  123496. RtreeCell cell;
  123497. int jj;
  123498. nodeGetCell(&tree, &node, ii, &cell);
  123499. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  123500. nCell = (int)strlen(zCell);
  123501. for(jj=0; jj<tree.nDim*2; jj++){
  123502. #ifndef SQLITE_RTREE_INT_ONLY
  123503. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  123504. (double)cell.aCoord[jj].f);
  123505. #else
  123506. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  123507. cell.aCoord[jj].i);
  123508. #endif
  123509. nCell = (int)strlen(zCell);
  123510. }
  123511. if( zText ){
  123512. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  123513. sqlite3_free(zText);
  123514. zText = zTextNew;
  123515. }else{
  123516. zText = sqlite3_mprintf("{%s}", zCell);
  123517. }
  123518. }
  123519. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  123520. }
  123521. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  123522. UNUSED_PARAMETER(nArg);
  123523. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  123524. || sqlite3_value_bytes(apArg[0])<2
  123525. ){
  123526. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  123527. }else{
  123528. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  123529. sqlite3_result_int(ctx, readInt16(zBlob));
  123530. }
  123531. }
  123532. /*
  123533. ** Register the r-tree module with database handle db. This creates the
  123534. ** virtual table module "rtree" and the debugging/analysis scalar
  123535. ** function "rtreenode".
  123536. */
  123537. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  123538. const int utf8 = SQLITE_UTF8;
  123539. int rc;
  123540. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  123541. if( rc==SQLITE_OK ){
  123542. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  123543. }
  123544. if( rc==SQLITE_OK ){
  123545. #ifdef SQLITE_RTREE_INT_ONLY
  123546. void *c = (void *)RTREE_COORD_INT32;
  123547. #else
  123548. void *c = (void *)RTREE_COORD_REAL32;
  123549. #endif
  123550. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  123551. }
  123552. if( rc==SQLITE_OK ){
  123553. void *c = (void *)RTREE_COORD_INT32;
  123554. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  123555. }
  123556. return rc;
  123557. }
  123558. /*
  123559. ** A version of sqlite3_free() that can be used as a callback. This is used
  123560. ** in two places - as the destructor for the blob value returned by the
  123561. ** invocation of a geometry function, and as the destructor for the geometry
  123562. ** functions themselves.
  123563. */
  123564. static void doSqlite3Free(void *p){
  123565. sqlite3_free(p);
  123566. }
  123567. /*
  123568. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  123569. ** scalar user function. This C function is the callback used for all such
  123570. ** registered SQL functions.
  123571. **
  123572. ** The scalar user functions return a blob that is interpreted by r-tree
  123573. ** table MATCH operators.
  123574. */
  123575. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  123576. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  123577. RtreeMatchArg *pBlob;
  123578. int nBlob;
  123579. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  123580. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  123581. if( !pBlob ){
  123582. sqlite3_result_error_nomem(ctx);
  123583. }else{
  123584. int i;
  123585. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  123586. pBlob->xGeom = pGeomCtx->xGeom;
  123587. pBlob->pContext = pGeomCtx->pContext;
  123588. pBlob->nParam = nArg;
  123589. for(i=0; i<nArg; i++){
  123590. #ifdef SQLITE_RTREE_INT_ONLY
  123591. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  123592. #else
  123593. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  123594. #endif
  123595. }
  123596. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  123597. }
  123598. }
  123599. /*
  123600. ** Register a new geometry function for use with the r-tree MATCH operator.
  123601. */
  123602. SQLITE_API int sqlite3_rtree_geometry_callback(
  123603. sqlite3 *db,
  123604. const char *zGeom,
  123605. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  123606. void *pContext
  123607. ){
  123608. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  123609. /* Allocate and populate the context object. */
  123610. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  123611. if( !pGeomCtx ) return SQLITE_NOMEM;
  123612. pGeomCtx->xGeom = xGeom;
  123613. pGeomCtx->pContext = pContext;
  123614. /* Create the new user-function. Register a destructor function to delete
  123615. ** the context object when it is no longer required. */
  123616. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  123617. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  123618. );
  123619. }
  123620. #if !SQLITE_CORE
  123621. #ifdef _WIN32
  123622. __declspec(dllexport)
  123623. #endif
  123624. SQLITE_API int sqlite3_rtree_init(
  123625. sqlite3 *db,
  123626. char **pzErrMsg,
  123627. const sqlite3_api_routines *pApi
  123628. ){
  123629. SQLITE_EXTENSION_INIT2(pApi)
  123630. return sqlite3RtreeInit(db);
  123631. }
  123632. #endif
  123633. #endif
  123634. /************** End of rtree.c ***********************************************/
  123635. /************** Begin file icu.c *********************************************/
  123636. /*
  123637. ** 2007 May 6
  123638. **
  123639. ** The author disclaims copyright to this source code. In place of
  123640. ** a legal notice, here is a blessing:
  123641. **
  123642. ** May you do good and not evil.
  123643. ** May you find forgiveness for yourself and forgive others.
  123644. ** May you share freely, never taking more than you give.
  123645. **
  123646. *************************************************************************
  123647. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  123648. **
  123649. ** This file implements an integration between the ICU library
  123650. ** ("International Components for Unicode", an open-source library
  123651. ** for handling unicode data) and SQLite. The integration uses
  123652. ** ICU to provide the following to SQLite:
  123653. **
  123654. ** * An implementation of the SQL regexp() function (and hence REGEXP
  123655. ** operator) using the ICU uregex_XX() APIs.
  123656. **
  123657. ** * Implementations of the SQL scalar upper() and lower() functions
  123658. ** for case mapping.
  123659. **
  123660. ** * Integration of ICU and SQLite collation sequences.
  123661. **
  123662. ** * An implementation of the LIKE operator that uses ICU to
  123663. ** provide case-independent matching.
  123664. */
  123665. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  123666. /* Include ICU headers */
  123667. #include <unicode/utypes.h>
  123668. #include <unicode/uregex.h>
  123669. #include <unicode/ustring.h>
  123670. #include <unicode/ucol.h>
  123671. /* #include <assert.h> */
  123672. #ifndef SQLITE_CORE
  123673. SQLITE_EXTENSION_INIT1
  123674. #else
  123675. #endif
  123676. /*
  123677. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  123678. ** operator.
  123679. */
  123680. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  123681. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  123682. #endif
  123683. /*
  123684. ** Version of sqlite3_free() that is always a function, never a macro.
  123685. */
  123686. static void xFree(void *p){
  123687. sqlite3_free(p);
  123688. }
  123689. /*
  123690. ** Compare two UTF-8 strings for equality where the first string is
  123691. ** a "LIKE" expression. Return true (1) if they are the same and
  123692. ** false (0) if they are different.
  123693. */
  123694. static int icuLikeCompare(
  123695. const uint8_t *zPattern, /* LIKE pattern */
  123696. const uint8_t *zString, /* The UTF-8 string to compare against */
  123697. const UChar32 uEsc /* The escape character */
  123698. ){
  123699. static const int MATCH_ONE = (UChar32)'_';
  123700. static const int MATCH_ALL = (UChar32)'%';
  123701. int iPattern = 0; /* Current byte index in zPattern */
  123702. int iString = 0; /* Current byte index in zString */
  123703. int prevEscape = 0; /* True if the previous character was uEsc */
  123704. while( zPattern[iPattern]!=0 ){
  123705. /* Read (and consume) the next character from the input pattern. */
  123706. UChar32 uPattern;
  123707. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  123708. assert(uPattern!=0);
  123709. /* There are now 4 possibilities:
  123710. **
  123711. ** 1. uPattern is an unescaped match-all character "%",
  123712. ** 2. uPattern is an unescaped match-one character "_",
  123713. ** 3. uPattern is an unescaped escape character, or
  123714. ** 4. uPattern is to be handled as an ordinary character
  123715. */
  123716. if( !prevEscape && uPattern==MATCH_ALL ){
  123717. /* Case 1. */
  123718. uint8_t c;
  123719. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  123720. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  123721. ** test string.
  123722. */
  123723. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  123724. if( c==MATCH_ONE ){
  123725. if( zString[iString]==0 ) return 0;
  123726. U8_FWD_1_UNSAFE(zString, iString);
  123727. }
  123728. iPattern++;
  123729. }
  123730. if( zPattern[iPattern]==0 ) return 1;
  123731. while( zString[iString] ){
  123732. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  123733. return 1;
  123734. }
  123735. U8_FWD_1_UNSAFE(zString, iString);
  123736. }
  123737. return 0;
  123738. }else if( !prevEscape && uPattern==MATCH_ONE ){
  123739. /* Case 2. */
  123740. if( zString[iString]==0 ) return 0;
  123741. U8_FWD_1_UNSAFE(zString, iString);
  123742. }else if( !prevEscape && uPattern==uEsc){
  123743. /* Case 3. */
  123744. prevEscape = 1;
  123745. }else{
  123746. /* Case 4. */
  123747. UChar32 uString;
  123748. U8_NEXT_UNSAFE(zString, iString, uString);
  123749. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  123750. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  123751. if( uString!=uPattern ){
  123752. return 0;
  123753. }
  123754. prevEscape = 0;
  123755. }
  123756. }
  123757. return zString[iString]==0;
  123758. }
  123759. /*
  123760. ** Implementation of the like() SQL function. This function implements
  123761. ** the build-in LIKE operator. The first argument to the function is the
  123762. ** pattern and the second argument is the string. So, the SQL statements:
  123763. **
  123764. ** A LIKE B
  123765. **
  123766. ** is implemented as like(B, A). If there is an escape character E,
  123767. **
  123768. ** A LIKE B ESCAPE E
  123769. **
  123770. ** is mapped to like(B, A, E).
  123771. */
  123772. static void icuLikeFunc(
  123773. sqlite3_context *context,
  123774. int argc,
  123775. sqlite3_value **argv
  123776. ){
  123777. const unsigned char *zA = sqlite3_value_text(argv[0]);
  123778. const unsigned char *zB = sqlite3_value_text(argv[1]);
  123779. UChar32 uEsc = 0;
  123780. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  123781. ** of deep recursion and N*N behavior in patternCompare().
  123782. */
  123783. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  123784. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  123785. return;
  123786. }
  123787. if( argc==3 ){
  123788. /* The escape character string must consist of a single UTF-8 character.
  123789. ** Otherwise, return an error.
  123790. */
  123791. int nE= sqlite3_value_bytes(argv[2]);
  123792. const unsigned char *zE = sqlite3_value_text(argv[2]);
  123793. int i = 0;
  123794. if( zE==0 ) return;
  123795. U8_NEXT(zE, i, nE, uEsc);
  123796. if( i!=nE){
  123797. sqlite3_result_error(context,
  123798. "ESCAPE expression must be a single character", -1);
  123799. return;
  123800. }
  123801. }
  123802. if( zA && zB ){
  123803. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  123804. }
  123805. }
  123806. /*
  123807. ** This function is called when an ICU function called from within
  123808. ** the implementation of an SQL scalar function returns an error.
  123809. **
  123810. ** The scalar function context passed as the first argument is
  123811. ** loaded with an error message based on the following two args.
  123812. */
  123813. static void icuFunctionError(
  123814. sqlite3_context *pCtx, /* SQLite scalar function context */
  123815. const char *zName, /* Name of ICU function that failed */
  123816. UErrorCode e /* Error code returned by ICU function */
  123817. ){
  123818. char zBuf[128];
  123819. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  123820. zBuf[127] = '\0';
  123821. sqlite3_result_error(pCtx, zBuf, -1);
  123822. }
  123823. /*
  123824. ** Function to delete compiled regexp objects. Registered as
  123825. ** a destructor function with sqlite3_set_auxdata().
  123826. */
  123827. static void icuRegexpDelete(void *p){
  123828. URegularExpression *pExpr = (URegularExpression *)p;
  123829. uregex_close(pExpr);
  123830. }
  123831. /*
  123832. ** Implementation of SQLite REGEXP operator. This scalar function takes
  123833. ** two arguments. The first is a regular expression pattern to compile
  123834. ** the second is a string to match against that pattern. If either
  123835. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  123836. ** is 1 if the string matches the pattern, or 0 otherwise.
  123837. **
  123838. ** SQLite maps the regexp() function to the regexp() operator such
  123839. ** that the following two are equivalent:
  123840. **
  123841. ** zString REGEXP zPattern
  123842. ** regexp(zPattern, zString)
  123843. **
  123844. ** Uses the following ICU regexp APIs:
  123845. **
  123846. ** uregex_open()
  123847. ** uregex_matches()
  123848. ** uregex_close()
  123849. */
  123850. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  123851. UErrorCode status = U_ZERO_ERROR;
  123852. URegularExpression *pExpr;
  123853. UBool res;
  123854. const UChar *zString = sqlite3_value_text16(apArg[1]);
  123855. (void)nArg; /* Unused parameter */
  123856. /* If the left hand side of the regexp operator is NULL,
  123857. ** then the result is also NULL.
  123858. */
  123859. if( !zString ){
  123860. return;
  123861. }
  123862. pExpr = sqlite3_get_auxdata(p, 0);
  123863. if( !pExpr ){
  123864. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  123865. if( !zPattern ){
  123866. return;
  123867. }
  123868. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  123869. if( U_SUCCESS(status) ){
  123870. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  123871. }else{
  123872. assert(!pExpr);
  123873. icuFunctionError(p, "uregex_open", status);
  123874. return;
  123875. }
  123876. }
  123877. /* Configure the text that the regular expression operates on. */
  123878. uregex_setText(pExpr, zString, -1, &status);
  123879. if( !U_SUCCESS(status) ){
  123880. icuFunctionError(p, "uregex_setText", status);
  123881. return;
  123882. }
  123883. /* Attempt the match */
  123884. res = uregex_matches(pExpr, 0, &status);
  123885. if( !U_SUCCESS(status) ){
  123886. icuFunctionError(p, "uregex_matches", status);
  123887. return;
  123888. }
  123889. /* Set the text that the regular expression operates on to a NULL
  123890. ** pointer. This is not really necessary, but it is tidier than
  123891. ** leaving the regular expression object configured with an invalid
  123892. ** pointer after this function returns.
  123893. */
  123894. uregex_setText(pExpr, 0, 0, &status);
  123895. /* Return 1 or 0. */
  123896. sqlite3_result_int(p, res ? 1 : 0);
  123897. }
  123898. /*
  123899. ** Implementations of scalar functions for case mapping - upper() and
  123900. ** lower(). Function upper() converts its input to upper-case (ABC).
  123901. ** Function lower() converts to lower-case (abc).
  123902. **
  123903. ** ICU provides two types of case mapping, "general" case mapping and
  123904. ** "language specific". Refer to ICU documentation for the differences
  123905. ** between the two.
  123906. **
  123907. ** To utilise "general" case mapping, the upper() or lower() scalar
  123908. ** functions are invoked with one argument:
  123909. **
  123910. ** upper('ABC') -> 'abc'
  123911. ** lower('abc') -> 'ABC'
  123912. **
  123913. ** To access ICU "language specific" case mapping, upper() or lower()
  123914. ** should be invoked with two arguments. The second argument is the name
  123915. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  123916. ** as the second argument is the same as invoking the 1 argument version
  123917. ** of upper() or lower().
  123918. **
  123919. ** lower('I', 'en_us') -> 'i'
  123920. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  123921. **
  123922. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  123923. */
  123924. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  123925. const UChar *zInput;
  123926. UChar *zOutput;
  123927. int nInput;
  123928. int nOutput;
  123929. UErrorCode status = U_ZERO_ERROR;
  123930. const char *zLocale = 0;
  123931. assert(nArg==1 || nArg==2);
  123932. if( nArg==2 ){
  123933. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  123934. }
  123935. zInput = sqlite3_value_text16(apArg[0]);
  123936. if( !zInput ){
  123937. return;
  123938. }
  123939. nInput = sqlite3_value_bytes16(apArg[0]);
  123940. nOutput = nInput * 2 + 2;
  123941. zOutput = sqlite3_malloc(nOutput);
  123942. if( !zOutput ){
  123943. return;
  123944. }
  123945. if( sqlite3_user_data(p) ){
  123946. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  123947. }else{
  123948. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  123949. }
  123950. if( !U_SUCCESS(status) ){
  123951. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  123952. return;
  123953. }
  123954. sqlite3_result_text16(p, zOutput, -1, xFree);
  123955. }
  123956. /*
  123957. ** Collation sequence destructor function. The pCtx argument points to
  123958. ** a UCollator structure previously allocated using ucol_open().
  123959. */
  123960. static void icuCollationDel(void *pCtx){
  123961. UCollator *p = (UCollator *)pCtx;
  123962. ucol_close(p);
  123963. }
  123964. /*
  123965. ** Collation sequence comparison function. The pCtx argument points to
  123966. ** a UCollator structure previously allocated using ucol_open().
  123967. */
  123968. static int icuCollationColl(
  123969. void *pCtx,
  123970. int nLeft,
  123971. const void *zLeft,
  123972. int nRight,
  123973. const void *zRight
  123974. ){
  123975. UCollationResult res;
  123976. UCollator *p = (UCollator *)pCtx;
  123977. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  123978. switch( res ){
  123979. case UCOL_LESS: return -1;
  123980. case UCOL_GREATER: return +1;
  123981. case UCOL_EQUAL: return 0;
  123982. }
  123983. assert(!"Unexpected return value from ucol_strcoll()");
  123984. return 0;
  123985. }
  123986. /*
  123987. ** Implementation of the scalar function icu_load_collation().
  123988. **
  123989. ** This scalar function is used to add ICU collation based collation
  123990. ** types to an SQLite database connection. It is intended to be called
  123991. ** as follows:
  123992. **
  123993. ** SELECT icu_load_collation(<locale>, <collation-name>);
  123994. **
  123995. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  123996. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  123997. ** collation sequence to create.
  123998. */
  123999. static void icuLoadCollation(
  124000. sqlite3_context *p,
  124001. int nArg,
  124002. sqlite3_value **apArg
  124003. ){
  124004. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  124005. UErrorCode status = U_ZERO_ERROR;
  124006. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  124007. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  124008. UCollator *pUCollator; /* ICU library collation object */
  124009. int rc; /* Return code from sqlite3_create_collation_x() */
  124010. assert(nArg==2);
  124011. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  124012. zName = (const char *)sqlite3_value_text(apArg[1]);
  124013. if( !zLocale || !zName ){
  124014. return;
  124015. }
  124016. pUCollator = ucol_open(zLocale, &status);
  124017. if( !U_SUCCESS(status) ){
  124018. icuFunctionError(p, "ucol_open", status);
  124019. return;
  124020. }
  124021. assert(p);
  124022. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  124023. icuCollationColl, icuCollationDel
  124024. );
  124025. if( rc!=SQLITE_OK ){
  124026. ucol_close(pUCollator);
  124027. sqlite3_result_error(p, "Error registering collation function", -1);
  124028. }
  124029. }
  124030. /*
  124031. ** Register the ICU extension functions with database db.
  124032. */
  124033. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  124034. struct IcuScalar {
  124035. const char *zName; /* Function name */
  124036. int nArg; /* Number of arguments */
  124037. int enc; /* Optimal text encoding */
  124038. void *pContext; /* sqlite3_user_data() context */
  124039. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  124040. } scalars[] = {
  124041. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  124042. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  124043. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  124044. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  124045. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  124046. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  124047. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  124048. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  124049. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  124050. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  124051. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  124052. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  124053. };
  124054. int rc = SQLITE_OK;
  124055. int i;
  124056. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  124057. struct IcuScalar *p = &scalars[i];
  124058. rc = sqlite3_create_function(
  124059. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  124060. );
  124061. }
  124062. return rc;
  124063. }
  124064. #if !SQLITE_CORE
  124065. #ifdef _WIN32
  124066. __declspec(dllexport)
  124067. #endif
  124068. SQLITE_API int sqlite3_icu_init(
  124069. sqlite3 *db,
  124070. char **pzErrMsg,
  124071. const sqlite3_api_routines *pApi
  124072. ){
  124073. SQLITE_EXTENSION_INIT2(pApi)
  124074. return sqlite3IcuInit(db);
  124075. }
  124076. #endif
  124077. #endif
  124078. /************** End of icu.c *************************************************/
  124079. /************** Begin file fts3_icu.c ****************************************/
  124080. /*
  124081. ** 2007 June 22
  124082. **
  124083. ** The author disclaims copyright to this source code. In place of
  124084. ** a legal notice, here is a blessing:
  124085. **
  124086. ** May you do good and not evil.
  124087. ** May you find forgiveness for yourself and forgive others.
  124088. ** May you share freely, never taking more than you give.
  124089. **
  124090. *************************************************************************
  124091. ** This file implements a tokenizer for fts3 based on the ICU library.
  124092. */
  124093. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124094. #ifdef SQLITE_ENABLE_ICU
  124095. /* #include <assert.h> */
  124096. /* #include <string.h> */
  124097. #include <unicode/ubrk.h>
  124098. /* #include <unicode/ucol.h> */
  124099. /* #include <unicode/ustring.h> */
  124100. #include <unicode/utf16.h>
  124101. typedef struct IcuTokenizer IcuTokenizer;
  124102. typedef struct IcuCursor IcuCursor;
  124103. struct IcuTokenizer {
  124104. sqlite3_tokenizer base;
  124105. char *zLocale;
  124106. };
  124107. struct IcuCursor {
  124108. sqlite3_tokenizer_cursor base;
  124109. UBreakIterator *pIter; /* ICU break-iterator object */
  124110. int nChar; /* Number of UChar elements in pInput */
  124111. UChar *aChar; /* Copy of input using utf-16 encoding */
  124112. int *aOffset; /* Offsets of each character in utf-8 input */
  124113. int nBuffer;
  124114. char *zBuffer;
  124115. int iToken;
  124116. };
  124117. /*
  124118. ** Create a new tokenizer instance.
  124119. */
  124120. static int icuCreate(
  124121. int argc, /* Number of entries in argv[] */
  124122. const char * const *argv, /* Tokenizer creation arguments */
  124123. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  124124. ){
  124125. IcuTokenizer *p;
  124126. int n = 0;
  124127. if( argc>0 ){
  124128. n = strlen(argv[0])+1;
  124129. }
  124130. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  124131. if( !p ){
  124132. return SQLITE_NOMEM;
  124133. }
  124134. memset(p, 0, sizeof(IcuTokenizer));
  124135. if( n ){
  124136. p->zLocale = (char *)&p[1];
  124137. memcpy(p->zLocale, argv[0], n);
  124138. }
  124139. *ppTokenizer = (sqlite3_tokenizer *)p;
  124140. return SQLITE_OK;
  124141. }
  124142. /*
  124143. ** Destroy a tokenizer
  124144. */
  124145. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  124146. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  124147. sqlite3_free(p);
  124148. return SQLITE_OK;
  124149. }
  124150. /*
  124151. ** Prepare to begin tokenizing a particular string. The input
  124152. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  124153. ** used to incrementally tokenize this string is returned in
  124154. ** *ppCursor.
  124155. */
  124156. static int icuOpen(
  124157. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  124158. const char *zInput, /* Input string */
  124159. int nInput, /* Length of zInput in bytes */
  124160. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  124161. ){
  124162. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  124163. IcuCursor *pCsr;
  124164. const int32_t opt = U_FOLD_CASE_DEFAULT;
  124165. UErrorCode status = U_ZERO_ERROR;
  124166. int nChar;
  124167. UChar32 c;
  124168. int iInput = 0;
  124169. int iOut = 0;
  124170. *ppCursor = 0;
  124171. if( zInput==0 ){
  124172. nInput = 0;
  124173. zInput = "";
  124174. }else if( nInput<0 ){
  124175. nInput = strlen(zInput);
  124176. }
  124177. nChar = nInput+1;
  124178. pCsr = (IcuCursor *)sqlite3_malloc(
  124179. sizeof(IcuCursor) + /* IcuCursor */
  124180. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  124181. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  124182. );
  124183. if( !pCsr ){
  124184. return SQLITE_NOMEM;
  124185. }
  124186. memset(pCsr, 0, sizeof(IcuCursor));
  124187. pCsr->aChar = (UChar *)&pCsr[1];
  124188. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  124189. pCsr->aOffset[iOut] = iInput;
  124190. U8_NEXT(zInput, iInput, nInput, c);
  124191. while( c>0 ){
  124192. int isError = 0;
  124193. c = u_foldCase(c, opt);
  124194. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  124195. if( isError ){
  124196. sqlite3_free(pCsr);
  124197. return SQLITE_ERROR;
  124198. }
  124199. pCsr->aOffset[iOut] = iInput;
  124200. if( iInput<nInput ){
  124201. U8_NEXT(zInput, iInput, nInput, c);
  124202. }else{
  124203. c = 0;
  124204. }
  124205. }
  124206. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  124207. if( !U_SUCCESS(status) ){
  124208. sqlite3_free(pCsr);
  124209. return SQLITE_ERROR;
  124210. }
  124211. pCsr->nChar = iOut;
  124212. ubrk_first(pCsr->pIter);
  124213. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  124214. return SQLITE_OK;
  124215. }
  124216. /*
  124217. ** Close a tokenization cursor previously opened by a call to icuOpen().
  124218. */
  124219. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  124220. IcuCursor *pCsr = (IcuCursor *)pCursor;
  124221. ubrk_close(pCsr->pIter);
  124222. sqlite3_free(pCsr->zBuffer);
  124223. sqlite3_free(pCsr);
  124224. return SQLITE_OK;
  124225. }
  124226. /*
  124227. ** Extract the next token from a tokenization cursor.
  124228. */
  124229. static int icuNext(
  124230. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  124231. const char **ppToken, /* OUT: *ppToken is the token text */
  124232. int *pnBytes, /* OUT: Number of bytes in token */
  124233. int *piStartOffset, /* OUT: Starting offset of token */
  124234. int *piEndOffset, /* OUT: Ending offset of token */
  124235. int *piPosition /* OUT: Position integer of token */
  124236. ){
  124237. IcuCursor *pCsr = (IcuCursor *)pCursor;
  124238. int iStart = 0;
  124239. int iEnd = 0;
  124240. int nByte = 0;
  124241. while( iStart==iEnd ){
  124242. UChar32 c;
  124243. iStart = ubrk_current(pCsr->pIter);
  124244. iEnd = ubrk_next(pCsr->pIter);
  124245. if( iEnd==UBRK_DONE ){
  124246. return SQLITE_DONE;
  124247. }
  124248. while( iStart<iEnd ){
  124249. int iWhite = iStart;
  124250. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  124251. if( u_isspace(c) ){
  124252. iStart = iWhite;
  124253. }else{
  124254. break;
  124255. }
  124256. }
  124257. assert(iStart<=iEnd);
  124258. }
  124259. do {
  124260. UErrorCode status = U_ZERO_ERROR;
  124261. if( nByte ){
  124262. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  124263. if( !zNew ){
  124264. return SQLITE_NOMEM;
  124265. }
  124266. pCsr->zBuffer = zNew;
  124267. pCsr->nBuffer = nByte;
  124268. }
  124269. u_strToUTF8(
  124270. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  124271. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  124272. &status /* Output success/failure */
  124273. );
  124274. } while( nByte>pCsr->nBuffer );
  124275. *ppToken = pCsr->zBuffer;
  124276. *pnBytes = nByte;
  124277. *piStartOffset = pCsr->aOffset[iStart];
  124278. *piEndOffset = pCsr->aOffset[iEnd];
  124279. *piPosition = pCsr->iToken++;
  124280. return SQLITE_OK;
  124281. }
  124282. /*
  124283. ** The set of routines that implement the simple tokenizer
  124284. */
  124285. static const sqlite3_tokenizer_module icuTokenizerModule = {
  124286. 0, /* iVersion */
  124287. icuCreate, /* xCreate */
  124288. icuDestroy, /* xCreate */
  124289. icuOpen, /* xOpen */
  124290. icuClose, /* xClose */
  124291. icuNext, /* xNext */
  124292. };
  124293. /*
  124294. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  124295. */
  124296. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  124297. sqlite3_tokenizer_module const**ppModule
  124298. ){
  124299. *ppModule = &icuTokenizerModule;
  124300. }
  124301. #endif /* defined(SQLITE_ENABLE_ICU) */
  124302. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124303. /************** End of fts3_icu.c ********************************************/